问:
I want to update the text inside a TextFormField when I change the item in a DropDownButton in Flutter
I have a dropDownButton populated with a query from my database here I have the users, when I select an item I want to show all the user info in the TextFields below.

Since some of the information should not be edited by hand, I wanted to make some of the fields as containers, so I can't write in them, but some fields should be a TextField so I can edit them. I'm new to flutter so I still don't understand this at full, and I can't find a way to load the info in the TextFields when I change the dropDownButton.

here is the code below:

```<code>class UtilizadorPage extends StatefulWidget {
  @override
  _UtilizadorPageState createState() => new _UtilizadorPageState();
}

class _UtilizadorPageState extends State<UtilizadorPage> {
  Utilizador user = Utilizador();
  BDLocal db = BDLocal.instance;
  Utilizador? _currentUser;
  var txt = TextEditingController();

  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Utilizadores",
        ),
      ),
      body: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FutureBuilder<List<Utilizador>>(
                  future: user.getUtilizadores(),
                  builder: (BuildContext context,
                      AsyncSnapshot<List<Utilizador>> snapshot){
                        if (!snapshot.hasData) return CircularProgressIndicator();
                        return DropdownButton<Utilizador>(
                          alignment: Alignment.center,
                          items: snapshot.data?.map((util) => DropdownMenuItem<Utilizador>(
                            child: Text(util.nome),
                            value: util,
                          )).toList(),
                          onChanged:(Utilizador? value) {
                          setState(() {
                            _currentUser = value;
                          });
                        },
                    isExpanded: false,
                    //value: _currentUser,
                    hint: Text('Select User'),
                    );
                  }),
            ]
          ),
          SizedBox(height: 20.0),
          Row(
            children: [
              _currentUser != null
                  ? Expanded(
                child: Column(
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Expanded(
                            flex: 1,
                            child: Container(
                              child: InputDecorator(
                                decoration: InputDecoration(
                                labelText: "Nome",
                                floatingLabelBehavior:FloatingLabelBehavior.always,
                                border: OutlineInputBorder(),
                              ),
                                  child: Text(_currentUser!.nome)
                              ),
                            ),
                          ),
                          SizedBox(width: 10.0),
                          Expanded(
                            flex: 1,
                            child: Container(
                              child: InputDecorator(
                                  decoration: InputDecoration(
                                    labelText: "ID na BDNuvem",
                                    floatingLabelBehavior:FloatingLabelBehavior.always,
                                    border: OutlineInputBorder(),
                                  ),
                                  child: Text(_currentUser!.id_BDNuvem.toString())
                              ),
                            ),
                          ),
                        ]),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: TextFormField(
                            initialValue: _currentUser!.perfil.toString(),
                            decoration: InputDecoration(
                              label: Text("Perfil"),
                              floatingLabelBehavior:FloatingLabelBehavior.always,
                              border: OutlineInputBorder(),
                            ),
                          ),
                        ),
                        SizedBox(width: 10.0),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Numero de Colaborador",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.numero.toString())
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Nome do Funcionario",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.nomeFuncionario)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Email",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.email)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Senha",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.senha)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Ultima Atualizacao",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.ultimaAtualizacao)
                            ),
                          ),
                        ),
                        SizedBox(width: 10.0),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Atualizado Por",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.atualizadoPor)
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              )
                  : Text("No User selected"),
            ],
          )
        ],
      ),
    );
  }
}
</code>```

I only have one textField now because I'm still experimenting things.
what I wanted to do is update the value of the text with the info I retrieved from the query for example: _currentUser!.perfil.toString(), which holds a string that represent the type of user

答:
If you've assigned a TextEditingController to Textfield you can simply manipulate value in by</p>
```<code>myTextEditingController.text = "new value";
</code>```

Body:
I have a dropDownButton populated with a query from my database here I have the users, when I select an item I want to show all the user info in the TextFields below.

Since some of the information should not be edited by hand, I wanted to make some of the fields as containers, so I can't write in them, but some fields should be a TextField so I can edit them. I'm new to flutter so I still don't understand this at full, and I can't find a way to load the info in the TextFields when I change the dropDownButton.

here is the code below:

class UtilizadorPage extends StatefulWidget {
  @override
  _UtilizadorPageState createState() => new _UtilizadorPageState();
}

class _UtilizadorPageState extends State<UtilizadorPage> {
  Utilizador user = Utilizador();
  BDLocal db = BDLocal.instance;
  Utilizador? _currentUser;
  var txt = TextEditingController();

  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Utilizadores",
        ),
      ),
      body: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FutureBuilder<List<Utilizador>>(
                  future: user.getUtilizadores(),
                  builder: (BuildContext context,
                      AsyncSnapshot<List<Utilizador>> snapshot){
                        if (!snapshot.hasData) return CircularProgressIndicator();
                        return DropdownButton<Utilizador>(
                          alignment: Alignment.center,
                          items: snapshot.data?.map((util) => DropdownMenuItem<Utilizador>(
                            child: Text(util.nome),
                            value: util,
                          )).toList(),
                          onChanged:(Utilizador? value) {
                          setState(() {
                            _currentUser = value;
                          });
                        },
                    isExpanded: false,
                    //value: _currentUser,
                    hint: Text('Select User'),
                    );
                  }),
            ]
          ),
          SizedBox(height: 20.0),
          Row(
            children: [
              _currentUser != null
                  ? Expanded(
                child: Column(
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Expanded(
                            flex: 1,
                            child: Container(
                              child: InputDecorator(
                                decoration: InputDecoration(
                                labelText: "Nome",
                                floatingLabelBehavior:FloatingLabelBehavior.always,
                                border: OutlineInputBorder(),
                              ),
                                  child: Text(_currentUser!.nome)
                              ),
                            ),
                          ),
                          SizedBox(width: 10.0),
                          Expanded(
                            flex: 1,
                            child: Container(
                              child: InputDecorator(
                                  decoration: InputDecoration(
                                    labelText: "ID na BDNuvem",
                                    floatingLabelBehavior:FloatingLabelBehavior.always,
                                    border: OutlineInputBorder(),
                                  ),
                                  child: Text(_currentUser!.id_BDNuvem.toString())
                              ),
                            ),
                          ),
                        ]),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: TextFormField(
                            initialValue: _currentUser!.perfil.toString(),
                            decoration: InputDecoration(
                              label: Text("Perfil"),
                              floatingLabelBehavior:FloatingLabelBehavior.always,
                              border: OutlineInputBorder(),
                            ),
                          ),
                        ),
                        SizedBox(width: 10.0),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Numero de Colaborador",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.numero.toString())
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Nome do Funcionario",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.nomeFuncionario)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Email",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.email)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Senha",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.senha)
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Ultima Atualizacao",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.ultimaAtualizacao)
                            ),
                          ),
                        ),
                        SizedBox(width: 10.0),
                        Expanded(
                          flex: 1,
                          child: Container(
                            child: InputDecorator(
                                decoration: InputDecoration(
                                  labelText: "Atualizado Por",
                                  floatingLabelBehavior:FloatingLabelBehavior.always,
                                  border: OutlineInputBorder(),
                                ),
                                child: Text(_currentUser!.atualizadoPor)
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              )
                  : Text("No User selected"),
            ],
          )
        ],
      ),
    );
  }
}

I only have one textField now because I'm still experimenting things.
what I wanted to do is update the value of the text with the info I retrieved from the query for example: _currentUser!.perfil.toString(), which holds a string that represent the type of user

Body:
If you've assigned a TextEditingController to Textfield you can simply manipulate value in by

myTextEditingController.text = "new value";


来源: stackexchange

问:
Calling a method of Runnable object doesn't affect objects outside of it JAVA
Given the code bellow, I Create two objects and ask the Swapper to swap between them.
Therefore the outcome should look like this:

```<code>1, 2
2, 1
</code>```

but it appears to not work, and the outcome is two lines of "1,2".

The example we were given did swap between them, with the only difference of using an object that has a "get, set" function for the data inside it.

Is this not working because of the "set, get" functions not present, or would this not work either way?

```<code> public static void main(String[] args) throws InterruptedException {
    StringBuffer _i1 , _i2;
    _i1 = new StringBuffer("1");
    _i2 = new StringBuffer("2");
    Thread t = new Thread(new Swapper(_i1, _i2));
    System.out.println(_i1 + ", " + _i2);
    System.out.println(_i1 + ", " + _i2);
    t.start();
    t.join();
    System.out.println(_i1 + ", " + _i2);
   }
}
class Swapper<Static> implements  Runnable {
StringBuffer _i1 , _i2;
Swapper(StringBuffer i1, StringBuffer i2) { _i1 = i1; _i2=i2;}
public void run(){
    synchronized (_i1){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (_i2){
            StringBuffer tmp = _i1;
            _i1 = _i2;
            _i2 = tmp;
        }
    }
}
</code>```

答:
Your logic is correct however there is an error in the scope.
There are _i1 & _i2 in both main(){} scope and Swapper{} scope.

The changed values of _i1 & _i2 in main scope are not assigned from the calculations.
Instead, try printing the values under Swapper class, after swapping the variables.

ContentLicense: CC BY-SA 4.0

Body:
Given the code bellow, I Create two objects and ask the Swapper to swap between them.
Therefore the outcome should look like this:

1, 2
2, 1

but it appears to not work, and the outcome is two lines of "1,2".

The example we were given did swap between them, with the only difference of using an object that has a "get, set" function for the data inside it.

Is this not working because of the "set, get" functions not present, or would this not work either way?

 public static void main(String[] args) throws InterruptedException {
    StringBuffer _i1 , _i2;
    _i1 = new StringBuffer("1");
    _i2 = new StringBuffer("2");
    Thread t = new Thread(new Swapper(_i1, _i2));
    System.out.println(_i1 + ", " + _i2);
    System.out.println(_i1 + ", " + _i2);
    t.start();
    t.join();
    System.out.println(_i1 + ", " + _i2);
   }
}
class Swapper<Static> implements  Runnable {
StringBuffer _i1 , _i2;
Swapper(StringBuffer i1, StringBuffer i2) { _i1 = i1; _i2=i2;}
public void run(){
    synchronized (_i1){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (_i2){
            StringBuffer tmp = _i1;
            _i1 = _i2;
            _i2 = tmp;
        }
    }
}


问:
Rewriting depreciated php class call to Twig_Environment
So I was running into this error in one of our old Page.php files after upgrading our version of Twig in our terribly dated web apps.

```<code>Error : Class 'Twig_Environment' not found
</code>```

According to this Github post, you can't use non-namespaced classes anymore.

The original code snippet looks like this:

```<code>    /* TWIG */
    $loader = new Twig_Loader_Filesystem(TEMPLATE_PATH);
    $twig = Twig_Environment($loader, array(
        'cache' => false
    ));
</code>```

Could I please get some help properly updating this use the class in my Twig/ directory without throwing a darn hissy fit?

I've been experimenting with defining the Twig path in our config file(forgive the messy directory):

```<code>define("TWIG_PATH", dirname($_SERVER["SCRIPT_FILENAME"])."/vendor/twig/twig/lib/Twig/");
</code>```

Then in my Page.php file I tried using Twig::Environment and \Twig\Environment instead of Twig_Environment with no luck.

I also tried explicitly writing the path in the header require TWIG_PATH."Environment.php";

It just throws a PHP Fatal error:  Uncaught Error: Class 'Twig' not found

I'm being a dingus somewhere here, and could really use another set of eyes on it. I'm also not a Twig expert, so I'm basically tackling these depreciation errors as they pop up.

I understand using namespaces properly is a really common question, but I know Twig s more of a niche package, so I figured anyone in the future running into my issues could use this post as a resource.

Edit: I may have answered my own formatting question by finding Twig's API documentation: https://twig.symfony.com/doc/3.x/api.html

Will update post if this works.

Edit 2: So I have the error changing now. It supposedly can find the file directory I gave it, but is now spitting out:

```<code> PHP Fatal error:  Cannot declare class Twig_Loader_Filesystem, because the name is already used in...
</code>```

Well I'm at a loss at this point. Even following the Twig documentation it isn't being happy. I want to use the class, not declare again.

答:
The answer to my own question was silly, but easy to overlook.

The newest version of Twig can't use non-namespaced function calls.

So to properly fix it, I had to use an explicit file path.

```<code>require_once ROOT_PATH."/vendor/twig/twig/lib/Twig/Loader/Filesystem.php";
</code>```

Note that your mileage may vary depending on how your file structure is organized. Additionally, you can clean up your files by using these namespace definitions in your global config file.

So my PHP file is properly "talking" with all of the Twig classes I need. My webapp still isn't working, and is now throwing a PHP Fatal error:  Uncaught TypeError, but in the scope of my original question, I've answered it.

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
So I was running into this error in one of our old Page.php files after upgrading our version of Twig in our terribly dated web apps.

Error : Class 'Twig_Environment' not found

According to this Github post, you can't use non-namespaced classes anymore.

The original code snippet looks like this:

    /* TWIG */
    $loader = new Twig_Loader_Filesystem(TEMPLATE_PATH);
    $twig = Twig_Environment($loader, array(
        'cache' => false
    ));

Could I please get some help properly updating this use the class in my Twig/ directory without throwing a darn hissy fit?

I've been experimenting with defining the Twig path in our config file(forgive the messy directory):

define("TWIG_PATH", dirname($_SERVER["SCRIPT_FILENAME"])."/vendor/twig/twig/lib/Twig/");

Then in my Page.php file I tried using Twig::Environment and \Twig\Environment instead of Twig_Environment with no luck.

I also tried explicitly writing the path in the header require TWIG_PATH."Environment.php";

It just throws a PHP Fatal error:  Uncaught Error: Class 'Twig' not found

I'm being a dingus somewhere here, and could really use another set of eyes on it. I'm also not a Twig expert, so I'm basically tackling these depreciation errors as they pop up.

I understand using namespaces properly is a really common question, but I know Twig s more of a niche package, so I figured anyone in the future running into my issues could use this post as a resource.

Edit: I may have answered my own formatting question by finding Twig's API documentation: https://twig.symfony.com/doc/3.x/api.html

Will update post if this works.

Edit 2: So I have the error changing now. It supposedly can find the file directory I gave it, but is now spitting out:

 PHP Fatal error:  Cannot declare class Twig_Loader_Filesystem, because the name is already used in...

Well I'm at a loss at this point. Even following the Twig documentation it isn't being happy. I want to use the class, not declare again.

Body:
The answer to my own question was silly, but easy to overlook.

The newest version of Twig can't use non-namespaced function calls.

So to properly fix it, I had to use an explicit file path.

require_once ROOT_PATH."/vendor/twig/twig/lib/Twig/Loader/Filesystem.php";

Note that your mileage may vary depending on how your file structure is organized. Additionally, you can clean up your files by using these namespace definitions in your global config file.

So my PHP file is properly "talking" with all of the Twig classes I need. My webapp still isn't working, and is now throwing a PHP Fatal error:  Uncaught TypeError, but in the scope of my original question, I've answered it.


问:
Which Linux distribution has the most active/recent Ruby support?
I have installed Ubuntu 11.04 and tried to install Ruby as apt-get install ruby. The default version in repositories was 1.8.7, okay, install 1.9.2 manually. Then I'm going for rubygems, download tar file, install rubygems, try to install something with them, zlib-mistake appeared. Found the solution with rvm, didn't help. Now I'm stuck with broken gem command and useless rvm installed.

The question is - which Linux distribution is the most friendly for a Ruby beginner?

答:
Many ruby developers use Ubuntu with rvm. The benefit is that you can install multiple versions and switching them is easy.

Furthermore there are many tutorials and help on errors for rvm.

I would suggest to install a VM and copy it, then and try rvm. If you cripple your system just use the copy again until you setup your system correctly.

Once you know your way around you can install ruby on your system or just stick with the VM like many other do.

On the other hand many server use Debian, wich is slightly different than Ubuntu as it uses older stable packages.

ContentLicense: CC BY-SA 3.0


问:
How to convert multiple columns into single column in snowflake table using query
I have a table "TABLE1" like below

```<code>Date        src_counrty  src_State   dst_country    dst_state   Value
2022-02-09       a           d           x             y          1
2022-02-09       a           e           x             y          1
2022-02-09       c           f           x             y          1
</code>```

I want to have output table as below using a select statement

```<code>Date         src    dst   Value
2022-02-09    a      x      1
2022-02-09    a      x      1
2022-02-09    c      x      1
2022-02-09    d      y      1
2022-02-09    e      y      1
2022-02-09    f      y      1
2022-02-09    a      y      1
2022-02-09    a      y      1
2022-02-09    c      y      1
2022-02-09    d      x      1
2022-02-09    e      x      1
2022-02-09    f      x      1
</code>```

As seen in output table column src_counrty  and src_State is merged as single column "src" and dst_country and dst_state as "dst"
Is there any way to achieve this output using SQL query!

I have searched related topics on the internet and could not find any, so if anyone has any suggestion/solution for this it will be much helpful for me.. Thanks!!

答:
You may use a series of unions:

SELECT Date, src_counrty, dst_country, Value FROM TABLE1
UNION ALL
SELECT Date, src_State, dst_country, Value FROM TABLE1
UNION ALL
SELECT Date, src_counrty, dst_state, Value FROM TABLE1
UNION ALL
SELECT Date, src_State, dst_state, Value FROM TABLE1
ORDER BY Date;
```

If the order of the output matters beyond the date, state the logic and the above query can be updated.

Body:
I have a table "TABLE1" like below

Date        src_counrty  src_State   dst_country    dst_state   Value
2022-02-09       a           d           x             y          1
2022-02-09       a           e           x             y          1
2022-02-09       c           f           x             y          1

I want to have output table as below using a select statement

Date         src    dst   Value
2022-02-09    a      x      1
2022-02-09    a      x      1
2022-02-09    c      x      1
2022-02-09    d      y      1
2022-02-09    e      y      1
2022-02-09    f      y      1
2022-02-09    a      y      1
2022-02-09    a      y      1
2022-02-09    c      y      1
2022-02-09    d      x      1
2022-02-09    e      x      1
2022-02-09    f      x      1

As seen in output table column src_counrty  and src_State is merged as single column "src" and dst_country and dst_state as "dst"
Is there any way to achieve this output using SQL query!

I have searched related topics on the internet and could not find any, so if anyone has any suggestion/solution for this it will be much helpful for me.. Thanks!!

Body:
You may use a series of unions:

SELECT Date, src_counrty, dst_country, Value FROM TABLE1
UNION ALL
SELECT Date, src_State, dst_country, Value FROM TABLE1
UNION ALL
SELECT Date, src_counrty, dst_state, Value FROM TABLE1
UNION ALL
SELECT Date, src_State, dst_state, Value FROM TABLE1
ORDER BY Date;

If the order of the output matters beyond the date, state the logic and the above query can be updated.


问:
Check if two dataframes have the same values in the column using .isin in koalas dataframe
I am having a small issue in comparing two dataframes and the dataframes are detailed as below.
The dataframes detailed below are all in koalas.

```<code>import databricks.koalas as ks

mini_team_df_1 = ks.DataFrame(['0000340b'], columns = ['team_code'])

mini_receipt_df_2 = ks.DataFrame(['0000340b'], columns = ['team_code'])

mini_receipt_df_2['match_flag'] = mini_receipt_df_2['team_code'].isin(ks.DataFrame(mini_team_df_1))

mini_receipt_df_2
</code>```

I am executing this code on databricks and I expect the mini_receipt_df_2 should have the output as follows:

```<code>    team_code   match_flag

0   0000340b     True
</code>```

But in my code shown above, the output is as follows:

```<code>    team_code   match_flag
0   0000340b     False
</code>```

This makes no sense to me as using the .isin function would give me the True value for team_code = 0000340b     as this is the same in both dataframes.

May someone help me understand what is wrong?

Thank you

答:
Try this:

```<code>mini_receipt_df_2['match_flag'] = np.isin(mini_team_df_1['team_code'].to_numpy(), mini_receipt_df_2['team_code'])
</code>```

Output:

```<code>>>> mini_receipt_df_2
  team_code  match_flag
0  0000340b        True
</code>```

Body:
I am having a small issue in comparing two dataframes and the dataframes are detailed as below.
The dataframes detailed below are all in koalas.

import databricks.koalas as ks

mini_team_df_1 = ks.DataFrame(['0000340b'], columns = ['team_code'])

mini_receipt_df_2 = ks.DataFrame(['0000340b'], columns = ['team_code'])

mini_receipt_df_2['match_flag'] = mini_receipt_df_2['team_code'].isin(ks.DataFrame(mini_team_df_1))

mini_receipt_df_2

I am executing this code on databricks and I expect the mini_receipt_df_2 should have the output as follows:

    team_code   match_flag

0   0000340b     True

But in my code shown above, the output is as follows:

    team_code   match_flag
0   0000340b     False

This makes no sense to me as using the .isin function would give me the True value for team_code = 0000340b     as this is the same in both dataframes.

May someone help me understand what is wrong?

Thank you

Body:
Try this:

mini_receipt_df_2['match_flag'] = np.isin(mini_team_df_1['team_code'].to_numpy(), mini_receipt_df_2['team_code'])

Output:

>>> mini_receipt_df_2
  team_code  match_flag
0  0000340b        True


问:
Why does my PHP class seem to be looping if I declare a property as an array outside of the method?
I have a class that essentially runs through a matching pair of arrays to do some error correction:

```<code>class PumpErrors {
    public $error = array();
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $i = 0;
        foreach($this->pumpdat as $val){
          if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);
</code>```

I'm feeding the class the array from the form (POST) (its a matched pair of an amount and ID of a pump.  The number of pumps varies depending on who is using the form.)
I then call the errors on the main page to show the errors:

```<code><?php
if(isset($errors)){
?>
    <div class='form-row justify-content-center'><p class='text-danger'>
<?php
    foreach($errors->firstOfAll() as $userErrors) {
        echo $userErrors . '<br />';

?>
        </p>
    </div>
<?php
    }
?>
</code>```

This results in the errors being displayed TWICE.

```<code>Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
</code>```

HOWEVER

If I run the class like this:

```<code>class PumpErrors {
    public $error;
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $this->error = array();
        $i = 0;
        foreach($this->pumpdat as $val){

            if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);
</code>```

and display the errors, it only shows up once, as intended.

I'm just looking for an explanation as to WHY this would be happening.

If I declare the property as an array at the beginning, I get doubles on the output.

If I set the property initially as nothing and then set property as an array inside the method, all is good.

I initially thought that perhaps declaring it as an array at the beginning was causing it to be a multidimensional array and somehow the loop through to display it was just going through it twice. But the kint dump didn't look as if that was happening.  If there is more than one error say pump 1 and pump 2, then i get doubles like this:

```<code>Pump 1 (error message)
Pump 2 (error message)

Pump 1 (error message)
Pump 2 (error message)
</code>```

(note:, im doing this as a class out of laziness so i can use the same error display code as rakit validator for the rest of the form, I know there are easier way to run thru the array to check it.  This was more of an exercise to see IF it could be done this way and I stumbled on this weird behavior.)

EDIT: perhaps a version issue? im running it on 7.4.24 locally.

答:
In the first version of the class you only clear the errors array when the class is instantiated

```<code>public $error = array();
</code>```

But in the second version you clear the errors array as part of the the call of the method

```<code>public function firstOfAll() {
    $this->error = array();
</code>```

So of course the errors in the first version will just keep building up over multiple calls to firstOfAll() but in the second each call initialises the errors array.

Body:
I have a class that essentially runs through a matching pair of arrays to do some error correction:

class PumpErrors {
    public $error = array();
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $i = 0;
        foreach($this->pumpdat as $val){
          if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);

I'm feeding the class the array from the form (POST) (its a matched pair of an amount and ID of a pump.  The number of pumps varies depending on who is using the form.)
I then call the errors on the main page to show the errors:

<?php
if(isset($errors)){
?>

<?php
    foreach($errors->firstOfAll() as $userErrors) {
        echo $userErrors . '
';

?>

<?php
    }
?>

This results in the errors being displayed TWICE.

Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.
Pump 12 must be a number and cannot be blank. Use 0 for no amount pumped.

HOWEVER

If I run the class like this:

class PumpErrors {
    public $error;
    private $pumpdat;
    private $welldat;

    public function __construct($pumpdat, $welldat){
        $this->pumpdat = $pumpdat;
        $this->welldat = $welldat;
    }

    public function firstOfAll() {
        $this->error = array();
        $i = 0;
        foreach($this->pumpdat as $val){

            if(!is_numeric($val)){

                $err = $this->welldat[$i].' must be a number and cannot be blank.  Use 0 for no amount pumped.';
                $this->error[] = $err;
            }
            $i++;
        }
        return $this->error;
    }
}

$errors = new PumpErrors($_POST['pumpamt'], $_POST['wellid']);

and display the errors, it only shows up once, as intended.

I'm just looking for an explanation as to WHY this would be happening.

If I declare the property as an array at the beginning, I get doubles on the output.

If I set the property initially as nothing and then set property as an array inside the method, all is good.

I initially thought that perhaps declaring it as an array at the beginning was causing it to be a multidimensional array and somehow the loop through to display it was just going through it twice. But the kint dump didn't look as if that was happening.  If there is more than one error say pump 1 and pump 2, then i get doubles like this:

Pump 1 (error message)
Pump 2 (error message)

Pump 1 (error message)
Pump 2 (error message)

(note:, im doing this as a class out of laziness so i can use the same error display code as rakit validator for the rest of the form, I know there are easier way to run thru the array to check it.  This was more of an exercise to see IF it could be done this way and I stumbled on this weird behavior.)

EDIT: perhaps a version issue? im running it on 7.4.24 locally.

Body:
In the first version of the class you only clear the errors array when the class is instantiated

public $error = array();

But in the second version you clear the errors array as part of the the call of the method

public function firstOfAll() {
    $this->error = array();

So of course the errors in the first version will just keep building up over multiple calls to firstOfAll() but in the second each call initialises the errors array.


问:
Tranforming dates into Weeks and Fortnights by Months using lubridate
I want to transform dates into weeks and fortnights by months using lubridate R package. My working example is below:

```<code>library(tidyverse)
library(lubridate)

dt1 <-
  tibble(
    Date      = seq(from = ymd("2021-01-01"), to = ymd("2021-12-31"), by = '1 day')
  , Week      = week(Date)
  , Fortnight = ceiling(week(Date)/2)
  , Month     =  month(Date)
    )
dt2 <-
  dt1 %>%
  group_by(Month) %>%
  mutate(
    WK = week(Date)
  , FN = ceiling(week(Date)/2)
    )

head(dt2, 10)
# A tibble: 10 x 6
# Groups:   Month [1]
   Date        Week Fortnight Month    WK    FN
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl>
 1 2021-01-01     1         1     1     1     1
 2 2021-01-02     1         1     1     1     1
 3 2021-01-03     1         1     1     1     1
 4 2021-01-04     1         1     1     1     1
 5 2021-01-05     1         1     1     1     1
 6 2021-01-06     1         1     1     1     1
 7 2021-01-07     1         1     1     1     1
 8 2021-01-08     2         1     1     2     1
 9 2021-01-09     2         1     1     2     1
10 2021-01-10     2         1     1     2     1

tail(dt2, 10)
# A tibble: 10 x 6
# Groups:   Month [1]
   Date        Week Fortnight Month    WK    FN
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl>
 1 2021-12-22    51        26    12    51    26
 2 2021-12-23    51        26    12    51    26
 3 2021-12-24    52        26    12    52    26
 4 2021-12-25    52        26    12    52    26
 5 2021-12-26    52        26    12    52    26
 6 2021-12-27    52        26    12    52    26
 7 2021-12-28    52        26    12    52    26
 8 2021-12-29    52        26    12    52    26
 9 2021-12-30    52        26    12    52    26
10 2021-12-31    53        27    12    53    27
</code>```

Questions

WK (Weeks by Months) and FT (Fortnight by Months) are not as expected.

Want to label Weeks as January 01-07, January 08-14, January 15-21, January 22-28, January 29-31, etc.

Want to label Fortnights as January 01-14, January 15-28, January 29-31, etc.

答:
We may need to group by the 'WK', 'FT' to do this

```<code>library(dplyr)
library(lubridate)
library(stringr)
dt1 %>%
  group_by(Month) %>%
  mutate(WK = week(Date), FN = ceiling(week(Date)/2)) %>%
  group_by(WK, .add = TRUE) %>%
  mutate(WKfmt = str_c(format(min(Date), '%B %d-'),
      format(max(Date), '%d'))) %>%
  group_by(Month, FN) %>%
  mutate(FNfmt = str_c(format(min(Date), '%B %d-'),
      format(max(Date), '%d'))) %>%
  ungroup
</code>```

-output

```<code># A tibble: 365 × 8
   Date        Week Fortnight Month    WK    FN WKfmt         FNfmt
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl> <chr>         <chr>
 1 2021-01-01     1         1     1     1     1 January 01-07 January 01-14
 2 2021-01-02     1         1     1     1     1 January 01-07 January 01-14
 3 2021-01-03     1         1     1     1     1 January 01-07 January 01-14
 4 2021-01-04     1         1     1     1     1 January 01-07 January 01-14
 5 2021-01-05     1         1     1     1     1 January 01-07 January 01-14
 6 2021-01-06     1         1     1     1     1 January 01-07 January 01-14
 7 2021-01-07     1         1     1     1     1 January 01-07 January 01-14
 8 2021-01-08     2         1     1     2     1 January 08-14 January 01-14
 9 2021-01-09     2         1     1     2     1 January 08-14 January 01-14
10 2021-01-10     2         1     1     2     1 January 08-14 January 01-14
# … with 355 more rows
</code>```

Body:
I want to transform dates into weeks and fortnights by months using lubridate R package. My working example is below:

library(tidyverse)
library(lubridate)

dt1 <-
  tibble(
    Date      = seq(from = ymd("2021-01-01"), to = ymd("2021-12-31"), by = '1 day')
  , Week      = week(Date)
  , Fortnight = ceiling(week(Date)/2)
  , Month     =  month(Date)
    )
dt2 <-
  dt1 %>%
  group_by(Month) %>%
  mutate(
    WK = week(Date)
  , FN = ceiling(week(Date)/2)
    )

head(dt2, 10)
# A tibble: 10 x 6
# Groups:   Month [1]
   Date        Week Fortnight Month    WK    FN
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl>
 1 2021-01-01     1         1     1     1     1
 2 2021-01-02     1         1     1     1     1
 3 2021-01-03     1         1     1     1     1
 4 2021-01-04     1         1     1     1     1
 5 2021-01-05     1         1     1     1     1
 6 2021-01-06     1         1     1     1     1
 7 2021-01-07     1         1     1     1     1
 8 2021-01-08     2         1     1     2     1
 9 2021-01-09     2         1     1     2     1
10 2021-01-10     2         1     1     2     1

tail(dt2, 10)
# A tibble: 10 x 6
# Groups:   Month [1]
   Date        Week Fortnight Month    WK    FN
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl>
 1 2021-12-22    51        26    12    51    26
 2 2021-12-23    51        26    12    51    26
 3 2021-12-24    52        26    12    52    26
 4 2021-12-25    52        26    12    52    26
 5 2021-12-26    52        26    12    52    26
 6 2021-12-27    52        26    12    52    26
 7 2021-12-28    52        26    12    52    26
 8 2021-12-29    52        26    12    52    26
 9 2021-12-30    52        26    12    52    26
10 2021-12-31    53        27    12    53    27

Questions

WK (Weeks by Months) and FT (Fortnight by Months) are not as expected.

Want to label Weeks as January 01-07, January 08-14, January 15-21, January 22-28, January 29-31, etc.

Want to label Fortnights as January 01-14, January 15-28, January 29-31, etc.

Body:
We may need to group by the 'WK', 'FT' to do this

library(dplyr)
library(lubridate)
library(stringr)
dt1 %>%
  group_by(Month) %>%
  mutate(WK = week(Date), FN = ceiling(week(Date)/2)) %>%
  group_by(WK, .add = TRUE) %>%
  mutate(WKfmt = str_c(format(min(Date), '%B %d-'),
      format(max(Date), '%d'))) %>%
  group_by(Month, FN) %>%
  mutate(FNfmt = str_c(format(min(Date), '%B %d-'),
      format(max(Date), '%d'))) %>%
  ungroup

-output

# A tibble: 365 × 8
   Date        Week Fortnight Month    WK    FN WKfmt         FNfmt
   <date>     <dbl>     <dbl> <dbl> <dbl> <dbl> <chr>         <chr>
 1 2021-01-01     1         1     1     1     1 January 01-07 January 01-14
 2 2021-01-02     1         1     1     1     1 January 01-07 January 01-14
 3 2021-01-03     1         1     1     1     1 January 01-07 January 01-14
 4 2021-01-04     1         1     1     1     1 January 01-07 January 01-14
 5 2021-01-05     1         1     1     1     1 January 01-07 January 01-14
 6 2021-01-06     1         1     1     1     1 January 01-07 January 01-14
 7 2021-01-07     1         1     1     1     1 January 01-07 January 01-14
 8 2021-01-08     2         1     1     2     1 January 08-14 January 01-14
 9 2021-01-09     2         1     1     2     1 January 08-14 January 01-14
10 2021-01-10     2         1     1     2     1 January 08-14 January 01-14
# … with 355 more rows


问:
How to pass string argument to the python script saving quotes in it
I am having trouble with passing a string argument to a Python script.

I need to pass a string in this format: "{"test_key_1": [1, 3], "test_key_2": [5]}"

but when I am doing this:

```<code>test_script.py --test_arg "{"test_key_1": [1, 3], "test_key_2": [5]}"
</code>```

I am getting this string inside the script:

```<code>'{test_key_1: [1, 3], test_ket_2: [5]}'
</code>```

Why did my double quotes disappear?

I need to do json.loads(string_argument) after I get the argument, but it fails because of the wrong format.

答:
You need to escape the double quotes like this:

```<code>test_script.py --test_arg "{\"test_key_1\": [1, 3], \"test_key_2\": [5]}"
</code>```

or like just change the delimiters like this:

```<code>test_script.py --test_arg '{"test_key_1": [1, 3], "test_key_2": [5]}'
</code>```

Body:
I am having trouble with passing a string argument to a Python script.

I need to pass a string in this format: "{"test_key_1": [1, 3], "test_key_2": [5]}"

but when I am doing this:

test_script.py --test_arg "{"test_key_1": [1, 3], "test_key_2": [5]}"

I am getting this string inside the script:

'{test_key_1: [1, 3], test_ket_2: [5]}'

Why did my double quotes disappear?

I need to do json.loads(string_argument) after I get the argument, but it fails because of the wrong format.

Body:
You need to escape the double quotes like this:

test_script.py --test_arg "{\"test_key_1\": [1, 3], \"test_key_2\": [5]}"

or like just change the delimiters like this:

test_script.py --test_arg '{"test_key_1": [1, 3], "test_key_2": [5]}'


问:
How to change the name of a GridFS bucket in python?
I have been trying to figure out how to change the default name of a bucket while using GridFS in python. By default they look like,

```<code>fs.chunks
fs.files
</code>```

I want them to look like,

```<code>custom.chunks
custom.files
</code>```

Can anyone explain how to do it?

答:
I have figured it out, you just need to pass the name of the bucket with the argument. like this,
if your desired name for the bucket is custom,</p>
```<code>GridFS(db, "Custom")
</code>```

Body:
I have been trying to figure out how to change the default name of a bucket while using GridFS in python. By default they look like,

fs.chunks
fs.files

I want them to look like,

custom.chunks
custom.files

Can anyone explain how to do it?

Body:
I have figured it out, you just need to pass the name of the bucket with the argument. like this,
if your desired name for the bucket is custom,

GridFS(db, "Custom")


问:
Find position of first value greater than X in a vector
I have a vector and want to find the position of the first value that is greater than 100.</p>

答:
As I need to perform a similar calculation many times within a loop, I was interested in which of the many answers provided in this thread would be most efficient.

TLDR:
Whether the first value appears early or late in a vector, which.max(v > 100) is the fastest solution to this problem.

Note, however, that if no entry in v exceeds 100, it will return 1; thus there may be cause for

SafeWhichMax <- function (v) {
  first <- which.max(v > 100)
  if (first == 1L && v[1] <= 100) NA else first
}
SafeWhichMax(100) # NA
SafeWhichMax(101) # 1

```
<p>If a vector is very long and is not guaranteed to contain any <code>TRUE</code> results, <code>match(TRUE, v > 100)</code> may be quicker than <code>which.max()</code> with checks.</p>
<pre class="lang-r prettyprint-override"><code># Short vector:
v <- 0:105

microbenchmark(
  which.max(v > 100),
  match(TRUE, v > 100),
  min(which(v > 100)),
  which(v > 100)[1],
  Position(function(x) x, v > 100),
  Position(function(x) x > 100, v),
  purrr::detect_index(v, function (x) x > 100)
)
</code>```
```<code>Unit: microseconds
                                  mean      median
which.max(v > 100)                24.112    23.80
SafeWhichMax(v)                   24.889    24.25
match(TRUE, v > 100)              34.752    33.20
min(which(v > 100))               25.506    25.20
which(v > 100)[1]                 25.320    24.90
Position(function(x) x, v > 100)  3231.783  3043.50
Position(function(x) x > 100, v)  3487.805  3314.75
purrr::detect_index               16436.579 16064.90
</code>```

# Long vector, with late first occurrence of v > 100
v <- -10000:105
```
```Unit: microseconds
                                  mean   median
which.max(v > 100)               24.958    24.30
SafeWhichMax(v)                  25.456    24.90
match(TRUE, v > 100)             37.680    37.85
min(which(v > 100))              26.439    26.00
which(v > 100)[1]                25.724    25.55
Position(function(x) x, v > 100) 3224.240  3036.50
Position(function(x) x > 100, v) 3389.538  3287.05
purrr::detect_index              17344.706 15283.35
```

Body:
As I need to perform a similar calculation many times within a loop, I was interested in which of the many answers provided in this thread would be most efficient.

TLDR:
Whether the first value appears early or late in a vector, which.max(v > 100) is the fastest solution to this problem.

Note, however, that if no entry in v exceeds 100, it will return 1; thus there may be cause for

SafeWhichMax <- function (v) {
  first <- which.max(v > 100)
  if (first == 1L && v[1] <= 100) NA else first
}
SafeWhichMax(100) # NA
SafeWhichMax(101) # 1

If a vector is very long and is not guaranteed to contain any TRUE results, match(TRUE, v > 100) may be quicker than which.max() with checks.

# Short vector:
v <- 0:105

microbenchmark(
  which.max(v > 100),
  match(TRUE, v > 100),
  min(which(v > 100)),
  which(v > 100)[1],
  Position(function(x) x, v > 100),
  Position(function(x) x > 100, v),
  purrr::detect_index(v, function (x) x > 100)
)

Unit: microseconds
                                  mean      median
which.max(v > 100)                24.112    23.80
SafeWhichMax(v)                   24.889    24.25
match(TRUE, v > 100)              34.752    33.20
min(which(v > 100))               25.506    25.20
which(v > 100)[1]                 25.320    24.90
Position(function(x) x, v > 100)  3231.783  3043.50
Position(function(x) x > 100, v)  3487.805  3314.75
purrr::detect_index               16436.579 16064.90

# Long vector, with late first occurrence of v > 100
v <- -10000:105

Unit: microseconds
                                  mean   median
which.max(v > 100)               24.958    24.30
SafeWhichMax(v)                  25.456    24.90
match(TRUE, v > 100)             37.680    37.85
min(which(v > 100))              26.439    26.00
which(v > 100)[1]                25.724    25.55
Position(function(x) x, v > 100) 3224.240  3036.50
Position(function(x) x > 100, v) 3389.538  3287.05
purrr::detect_index              17344.706 15283.35


问:
Whats wrong with my Javascript Date Comparison
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}
</code>```

And here is the Code in Debug so you can see the values:

EDIT:
Solution

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}
</code>```

答:
If you supply no arguments, the constructor creates a Date object for
  today's date and time according to local time. If you supply some
  arguments but not others, the missing arguments are set to 0. If you
  supply any arguments, you must supply at least the year, month, and
  day. You can omit the hours, minutes, seconds, and milliseconds.

The date is measured in milliseconds since midnight 01 January, 1970
  UTC.
  A day holds 86,400,000 milliseconds. The Date object range is
  -100,000,000 days to 100,000,000 days relative to 01 January, 1970
  UTC.

try the following code while comparing the dates

```<code>if ( today < lastWeek.getMilliseconds() ) {
        alert('Date Under Week');
    }
    if ( today > nextWeek.getMilliseconds() ) {
        alert('Date Over Week');
    }
</code>```

The Date object provides uniform behavior across platforms.

Body:
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}

And here is the Code in Debug so you can see the values:

EDIT:
Solution

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}

Body:
If you supply no arguments, the constructor creates a Date object for
  today's date and time according to local time. If you supply some
  arguments but not others, the missing arguments are set to 0. If you
  supply any arguments, you must supply at least the year, month, and
  day. You can omit the hours, minutes, seconds, and milliseconds.

The date is measured in milliseconds since midnight 01 January, 1970
  UTC.
  A day holds 86,400,000 milliseconds. The Date object range is
  -100,000,000 days to 100,000,000 days relative to 01 January, 1970
  UTC.

try the following code while comparing the dates

if ( today < lastWeek.getMilliseconds() ) {
        alert('Date Under Week');
    }
    if ( today > nextWeek.getMilliseconds() ) {
        alert('Date Over Week');
    }

The Date object provides uniform behavior across platforms.


问:
Input closes when I try to delete the string and the string has the length 1 on Ant Design Vue Table
When I try to delete the content in the input and the length of the content is 1, the input closes and I have no idea why. I'm having some trouble trying to figure it out why this is happening.

On this editable table I'm able to edit everything that I wanted, and when the string is longer than 1 this doesn't happen. What am I doing wrong?

This is my code now:

```<code><template>
     <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false" class="tableEditable">
        <template #title>
            <div class="formLayoutCrud">
                <p>{{this.title}}</p>
                <input-multiple-button :name="'buttonOptions'" :value="'percentage'" :options="this.buttonOptions"> </input-multiple-button>
            </div>
        </template>
        <template v-for="col in this.editableCells" #[col]="{ column, text, record }" :key="col">
            <div class="editable-cell">
                <div v-if="editableData[record.key + '|' + column.key]" class="editable-cell-input-wrapper">
                    <a-input v-model:value="editableData[record.key + '|' + column.key]" @pressEnter="save(record.key, column.key)" type="number" />
                    <check-outlined class="editable-cell-icon-check" @click="save(record.key, column.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="edit(record.key, column.key)" />
                </div>
            </div>
        </template>
    </a-table>
</template>
<script>
import { reactive, ref } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

import InputMultipleButton from '@/components/crudForm/InputMultipleButton.vue';

export default {
    name: 'TableEditable',
    props: {
        title: String,
        buttonOptions: Array,
        editableCells: Array,
        dataSrc: Array
    },
    components: {
        CheckOutlined,
        EditOutlined,
        InputMultipleButton
    },
    setup() {
        const columns = [
            {
                title: 'Mon',
                dataIndex: 'monday',
                slots: {
                    customRender: 'monday',
                },
            },
            {
                title: 'Tue',
                dataIndex: 'tuesday',
                slots: {
                    customRender: 'tuesday',
                },
            },
            {
                title: 'Wed',
                dataIndex: 'wednesday',
                slots: {
                    customRender: 'wednesday',
                },
            },
            {
                title: 'Thr',
                dataIndex: 'thursday',
                slots: {
                    customRender: 'thursday',
                },
            },
            {
                title: 'Fri',
                dataIndex: 'friday',
                slots: {
                    customRender: 'friday',
                },
            },
            {
                title: 'Sat',
                dataIndex: 'saturday',
                slots: {
                    customRender: 'saturday',
                },
            },
            {
                title: 'Sun',
                dataIndex: 'sunday',
                slots: {
                    customRender: 'sunday',
                },
            },
        ];
        const dataSource = ref([
            {
                key: '0',
                monday: '0',
                tuesday: '0',
                wednesday: '0',
                thursday: '0',
                friday: '0',
                saturday: '9',
                sunday: '10'

            }
            ]);

        const editableData = reactive({});

        const edit = (row, column) => {
            console.log(editableData)
            editableData[row + '|' + column] = dataSource.value.filter((item) => row === item.key)[0][column];
        };

        const save = (row, column) => {
            dataSource.value[row][column] = editableData[row + '|' + column];
            delete editableData[row + '|' + column];
            };

        return {
            columns,
            dataSource,
            editableData,
            edit,
            save
        };
  },
}
</script>
</code>```

For example: When I edit the Sunday option (10), this doesn't happen. But it happens to all of the other examples. I'm not sure if it's related to the edit/filter function or something else

Thanks in advance!

答:
I believe the issue you're seeing is due to the way type coercion works in js

if you have a if(val == false) or just if(val) it will change the type of the variable, and because "" == false, this statement will be treated as falsy if the value is an empty string: v-if="editableData[record.key + '|' + column.key]"

Because your delete command in the save method will remove the key value, you can do a type-strict compare against undefined like this:

```

Body:
When I try to delete the content in the input and the length of the content is 1, the input closes and I have no idea why. I'm having some trouble trying to figure it out why this is happening.

On this editable table I'm able to edit everything that I wanted, and when the string is longer than 1 this doesn't happen. What am I doing wrong?

This is my code now:

<template>

        <template #title>

{{this.title}}

                <input-multiple-button :name="'buttonOptions'" :value="'percentage'" :options="this.buttonOptions"> </input-multiple-button>

        </template>
        <template v-for="col in this.editableCells" #[col]="{ column, text, record }" :key="col">

                    <check-outlined class="editable-cell-icon-check" @click="save(record.key, column.key)" />

                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="edit(record.key, column.key)" />

        </template>

</template>

For example: When I edit the Sunday option (10), this doesn't happen. But it happens to all of the other examples. I'm not sure if it's related to the edit/filter function or something else

Thanks in advance!

Body:
I believe the issue you're seeing is due to the way type coercion works in js

if you have a if(val == false) or just if(val) it will change the type of the variable, and because "" == false, this statement will be treated as falsy if the value is an empty string: v-if="editableData[record.key + '|' + column.key]"

Because your delete command in the save method will remove the key value, you can do a type-strict compare against undefined like this:

<div
  v-if="editableData[record.key + '|' + column.key] !== undefined"
  class="editable-cell-input-wrapper"
>


问:
Horizontal RecyclerView with dynamic item height
I am trying to create a horizontal recycler view with dynamic height by following this stack overflow post. The solution seems working. But the recycler view items disappear when I try to remove an item from recycler view.

recyclerview layout:

```<code>    <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:clipToPadding="false"
    android:orientation="horizontal"
    android:paddingStart="13dp"
    android:paddingEnd="13dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

Recycler view item layout:

```<code><androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:layout_marginStart="4dp"
app:cardBackgroundColor="#BCAAAA"
app:cardElevation="2dp">

    <TextView
        android:padding="36dp"
        android:id="@+id/textViewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="22sp"
        tools:text="Test String"/>

</androidx.cardview.widget.CardView>
</code>```

Activity:

```<code>     val flexBoxLayoutManager = FlexboxLayoutManager(this, FlexDirection.ROW, FlexWrap.NOWRAP)
    with(recyclerView) {
        layoutManager = flexBoxLayoutManager
        adapter = RecyclerViewAdapter()
        setHasFixedSize(false)
    }
</code>```

Adapter:

```<code> class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var textViewName: TextView = itemView.findViewById(R.id.textViewName)
    init {
        updateLayoutParamsToAllowHorizontalScrolling()
    }
    private fun updateLayoutParamsToAllowHorizontalScrolling() {
        (itemView.layoutParams as? FlexboxLayoutManager.LayoutParams)?.let {
            it.flexShrink = 0.0f
            it.alignSelf = AlignItems.FLEX_START
        }
    }
}

    override fun onBindViewHolder(holder: RecyclerViewAdapter.ViewHolder, position: Int) {
    val item = listItems[position]
    var msg = "Sample item no:$position "
    for(i in 0..position){
        msg += "dynamic content \n"
    }
    holder.textViewName.text = msg
    holder.itemView.setOnClickListener {
        val pos = listItems.indexOf(item)
        listItems.removeAt(pos)
        notifyItemRemoved(pos)
    }
}
</code>```

A screen recording of the output:

Is there any way to fix this issue? Or Are there any other approach to implement horizontal recyclerveiw with dynamic height?

答:
I have fixed the issue without using FlexBoxLayoutManger.

Used LinearLayoutManager with horizontal orientation and the following code in onBindViewHolder in RecyclerViewAdapter.

```<code>  holder.itemView.post {
        val wMeasureSpec =
            View.MeasureSpec.makeMeasureSpec(holder.itemView.width, View.MeasureSpec.EXACTLY)
        val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        holder.itemView.measure(wMeasureSpec, hMeasureSpec)
        if (holder.itemView.measuredHeight > holder.itemView.height) {
            holder.itemView.layoutParams =
                (holder.itemView.layoutParams as ViewGroup.LayoutParams)
                    .apply {
                            height = holder.itemView.measuredHeight
                    }
        }
    }
</code>```

Body:
I am trying to create a horizontal recycler view with dynamic height by following this stack overflow post. The solution seems working. But the recycler view items disappear when I try to remove an item from recycler view.

recyclerview layout:

    <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:clipToPadding="false"
    android:orientation="horizontal"
    android:paddingStart="13dp"
    android:paddingEnd="13dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Recycler view item layout:

<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:layout_marginStart="4dp"
app:cardBackgroundColor="#BCAAAA"
app:cardElevation="2dp">

    <TextView
        android:padding="36dp"
        android:id="@+id/textViewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="22sp"
        tools:text="Test String"/>

</androidx.cardview.widget.CardView>

Activity:

     val flexBoxLayoutManager = FlexboxLayoutManager(this, FlexDirection.ROW, FlexWrap.NOWRAP)
    with(recyclerView) {
        layoutManager = flexBoxLayoutManager
        adapter = RecyclerViewAdapter()
        setHasFixedSize(false)
    }

Adapter:

 class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var textViewName: TextView = itemView.findViewById(R.id.textViewName)
    init {
        updateLayoutParamsToAllowHorizontalScrolling()
    }
    private fun updateLayoutParamsToAllowHorizontalScrolling() {
        (itemView.layoutParams as? FlexboxLayoutManager.LayoutParams)?.let {
            it.flexShrink = 0.0f
            it.alignSelf = AlignItems.FLEX_START
        }
    }
}

    override fun onBindViewHolder(holder: RecyclerViewAdapter.ViewHolder, position: Int) {
    val item = listItems[position]
    var msg = "Sample item no:$position "
    for(i in 0..position){
        msg += "dynamic content \n"
    }
    holder.textViewName.text = msg
    holder.itemView.setOnClickListener {
        val pos = listItems.indexOf(item)
        listItems.removeAt(pos)
        notifyItemRemoved(pos)
    }
}

A screen recording of the output:

Is there any way to fix this issue? Or Are there any other approach to implement horizontal recyclerveiw with dynamic height?

Body:
I have fixed the issue without using FlexBoxLayoutManger.

Used LinearLayoutManager with horizontal orientation and the following code in onBindViewHolder in RecyclerViewAdapter.

  holder.itemView.post {
        val wMeasureSpec =
            View.MeasureSpec.makeMeasureSpec(holder.itemView.width, View.MeasureSpec.EXACTLY)
        val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        holder.itemView.measure(wMeasureSpec, hMeasureSpec)
        if (holder.itemView.measuredHeight > holder.itemView.height) {
            holder.itemView.layoutParams =
                (holder.itemView.layoutParams as ViewGroup.LayoutParams)
                    .apply {
                            height = holder.itemView.measuredHeight
                    }
        }
    }


问:
In Java Swing (using swingx) how to sort rows in one table in same order as another table
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

```<code>Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums
</code>```

If I sort by table 1, column 2 Ascending I want to get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges
</code>```

but I get

```<code>Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums
</code>```

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

答:
Here is what I meant in the comments:</p>
```<code>import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.*;

public class TablesExample extends JPanel {
    static class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Row Id",
                "Person",
                "Fruit"};
        private Object[][] data = {
                {"1", "Tom", "Orange"},
                {"2", "Jane", "Apple"},
                {"3", "Fred", "Pear"},
                {"4", "Steve", "Lemon"},
                {"5", "Jim", "Plum"}
        };

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Tables Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setPreferredSize(new Dimension(500, 100));

        TablesExample newContentPane = new TablesExample();
        newContentPane.setOpaque(true);

        MyTableModel model = new MyTableModel();
        TableRowSorter<MyTableModel> sorter = new TableRowSorter<>(model);
        JTable table = new JTable(model);
        table.setRowSorter(sorter);
        TableColumn column2 = table.getColumnModel().getColumn(2);
        column2.setMinWidth(0);
        column2.setMaxWidth(0);
        column2.setWidth(0);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(table);
        tabbedPane.add("Persons", scrollPane);

        JTable table2 = new JTable(model);
        table2.setRowSorter(sorter);
        TableColumn column1 = table2.getColumnModel().getColumn(1);
        column1.setMinWidth(0);
        column1.setMaxWidth(0);
        column1.setWidth(0);

        JScrollPane scrollPane2 = new JScrollPane();
        scrollPane2.setViewportView(table2);
        tabbedPane.add("Fruits", scrollPane2);

        frame.setContentPane(tabbedPane);

        frame.pack();
        frame.setVisible(true);
    }
}
</code>```

Body:
I have a table with x num of rows, I have a second table with the same number of rows but different columns and metadata, they have different table models. but each row represents the same object (a song).

I want to synchronize row sorting between the two tables so for example if I sort on column 2 of table 1 then rows of the table will be sorted in the same order. But currently, I just have sorted by matching sort keys so sort on the same column (but because different data get different results)

e.g

Starting point

Table 1
1    tom
2    jane
3    fred
4    steve
5    jim

Table 2
1    oranges
2    apples
3    pears
4    lemons
5    plums

If I sort by table 1, column 2 Ascending I want to get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
5    plums
3    pears
4    lemons
1    oranges

but I get

Table 1
2    jane
5    jim
3    fred
4    steve
1    tom

Table 2
2    apples
4    lemons
1    oranges
3    pears
5    plums

My sorting is done by calling setSortKeys() on table 2 to the getSortKeys() of table 1 and vice versa. I can see why it doesn't work, I am telling table 2 to sort by column 2 ascending the same as table 1 but of course these columns have different data in each table. But I can't work out a way to get table 2 to sort to the final order of table 1 instead.

One solution would be for both tables to share the same table model and just show the columns relevant to their table, but that would require a major rework of the code, so I am hoping for a more specific solution just to resolve the sorting issue.

I am using Java 11, and swingx latest version 1.6.4 (i know very old)  but this delegates sorting to standard Java (earlier version that I was previously using had its own sorting) so not really a swingx question.

The real world situation, within my application is as follows, each row represents a song, and the tabs show metadata for that song. the tabs under the edit menu all share same model and all work using the setSortKeys() method described above. So here i have sorted on Mood Aggressive column

Edit metadata tab

and if I go to another tab, we see the rows are sorted in same order

Another Edit metadata tab, sorted same order

but if I go to the Edit ID3 tab, we see the rows have been sorted in different order.

ID3 Edit tab sorted different order

This is because ID3 Edit tab shows the metadata in different format (ID3) and has different table model so column x represent in the model stores different data.

Note because all models store the rowno in first column, sorting my the rowno column works for all tabs.

So from a user point of view they are just viewing different tabs of the same table, and therefore would expect sort to be consistent for the tabs

Body:
Here is what I meant in the comments:

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.*;

public class TablesExample extends JPanel {
    static class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Row Id",
                "Person",
                "Fruit"};
        private Object[][] data = {
                {"1", "Tom", "Orange"},
                {"2", "Jane", "Apple"},
                {"3", "Fred", "Pear"},
                {"4", "Steve", "Lemon"},
                {"5", "Jim", "Plum"}
        };

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Tables Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setPreferredSize(new Dimension(500, 100));

        TablesExample newContentPane = new TablesExample();
        newContentPane.setOpaque(true);

        MyTableModel model = new MyTableModel();
        TableRowSorter<MyTableModel> sorter = new TableRowSorter<>(model);
        JTable table = new JTable(model);
        table.setRowSorter(sorter);
        TableColumn column2 = table.getColumnModel().getColumn(2);
        column2.setMinWidth(0);
        column2.setMaxWidth(0);
        column2.setWidth(0);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(table);
        tabbedPane.add("Persons", scrollPane);

        JTable table2 = new JTable(model);
        table2.setRowSorter(sorter);
        TableColumn column1 = table2.getColumnModel().getColumn(1);
        column1.setMinWidth(0);
        column1.setMaxWidth(0);
        column1.setWidth(0);

        JScrollPane scrollPane2 = new JScrollPane();
        scrollPane2.setViewportView(table2);
        tabbedPane.add("Fruits", scrollPane2);

        frame.setContentPane(tabbedPane);

        frame.pack();
        frame.setVisible(true);
    }
}


问:
thread 'main' panicked at 'attempt to add with overflow', test.rs:15:12
I have been learning rust while practicing recursion. So this is just a simple recursive problem and the type is an signed8 and should be working. But I get this error which I am not able to understand why.

The base case is correct and the calls recursive calls are correct as well.

fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i8) -> i8 {

    println!("{}", n);
    if n == 0 || n == 1 {
        return 1;
    }
    if n < 0 {
        return 0;
    }
    return ways_to_climb(n - 1) + ways_to_climb(n - 2) + ways_to_climb(n - 3);
}

```

答:
The overflow is because of i8. Use i32 instead, which is usually default.</p>
```<code>fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i32) -> i32 {

   println!("{}", n);
   if n == 0 || n == 1 {
    return 1;
   }
   if n < 0 {
    return 0;
   }
   return ways_to_climb(n - 1) + ways_to_climb(n - 2) + ways_to_climb(n - 3);
}
</code>```

Body:
The overflow is because of i8. Use i32 instead, which is usually default.

fn main() {
    let num = ways_to_climb(10);
    println!("{}", num);
}

fn ways_to_climb(n: i32) -> i32 {

   println!("{}", n);
   if n == 0 || n == 1 {
    return 1;
   }
   if n < 0 {
    return 0;
   }
   return ways_to_climb(n - 1) + ways_to_climb(n - 2) + ways_to_climb(n - 3);
}


问:
Django Channels Error - Cannot import BACKEND 'asgi_redis.RedisChannelLayer'
I have installed Django-Channels but while running the daphne-server I am getting this error given below:

```<code>File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 36, in make_backend
"Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name)

channels.asgi.InvalidChannelLayerError: Cannot import BACKEND 'asgi_redis.RedisChannelLayer' specified for default
</code>```

My settings.py is:

```<code>CHANNEL_LAYERS = {
"default": {
    "BACKEND": "asgi_redis.RedisChannelLayer",
    "CONFIG": {
        "hosts": [os.environ.get('REDIS_URL', 'redis://X.X.X.X:6379')],
    },
    "ROUTING": "MyProject.routing.channel_routing",
},
}
</code>```

Need help in resolving this error.

答:
That did the thing for me.</p>
```<code>daphne = "~=3.0.2"
channels = "~=3.0.4"
channels-redis = "~=3.3.1"
async-timeout = "~=3.0.1"
</code>```

Body:
I have installed Django-Channels but while running the daphne-server I am getting this error given below:

File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 36, in make_backend
"Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name)

channels.asgi.InvalidChannelLayerError: Cannot import BACKEND 'asgi_redis.RedisChannelLayer' specified for default

My settings.py is:

CHANNEL_LAYERS = {
"default": {
    "BACKEND": "asgi_redis.RedisChannelLayer",
    "CONFIG": {
        "hosts": [os.environ.get('REDIS_URL', 'redis://X.X.X.X:6379')],
    },
    "ROUTING": "MyProject.routing.channel_routing",
},
}

Need help in resolving this error.

Body:
That did the thing for me.

daphne = "~=3.0.2"
channels = "~=3.0.4"
channels-redis = "~=3.3.1"
async-timeout = "~=3.0.1"


问:
Find first file in directory with Java
I have some sort of batch program that should pick up a file from a directory and process it.

Since this program is supposed to:

run on JDK 5,

be small (no external libraries)

and fast! (with a bang)

...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?

答: There is no good solution here on Java 1.5, you can use a filter to get only 1 file, but then java will only return one file but parse over all of them anyways. If you don't need the actual file object you could try something like Runtime.getRuntime().exec("dir") split the returned string on \n and print out the first line :-P

Title: Find first file in directory with Java


问:
Identify specific element of dataframe
I'm trying to extract a pattern from a dataset in order to identify specific element in dataframe.
Here's a sample dataset that I'm using:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])
</code>```

to
from

A
B

B
C

C
D

D
E

D
F

E
G

F
H

Z
T

T
M

V
D

The table represents a series of links between elements. The meaning is that A is calculated from B, B is calculated from C, C is calculated from D, D is calculated from E and F, etc.

I'm trying to identify all the input elements given a specific element. Here's my try:

```<code>obj = 'A'
target = []
flag = True

while len(df[df['to'] == obj])>0:
    for i in range(0, len(df[df['to'] == obj])):
        for m in range(0, len(df)):
            if obj == df.loc[m,'to']:
                target.append(df.loc[m,'from'])
                obj = df.loc[m,'from']
                print(obj)

target = target[-1]
print(target)
</code>```

With that code, I obtain G as the only input element but i the main problem is that the element D is calculated from 2 elements and i can't manage to obtain G and H as input.

I hope I have been clear and comprehensive and I thank in advance anyone who can help me.

Thank you,

Giammaria

答:
What you want to achieve is a graph problem.

You want to find the root(s) of the subtree that contains your element.

For this networkx is the ideal tool. You can convert your dataframe to directed graph using from_pandas_edgelist.

```<code>import networkx as nx

query = 'A'

# make graph
G = nx.from_pandas_edgelist(df, source='from', target='to',
                            create_using=nx.DiGraph) # important to have directed

# get nodes positions
# 0 = root
degrees = G.in_degree()

# find roots of given element
roots = {node for node in nx.ancestors(G, source=query) if degrees[node]==0}
</code>```

output: {'G', 'H'}

The graph:

getting all roots per element

For this you need to split the graph in disjoint subgraphs and to find the root(s) of each graph. Then you can use a dictionary comprehension to build the matches:

```<code>groups = list(nx.weakly_connected_components(G))
# [{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'V'}, {'M', 'T', 'Z'}]

subgraphs = [G.subgraph(c) for c in groups]

roots = [{node for node,degree in list(g.in_degree()) if degree == 0}
         for g in subgraphs]
# [{'G', 'H'}, {'M'}]

out = pd.Series({node: nx.ancestors(g, node).intersection(r)
                 for s,g,r in zip(groups, subgraphs, roots) for node in s},
                name='root')

df.merge(out, left_on='to', right_index=True)
</code>```

output:

```<code>  to from    root
0  A    B  {G, H}
1  B    C  {G, H}
2  C    D  {G, H}
3  D    E  {G, H}
4  D    F  {G, H}
5  E    G     {G}
6  F    H     {H}
7  Z    T     {M}
8  T    M     {M}
9  V    D  {G, H}
</code>```

Title: Identify specific element of dataframe

Body:
I'm trying to extract a pattern from a dataset in order to identify specific element in dataframe.
Here's a sample dataset that I'm using:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['A', 'B'], ['B', 'C'], ['C', 'D'],['D', 'E'], ['D', 'F'], ['E', 'G'],['F', 'H'], ['Z', 'T'], ['T', 'M'],['V','D']]),
                   columns=['to', 'from'])

to
from

A
B

B
C

C
D

D
E

D
F

E
G

F
H

Z
T

T
M

V
D

The table represents a series of links between elements. The meaning is that A is calculated from B, B is calculated from C, C is calculated from D, D is calculated from E and F, etc.

I'm trying to identify all the input elements given a specific element. Here's my try:

obj = 'A'
target = []
flag = True

while len(df[df['to'] == obj])>0:
    for i in range(0, len(df[df['to'] == obj])):
        for m in range(0, len(df)):
            if obj == df.loc[m,'to']:
                target.append(df.loc[m,'from'])
                obj = df.loc[m,'from']
                print(obj)

target = target[-1]
print(target)

With that code, I obtain G as the only input element but i the main problem is that the element D is calculated from 2 elements and i can't manage to obtain G and H as input.

I hope I have been clear and comprehensive and I thank in advance anyone who can help me.

Thank you,

Giammaria

Body:
What you want to achieve is a graph problem.

You want to find the root(s) of the subtree that contains your element.

For this networkx is the ideal tool. You can convert your dataframe to directed graph using from_pandas_edgelist.

import networkx as nx

query = 'A'

# make graph
G = nx.from_pandas_edgelist(df, source='from', target='to',
                            create_using=nx.DiGraph) # important to have directed

# get nodes positions
# 0 = root
degrees = G.in_degree()

# find roots of given element
roots = {node for node in nx.ancestors(G, source=query) if degrees[node]==0}

output: {'G', 'H'}

The graph:

getting all roots per element

For this you need to split the graph in disjoint subgraphs and to find the root(s) of each graph. Then you can use a dictionary comprehension to build the matches:

groups = list(nx.weakly_connected_components(G))
# [{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'V'}, {'M', 'T', 'Z'}]

subgraphs = [G.subgraph(c) for c in groups]

roots = [{node for node,degree in list(g.in_degree()) if degree == 0}
         for g in subgraphs]
# [{'G', 'H'}, {'M'}]

out = pd.Series({node: nx.ancestors(g, node).intersection(r)
                 for s,g,r in zip(groups, subgraphs, roots) for node in s},
                name='root')

df.merge(out, left_on='to', right_index=True)

output:

  to from    root
0  A    B  {G, H}
1  B    C  {G, H}
2  C    D  {G, H}
3  D    E  {G, H}
4  D    F  {G, H}
5  E    G     {G}
6  F    H     {H}
7  Z    T     {M}
8  T    M     {M}
9  V    D  {G, H}


问:
Insert spaceing between chaptername and thechapter in header
I am using the scrheadings package in Latex. I want to add the chapter name and number with the following command to my header:

```<code>\ihead[\chaptername \thechapter]{}
</code>```

The output looks like "Chapter1". I would like to have a 'normal' space between the chaptername and the number like "Chapter 1". What can I do?

答:
Probably add an ~ for your spacing...:

\ihead[\chaptername~\thechapter]{}
```

Body:
I am using the scrheadings package in Latex. I want to add the chapter name and number with the following command to my header:

\ihead[\chaptername \thechapter]{}

The output looks like "Chapter1". I would like to have a 'normal' space between the chaptername and the number like "Chapter 1". What can I do?