问:
Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
I have a form to submit add salarie, the problem here if I delete the function store in controller, it even gives me error instead of giving me error function store does not exist.

SalarieController.php

```<code>public function store(request $request){
      Salarie::create($request->all());
      session()->flash('success','salarie add successfully');
      return redirect('salaries');
    }
</code>```

web.php

```<code>Route::resource('salaries', 'SalarieController');
</code>```

create.blade.php

```<code><form action="{{ url('salaries') }}" method="post">
                  {{ csrf_field() }}

                <div class="col-md-12">
                    <div class="form-group col-md-3  @if($errors->get('matricule')) has-error @endif">
                      <input type="text" name="matricule" class="form-control" value="{{ old('matricule') }}" placeholder="matricule">
                    </div>

                    <div class="form-group col-md-3  @if($errors->get('nom')) has-error @endif">
                      <input type="text" name="nom" class="form-control" value="{{ old('nom') }}" placeholder="nom">
                    </div>

                    <div class="form-group col-md-3  @if($errors->get('prenom')) has-error @endif">
                      <input type="text" name="prenom" class="form-control" value="{{ old('prenom') }}" placeholder="prenom">
                    </div>

                    <div class="form-group col-md-3  @if($errors->get('cin')) has-error @endif">
                      <input type="text" name="cin" class="form-control" value="{{ old('cin') }}" placeholder="cin">
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group col-md-3 ">
                      <input type="date" name="daten" class="form-control" value="{{ old('daten') }}" placeholder="date naissance">
                    </div>

                    <div class="form-group col-md-3">
                          <select class="form-control" name="situationf">
                              <option>celebataire</option>
                              <option>marie</option>
                          </select>
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="nbree" class="form-control" value="{{ old('nbree') }}" placeholder="nombre d'enfant">
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="cnss" class="form-control" value="{{ old('cnss') }}" placeholder="matricule CNSS">
                    </div>
                </div>

                <div class="col-md-12">
                    <div class="form-group col-md-3  @if($errors->get('salairenet')) has-error @endif">
                      <input type="text" name="salairenet" class="form-control" value="{{ old('salairenet') }}" placeholder="salaire net">
                    </div>

                    <div class="form-group col-md-3  @if($errors->get('unite')) has-error @endif">
                      <select class="form-control" name="unite">
                              <option>Heure</option>
                              <option>Jour</option>
                              <option>Mois</option>
                      </select>
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="hs" class="form-control" value="{{ old('hs') }}" placeholder="tarif HS">
                    </div>

                    <div class="form-group col-md-3">
                      <input type="date" name="datee" class="form-control" value="{{ old('datee') }}" placeholder="date embouche">
                    </div>
                </div>

                <div class="col-md-12">
                    <div class="form-group col-md-3">
                     <select class="form-control" name="fonction_id">
                        <option></option>
                       @foreach($fonctions as $fonction)
                      <option value="{{ $fonction->id }}">{{ $fonction->fonction}}</option>
                       @endforeach
                     </select>
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="primer" class="form-control" value="{{ old('primer') }}" placeholder="prime rendement">
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="primel" class="form-control" value="{{ old('primel') }}" placeholder="prime de longement">
                    </div>

                    <div class="form-group col-md-3">
                      <input type="text" name="primet" class="form-control" value="{{ old('primet') }}" placeholder="prime de transport">
                    </div>
                </div>

                <div class="col-md-12">
                  <div class="form-group col-md-3">
                      <select class="form-control" name="chantier_id">
                              <option></option>
                               @foreach($chantiers as $chantier)
                              <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
                               @endforeach
                      </select>
                  </div>
                </div>
                <div class="col-md-12">
                <div class="form-group col-md-2 col-md-offset-5">
                  <button type="submit" class="btn btn-theme btn-lg" value="submit">Ajouter</button>
                </div>
              </div>

              </form>
</code>```

Salarie.php

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Salarie extends Model
{
    public function chantier(){
        return $this->belongsTo('App\Chantier');
    }
    protected $guarded = [];
}
</code>```

答:
I guess you're missing some options values

here

```<code><select class="form-control" name="situationf">
      <option>celebataire</option> // must be <option value="celeb_value">celebataire</option>
      <option>marie</option> // must be <option value="marie_value">celebataire</option>
</select>
</code>```

here also

```<code><select class="form-control" name="unite">
       <option>Heure</option> // must be <option value="heure_value">Heure</option>
       <option>Jour</option> // must be <option value="jour_value">Jour</option>
       <option>Mois</option> // must be <option value="mois_value">Mois</option>
</select>
</code>```

here too

```<code><select class="form-control" name="fonction_id">
      <option></option> // remove empty option or set function_id to nullable
      @foreach($fonctions as $fonction)
      <option value="{{ $fonction->id }}">{{ $fonction->fonction}}</option>
      @endforeach
</select>
</code>```

and here

```<code><select class="form-control" name="chantier_id">
        <option></option> // same as function_id
        @foreach($chantiers as $chantier)
        <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
        @endforeach
</select>
</code>```

Body:
I have a form to submit add salarie, the problem here if I delete the function store in controller, it even gives me error instead of giving me error function store does not exist.

SalarieController.php

public function store(request $request){
      Salarie::create($request->all());
      session()->flash('success','salarie add successfully');
      return redirect('salaries');
    }

web.php

Route::resource('salaries', 'SalarieController');

create.blade.php

<form action="{{ url('salaries') }}" method="post">
                  {{ csrf_field() }}

get('matricule')) has-error @endif">
                      <input type="text" name="matricule" class="form-control" value="{{ old('matricule') }}" placeholder="matricule">

get('nom')) has-error @endif">
                      <input type="text" name="nom" class="form-control" value="{{ old('nom') }}" placeholder="nom">

get('prenom')) has-error @endif">
                      <input type="text" name="prenom" class="form-control" value="{{ old('prenom') }}" placeholder="prenom">

get('cin')) has-error @endif">
                      <input type="text" name="cin" class="form-control" value="{{ old('cin') }}" placeholder="cin">

                      <input type="date" name="daten" class="form-control" value="{{ old('daten') }}" placeholder="date naissance">

                          <select class="form-control" name="situationf">
                              <option>celebataire</option>
                              <option>marie</option>
                          </select>

                      <input type="text" name="nbree" class="form-control" value="{{ old('nbree') }}" placeholder="nombre d'enfant">

                      <input type="text" name="cnss" class="form-control" value="{{ old('cnss') }}" placeholder="matricule CNSS">

get('salairenet')) has-error @endif">
                      <input type="text" name="salairenet" class="form-control" value="{{ old('salairenet') }}" placeholder="salaire net">

get('unite')) has-error @endif">
                      <select class="form-control" name="unite">
                              <option>Heure</option>
                              <option>Jour</option>
                              <option>Mois</option>
                      </select>

                      <input type="text" name="hs" class="form-control" value="{{ old('hs') }}" placeholder="tarif HS">

                      <input type="date" name="datee" class="form-control" value="{{ old('datee') }}" placeholder="date embouche">

                     <select class="form-control" name="fonction_id">
                        <option></option>
                       @foreach($fonctions as $fonction)
                      <option value="{{ $fonction->id }}">{{ $fonction->fonction}}</option>
                       @endforeach
                     </select>

                      <input type="text" name="primer" class="form-control" value="{{ old('primer') }}" placeholder="prime rendement">

                      <input type="text" name="primel" class="form-control" value="{{ old('primel') }}" placeholder="prime de longement">

                      <input type="text" name="primet" class="form-control" value="{{ old('primet') }}" placeholder="prime de transport">

                      <select class="form-control" name="chantier_id">
                              <option></option>
                               @foreach($chantiers as $chantier)
                              <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
                               @endforeach
                      </select>

                  <button type="submit" class="btn btn-theme btn-lg" value="submit">Ajouter</button>

              </form>

Salarie.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Salarie extends Model
{
    public function chantier(){
        return $this->belongsTo('App\Chantier');
    }
    protected $guarded = [];
}

Body:
I guess you're missing some options values

here

<select class="form-control" name="situationf">
      <option>celebataire</option> // must be <option value="celeb_value">celebataire</option>
      <option>marie</option> // must be <option value="marie_value">celebataire</option>
</select>

here also

<select class="form-control" name="unite">
       <option>Heure</option> // must be <option value="heure_value">Heure</option>
       <option>Jour</option> // must be <option value="jour_value">Jour</option>
       <option>Mois</option> // must be <option value="mois_value">Mois</option>
</select>

here too

<select class="form-control" name="fonction_id">
      <option></option> // remove empty option or set function_id to nullable
      @foreach($fonctions as $fonction)
      <option value="{{ $fonction->id }}">{{ $fonction->fonction}}</option>
      @endforeach
</select>

and here

<select class="form-control" name="chantier_id">
        <option></option> // same as function_id
        @foreach($chantiers as $chantier)
        <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
        @endforeach
</select>


来源: stackexchange

问:
why does `boost::lower_bound` take its argument by value?
The implementation of boost::lower_bound (found here) in Range 2.0 takes its argument by value.

Why is this?  std::lower_bound takes its argument by const ref - see here

答:
This has now been fixed by this issue.

There may be historical reasons for taking the argument by value.  See this answer about function objects passed by value to standard algorithms.

ContentLicense: CC BY-SA 4.0


问:
css not loading even though there're no errors and it's linked correctly in ejs
so, I'm trying to link a css file to an ejs file but it's not working, and I think I'm linking them correctly:

```<code><head>
<title>Acres & Karats Calculator</title>
<base href="/">
<link type="text/css" href="css/Acres and Karats Calculator.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700&display=swap" rel="stylesheet">
</code>```

and i specified the public directory to be used in express:

```<code>let express = require("express"),
    app     = express();

app.use("/public", express.static(__dirname + "/public"));

app.get("/", (req, res) => {
    res.render("Acres and Karats Calculator.ejs")
});

app.listen("3000", () => {
    console.log("Server started!");
});
</code>```

and there are no errors in the console at all and the css is not loaded

file structure:

app.js

views

pubilc

css

Acres and Karats Calculator.css

答: I solved it by adding rel="stylesheet" and adding a / before the file path

Body:
so, I'm trying to link a css file to an ejs file but it's not working, and I think I'm linking them correctly:

<title>Acres & Karats Calculator</title>
<base href="/">
<link type="text/css" href="css/Acres and Karats Calculator.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700&display=swap" rel="stylesheet">

and i specified the public directory to be used in express:

let express = require("express"),
    app     = express();

app.use("/public", express.static(__dirname + "/public"));

app.get("/", (req, res) => {
    res.render("Acres and Karats Calculator.ejs")
});

app.listen("3000", () => {
    console.log("Server started!");
});

and there are no errors in the console at all and the css is not loaded

file structure:

app.js

views

pubilc

css

Acres and Karats Calculator.css


问:
Load data list in same registration page JSP and Servlet
I have a registration form and table in the same page but my table only load data when i submit a new registration. How can i load the table when i open the page? Im using JSP and Servlet. I tried to search before asking here but i didnt find what i need.

index.jsp

```<code>    <table class="table table-striped table-bordered">
        <thead class="thead-dark text-center">
            <tr>
                <th scope="col">CÓDIGO</th>
                <th scope="col">DATA</th>
                <th scope="col">QUANTIDADE</th>
                <th scope="col">VALOR</th>
                <th scope="col">VOLUME</th>
            </tr>
        </thead>

        <tbody>
            <c:forEach items="${investimentos}" var="inv">
                <tr>
                    <td><c:out value="${inv.codigo}"></c:out></td>
                    <td><c:out value="${inv.data}"></c:out></td>
                    <td><c:out value="${inv.quantidade}"></c:out></td>
                    <td>R$<c:out value="${inv.valor}"></c:out></td>
                    <td>R$<c:out value="${inv.valor * inv.quantidade}"></c:out></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</code>```

Servlet

```<code>@WebServlet("/registrarAcao")
public class Acao extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private AcaoDAO acaoDAO = new AcaoDAO();

    public Acao() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String codigo = req.getParameter("codigo");
        String dataString = req.getParameter("data");

        String quantidade = req.getParameter("quantidade");
        String valor = req.getParameter("valor");

        AcaoBean acao = new AcaoBean();
        acao.setCodigo(codigo);
        acao.setData(dataString);
        acao.setQuantidade(Double.parseDouble(quantidade));
        acao.setValor(Double.parseDouble(valor));
        acaoDAO.salvar(acao);

        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
You cant view the table if you start with /index.jsp. You need to start with /registrarAcao and you will get to doGet method and you table will be loaded

Change welcome page

```<code><welcome-file-list>
    <welcome-file>index.page</welcome-file>
</welcome-file-list>
</code>```

Body:
I have a registration form and table in the same page but my table only load data when i submit a new registration. How can i load the table when i open the page? Im using JSP and Servlet. I tried to search before asking here but i didnt find what i need.

index.jsp

                CÓDIGO
                DATA
                QUANTIDADE
                VALOR
                VOLUME

            <c:forEach items="${investimentos}" var="inv">

                    <c:out value="${inv.codigo}"></c:out>
                    <c:out value="${inv.data}"></c:out>
                    <c:out value="${inv.quantidade}"></c:out>
                    R$<c:out value="${inv.valor}"></c:out>
                    R$<c:out value="${inv.valor * inv.quantidade}"></c:out>

            </c:forEach>

Servlet

@WebServlet("/registrarAcao")
public class Acao extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private AcaoDAO acaoDAO = new AcaoDAO();

    public Acao() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String codigo = req.getParameter("codigo");
        String dataString = req.getParameter("data");

        String quantidade = req.getParameter("quantidade");
        String valor = req.getParameter("valor");

        AcaoBean acao = new AcaoBean();
        acao.setCodigo(codigo);
        acao.setData(dataString);
        acao.setQuantidade(Double.parseDouble(quantidade));
        acao.setValor(Double.parseDouble(valor));
        acaoDAO.salvar(acao);

        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Body:
You cant view the table if you start with /index.jsp. You need to start with /registrarAcao and you will get to doGet method and you table will be loaded

Change welcome page

<welcome-file-list>
    <welcome-file>index.page</welcome-file>
</welcome-file-list>


问:
How to fix "ImportError: No module named 'x'"
I'm trying to create some test cases and i'm running into this:

ImportError: No module named bjmusic.controllers.music_c

I'm running music_test.py and my directory structure is the following:

```<code>BJMusic
├── app.py
└── bjmusic
    ├── controllers
    │   ├── album_c.py
    │   ├── __init__.py
    │   ├── main_c.py
    │   ├── main_c.pyc
    │   ├── music_c.py
    ├── __init__.py
    ├── models
    │   ├── album_m.py
    │   ├── albuns.txt
    │   ├── __init__.py
    │   ├── music_m.py
    │   ├── musics.txt
    │   ├── playlist.py
    │   ├── playlists.txt
    ├── tests
    │   ├── album_test.py
    │   ├── __init__.py
    │   ├── music_test.py
    │   ├── music_test.pyc
    │   └── playlist_test.py
    └── views
        ├── album_v.py
        ├── __init__.py
        ├── main_v.py
        ├── music_v.py
</code>```

My 'music_test.py' file is the following:

```<code>import unittest
from bjmusic.controllers.music_c import searchMusicsById

class TestAlbums(unittest.Testcase):
    def test_searchMusicsById(self):
        self.assertEqual(bjmusic.controllers.music_c.searchMusicsById(23), {1: ['Michael Jackson', 'Bad', '4:07']})
</code>```

I've searched on stackoverflow and didn't found anything that helped me. I was having the same issue earlier, I believe because of circular importing, but I corrected it in all the files, so I dont think its this.

答:
Add the top-level directory to PYTHONPATH.
If you change directory there before you run it, you can just set "PYTHONPATH=."</p>

Body:
I'm trying to create some test cases and i'm running into this:

ImportError: No module named bjmusic.controllers.music_c

I'm running music_test.py and my directory structure is the following:

BJMusic
├── app.py
└── bjmusic
    ├── controllers
    │   ├── album_c.py
    │   ├── __init__.py
    │   ├── main_c.py
    │   ├── main_c.pyc
    │   ├── music_c.py
    ├── __init__.py
    ├── models
    │   ├── album_m.py
    │   ├── albuns.txt
    │   ├── __init__.py
    │   ├── music_m.py
    │   ├── musics.txt
    │   ├── playlist.py
    │   ├── playlists.txt
    ├── tests
    │   ├── album_test.py
    │   ├── __init__.py
    │   ├── music_test.py
    │   ├── music_test.pyc
    │   └── playlist_test.py
    └── views
        ├── album_v.py
        ├── __init__.py
        ├── main_v.py
        ├── music_v.py

My 'music_test.py' file is the following:

import unittest
from bjmusic.controllers.music_c import searchMusicsById

class TestAlbums(unittest.Testcase):
    def test_searchMusicsById(self):
        self.assertEqual(bjmusic.controllers.music_c.searchMusicsById(23), {1: ['Michael Jackson', 'Bad', '4:07']})

I've searched on stackoverflow and didn't found anything that helped me. I was having the same issue earlier, I believe because of circular importing, but I corrected it in all the files, so I dont think its this.


问:
Getting some device info before the main app view is loaded up
Objective-c is pretty new to me so I may well be asking an absurdly simple question but having been looking over the web and in some books I'm a bit stumped to some degree. Quite probably due to my severe lack of knowledge with obj-c. So... any help with this one will be really handy...

All I want to do is get some simple info about the device the app is running on (using [UIDevice currentDevice]) on the app launch but before the main app view is loaded up. Simple stuff huh but in all honesty I have not got the idea quite how to do this! I then want whatever info I have to be availiable (In a variable? Not too sure if thats the correct term with obj-c) throughout the app and its views. Again, I don't really have much of an idea how.

I come form a web dev background so this is very new to me to a large degree. So... yeah, any tips/pointers, help etc would be ridiculously useful!

Thanks in advance, sorry for my n00b question!

答:
The place for this would probably be in your App Delegates -application:didFinishLaunchingWithOptions: method. This method gets called when your app finishes launching and is (generally) responsible for adding your main view to the application window. You can put the information into an instance variable of your app delegate. You can get a reference to your app delegate from anywhere in your program by calling [[UIApplication sharedApplication] delegate]. An example implementation might look something like this:

```<code>// In MyAppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //Get your information, potentially put it into an
    //instance variable of the App Delegate

    //Add the main view to the view hierarchy
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The place for this would probably be in your App Delegates -application:didFinishLaunchingWithOptions: method. This method gets called when your app finishes launching and is (generally) responsible for adding your main view to the application window. You can put the information into an instance variable of your app delegate. You can get a reference to your app delegate from anywhere in your program by calling [[UIApplication sharedApplication] delegate]. An example implementation might look something like this:

// In MyAppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //Get your information, potentially put it into an
    //instance variable of the App Delegate

    //Add the main view to the view hierarchy
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}


问:
how can i convert an array to nested array in php
i have a function in my project that returns an array like this

```<code>array (size=6)
  0 =>
    array (size=4)
      'id' => string '1' (length=1)
      'user_id' => string '1' (length=1)
      'parent_id' => string '0' (length=1)
      'name' => string 'jack' (length=4)
  1 =>
    array (size=4)
      'id' => string '2' (length=1)
      'user_id' => string '6' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'jill' (length=4)
  2 =>
    array (size=4)
      'id' => string '3' (length=1)
      'user_id' => string '7' (length=1)
      'parent_id' => string '2' (length=1)
      'name' => string 'mary' (length=4)
  3 =>
    array (size=4)
      'id' => string '4' (length=1)
      'user_id' => string '2' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'scriptfloor' (length=11)

</code>```

i would like to convert this into a nested array based on parent id into this

```<code>{
  "id": "1",
  "user_id": "1",
  "parent_id": "0",
  "name": "jack",
  "children": [
    {
      "id": "2",
      "user_id": "6",
      "parent_id": "1",
      "name": "jill"
    },
    {
      "id": "4",
      "user_id": "2",
      "parent_id": "1",
      "name": "scriptfloor"
    },
    {
      "id": "6",
      "user_id": "3",
      "parent_id": "1",
      "name": "silas"
    }
  ]
}
</code>```

so far i have only gone up to one nested level. i would like to be able to make a multi-dimensional array of n-levels . i need this for  to build tree hierarchy of users and the users who referred them .Any help will be appreciated

i have used this function where $items is the unsorted array

```<code>for ( $count = 0; $count < count( $items ); $count ++ ) {
    if ( count( $items[ $count ] ) > 0 ) {
        foreach ( $items[ $count ] as $itm ) {
            if ( $itm['parent_id'] == $tree['user_id'] ) {
                $tree['children'][] = $itm;
            }

        }

    }

}

</code>```

答:
This problem reveals lot of things to now (reference variable, remove item from array, array structure, continue instruction, ...).

As a workaround below, i advice you to loop on the $items list a first time,
next you loop again on the same list  to fill children list for each parent,
you need to compare id and parent_id, if it's true you inject item on parent's children list, you remove the item to clean your array and then you end statement for current $item iteration.

I hope it's clear enought.

```<code>foreach($items as $k => $item) {
   foreach($items as $j => $parent) {
       if ($item['parent_id'] === $parent['id']) {
           $parents[$j]['children'][] = $item;
           unset($items[$k]);
           continue 2;
       }
   }
}
</code>```

Body:
i have a function in my project that returns an array like this

array (size=6)
  0 =>
    array (size=4)
      'id' => string '1' (length=1)
      'user_id' => string '1' (length=1)
      'parent_id' => string '0' (length=1)
      'name' => string 'jack' (length=4)
  1 =>
    array (size=4)
      'id' => string '2' (length=1)
      'user_id' => string '6' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'jill' (length=4)
  2 =>
    array (size=4)
      'id' => string '3' (length=1)
      'user_id' => string '7' (length=1)
      'parent_id' => string '2' (length=1)
      'name' => string 'mary' (length=4)
  3 =>
    array (size=4)
      'id' => string '4' (length=1)
      'user_id' => string '2' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'scriptfloor' (length=11)

i would like to convert this into a nested array based on parent id into this

{
  "id": "1",
  "user_id": "1",
  "parent_id": "0",
  "name": "jack",
  "children": [
    {
      "id": "2",
      "user_id": "6",
      "parent_id": "1",
      "name": "jill"
    },
    {
      "id": "4",
      "user_id": "2",
      "parent_id": "1",
      "name": "scriptfloor"
    },
    {
      "id": "6",
      "user_id": "3",
      "parent_id": "1",
      "name": "silas"
    }
  ]
}

so far i have only gone up to one nested level. i would like to be able to make a multi-dimensional array of n-levels . i need this for  to build tree hierarchy of users and the users who referred them .Any help will be appreciated

i have used this function where $items is the unsorted array

for ( $count = 0; $count < count( $items ); $count ++ ) {
    if ( count( $items[ $count ] ) > 0 ) {
        foreach ( $items[ $count ] as $itm ) {
            if ( $itm['parent_id'] == $tree['user_id'] ) {
                $tree['children'][] = $itm;
            }

        }

    }

}

Body:
This problem reveals lot of things to now (reference variable, remove item from array, array structure, continue instruction, ...).

As a workaround below, i advice you to loop on the $items list a first time,
next you loop again on the same list  to fill children list for each parent,
you need to compare id and parent_id, if it's true you inject item on parent's children list, you remove the item to clean your array and then you end statement for current $item iteration.

I hope it's clear enought.

foreach($items as $k => $item) {
   foreach($items as $j => $parent) {
       if ($item['parent_id'] === $parent['id']) {
           $parents[$j]['children'][] = $item;
           unset($items[$k]);
           continue 2;
       }
   }
}


问:
Drop observations with certain conditions iterating in the whole dataframe
I am sure this question have been already made several times, but for some reason I am not able to find the answer. Basically, I have a dataframe with 500 variables (columns) and 15000 observarions (rows). The values of the variables ranges from -140 to 100, in all the obsertations.

Basically, I need to remove the observations (rows) that have some values that are between -20 and 0.

I tried with (X_train are the 500 variables):

```<code>for i in X_train.columns:
    a=X_train[(X_train[i] >= -20) & (X_train[i] <= 0) ]
</code>```

And also with this:

```<code>a = X_train[(X_train.iloc[:,:].values > -20) & (X_train.iloc[:,:].values < -0)]
</code>```

The first code gives me a dataframe full of NA's, and the second one a dataframe with 0 rows.

Someone could help me with the correct syntaxis for this?

Thank you!!!

答:
This should work ( i.e. remove rows which have any values between -20 and 0 ) :</p>

```<code> df[(df<-20)|(df>0)].dropna()
</code>```

Body:
I am sure this question have been already made several times, but for some reason I am not able to find the answer. Basically, I have a dataframe with 500 variables (columns) and 15000 observarions (rows). The values of the variables ranges from -140 to 100, in all the obsertations.

Basically, I need to remove the observations (rows) that have some values that are between -20 and 0.

I tried with (X_train are the 500 variables):

for i in X_train.columns:
    a=X_train[(X_train[i] >= -20) & (X_train[i] <= 0) ]

And also with this:

a = X_train[(X_train.iloc[:,:].values > -20) & (X_train.iloc[:,:].values < -0)]

The first code gives me a dataframe full of NA's, and the second one a dataframe with 0 rows.

Someone could help me with the correct syntaxis for this?

Thank you!!!

Body:
This should work ( i.e. remove rows which have any values between -20 and 0 ) :

 df[(df<-20)|(df>0)].dropna()


问:
Sending Email Using Acumatica REST API
I am trying to send a mail from Acumatica RestAPI by using the below
API URL:

```<code>https:/{url}/entity/Default/17.200.001/Email?CompanyID=STS&ScreenID=CR306015
</code>```

The problem am facing while calling this API with the request shown here:

```<code>{
    "From":
            {
            "value":"abc.service@abc.com"
            },

            "To":
            {
                "value":"example@abc.com"
            },
            "Subject":
            {
                "value":"Test Email"
            },
            "Body":
            {
                "value":"Sample Erp Bot Mail Check"
            }

    }
</code>```

Is the mail is getting saved into Drafts rather than saving into sent(not being sent to receipt).

The response I am getting when calling the RestAPI is:

(Response from Postman Status:200 OK)

```<code> "MailStatus": {
        "value": "Draft"
    }
</code>```

Please suggest a way to send email through Acumatica [RestAPI] using C# and .NET.

答:
To do that you need to actually perform 2 API calls:

Create email (as you do right now)

Execute send action.

To execute Send action you do the following request:

```<code>POST: https://{url}/entity/Default/17.200.001/Email/SendEmail
Body:
{
  "entity":
   {
     "id": "put yor email ID here that you get as a result of email creation"
   }
}
</code>```

For optimization purpose you can combine both requests into one like that:

```<code>POST: https://{url}/entity/Default/17.200.001/Email/SendEmail
Body:
{
  "entity":
   {
     {
        "From":
        {
        "value":"abc.service@abc.com"
        },

        "To":
        {
            "value":"example@abc.com"
        },
        "Subject":
        {
            "value":"Test Email"
        },
        "Body":
        {
            "value":"Sample Erp Bot Mail Check"
        }
    }
  }
}
</code>```

Title: Sending Email Using Acumatica REST API

Body:
I am trying to send a mail from Acumatica RestAPI by using the below
API URL:

https:/{url}/entity/Default/17.200.001/Email?CompanyID=STS&ScreenID=CR306015

The problem am facing while calling this API with the request shown here:

{
    "From":
            {
            "value":"abc.service@abc.com"
            },

            "To":
            {
                "value":"example@abc.com"
            },
            "Subject":
            {
                "value":"Test Email"
            },
            "Body":
            {
                "value":"Sample Erp Bot Mail Check"
            }

    }

Is the mail is getting saved into Drafts rather than saving into sent(not being sent to receipt).

The response I am getting when calling the RestAPI is:

(Response from Postman Status:200 OK)

 "MailStatus": {
        "value": "Draft"
    }

Please suggest a way to send email through Acumatica [RestAPI] using C# and .NET.

Body:
To do that you need to actually perform 2 API calls:

Create email (as you do right now)

Execute send action.

To execute Send action you do the following request:

POST: https://{url}/entity/Default/17.200.001/Email/SendEmail
Body:
{
  "entity":
   {
     "id": "put yor email ID here that you get as a result of email creation"
   }
}

For optimization purpose you can combine both requests into one like that:

POST: https://{url}/entity/Default/17.200.001/Email/SendEmail
Body:
{
  "entity":
   {
     {
        "From":
        {
        "value":"abc.service@abc.com"
        },

        "To":
        {
            "value":"example@abc.com"
        },
        "Subject":
        {
            "value":"Test Email"
        },
        "Body":
        {
            "value":"Sample Erp Bot Mail Check"
        }
    }
  }
}


问:
How to send POST/GET requests from Django Website to Spring Rest api?
I have a form in a submit.html file:

```<code>{% extends 'base.html' %}

    {% block content %}
    <div class="container">
    <h1>Here you submit a new job</h1>

        <form class = "form" method="post">
            <label for="Company">Company Name:</label>
            <input type="text" value="{{ user.username }}" name="Company" id="Company">
            <br>
            <label for="position">Position:</label>
            <input type="text" name="position" placeholder="e.g Web Developer">
            <br>
            <button type="submit">Submit</button>
        </form>
    </div>

    {% endblock %}
</code>```

I also have another project built on Java Spring, and it provides the following api :
http://myhost:port/projectname/api/addposition?compName=Google&category=Developer

where it actualy takes the username as the compName and the position input as category parameters.

I've searched for a way but I mostly found examples for inside requests, not to other api.

I'm trying to find a way to send a request to this api, using post method.This api can use either params via the url or data sent to it (like json for example)
Sorry if question is not clear, it`s my first question on stack :)

Any help will be appreciated.

答:
You must submit the form for viewing and submit to an API.

For example:

submit.html

```<code>{% extends 'base.html' %}

    {% block content %}
    <div class="container">
    <h1>Here you submit a new job</h1>

        <form class = "form" method="post" **action="api"**>
            <label for="Company">Company Name:</label>
            <input type="text" value="{{ user.username }}" name="Company" id="Company">
            <br>
            <label for="position">Position:</label>
            <input type="text" name="position" placeholder="e.g Web Developer">
            <br>
            <button type="submit">Submit</button>
        </form>
    </div>

    {% endblock %}
</code>```

views.py

```<code>import os
import requests
from requests.auth import HTTPBasicAuth

def api(request):
    Company = request.POST.get('Company')
    Position = request.POST.get('position')

    url = os.environ.get("URL", 'http://myhost:port/projectname/api/addposition?compName=Google&category=Developer')
    url = "%s" % (url)
    body = {"Company" : "%s" % Company, "Position" : "%s" % Position}
        response = requests.post(url, auth=HTTPBasicAuth('USER', 'PASSWORD'), headers={'Content-Type': 'application/json'}, json=body)
    if response.status_code == 200:
        print("Code 200")
    else:
        print("Code not 200")
</code>```

urls.py

```<code>from YOURAPP.views import api

urlpatterns = [
    path('api/',
         views.api, name='api'),
]
</code>```

Body:
I have a form in a submit.html file:

{% extends 'base.html' %}

    {% block content %}

Here you submit a new job

        <form class = "form" method="post">
            Company Name:
            <input type="text" value="{{ user.username }}" name="Company" id="Company">

            Position:
            <input type="text" name="position" placeholder="e.g Web Developer">

            <button type="submit">Submit</button>
        </form>

    {% endblock %}

I also have another project built on Java Spring, and it provides the following api :
http://myhost:port/projectname/api/addposition?compName=Google&category=Developer

where it actualy takes the username as the compName and the position input as category parameters.

I've searched for a way but I mostly found examples for inside requests, not to other api.

I'm trying to find a way to send a request to this api, using post method.This api can use either params via the url or data sent to it (like json for example)
Sorry if question is not clear, it`s my first question on stack :)

Any help will be appreciated.

Body:
You must submit the form for viewing and submit to an API.

For example:

submit.html

{% extends 'base.html' %}

    {% block content %}
    <div class="container">
    <h1>Here you submit a new job</h1>

        <form class = "form" method="post" **action="api"**>
            <label for="Company">Company Name:</label>
            <input type="text" value="{{ user.username }}" name="Company" id="Company">
            <br>
            <label for="position">Position:</label>
            <input type="text" name="position" placeholder="e.g Web Developer">
            <br>
            <button type="submit">Submit</button>
        </form>
    </div>

    {% endblock %}

views.py

import os
import requests
from requests.auth import HTTPBasicAuth

def api(request):
    Company = request.POST.get('Company')
    Position = request.POST.get('position')

    url = os.environ.get("URL", 'http://myhost:port/projectname/api/addposition?compName=Google&category=Developer')
    url = "%s" % (url)
    body = {"Company" : "%s" % Company, "Position" : "%s" % Position}
        response = requests.post(url, auth=HTTPBasicAuth('USER', 'PASSWORD'), headers={'Content-Type': 'application/json'}, json=body)
    if response.status_code == 200:
        print("Code 200")
    else:
        print("Code not 200")

urls.py

from YOURAPP.views import api

urlpatterns = [
    path('api/',
         views.api, name='api'),
]


问:
failed to open stream: No such file or directory
I now upload my project to server in digital ocean,but I get this error in apache2 error log

require_once(/var/www/html/example/v1../include/DbHandler.php): failed
  to open stream: No such file or directory

The 2 line that occur error is this,is working well in localhost,but when go to server it having the error above

```<code>require_once '../include/DBHandler.php';
require_once '../include/PassHash.php';
</code>```

My directory is as below,I have to required DBhandler.php which in include folder,and index.php is from v1 folder(the place that require_once calling from).

```<code>-include
  -DBhandler.php
  -PassHash.php
-v1
  -index.php
</code>```

Here is the error log I got

[Fri May 19 12:33:19.621030 2017] [:error] [pid 5236] [client 115.133.247.14:575                                                                                22] PHP Warning:  require_once(/var/www/html/example/v1../include/                                                                                DbHandler.php): failed to open stream: No such file or directory in /var/www/htm                                                                                l/example/v1/index.php on line 9

What I tried so far

require_once $_SERVER['DOCUMENT_ROOT'].'/include/DBHandler.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/include/PassHash.php';

And this,but none of this solve the problem

```<code>require_once __DIR__."/../include/DBHandler.php";
require_once __DIR__."/../include/PassHash.php";
</code>```

Someone please help!Give me the a right direction,so I can proceed

答:
Just Remove  the symbol  /  this on staring  of file path  your problem  will be sovled.

require_once(var/www/html/example/v1../include/DbHandler.php): failed to open stream: No such file or directory

Body:
I now upload my project to server in digital ocean,but I get this error in apache2 error log

require_once(/var/www/html/example/v1../include/DbHandler.php): failed
  to open stream: No such file or directory

The 2 line that occur error is this,is working well in localhost,but when go to server it having the error above

require_once '../include/DBHandler.php';
require_once '../include/PassHash.php';

My directory is as below,I have to required DBhandler.php which in include folder,and index.php is from v1 folder(the place that require_once calling from).

-include
  -DBhandler.php
  -PassHash.php
-v1
  -index.php

Here is the error log I got

[Fri May 19 12:33:19.621030 2017] [:error] [pid 5236] [client 115.133.247.14:575                                                                                22] PHP Warning:  require_once(/var/www/html/example/v1../include/                                                                                DbHandler.php): failed to open stream: No such file or directory in /var/www/htm                                                                                l/example/v1/index.php on line 9

What I tried so far

require_once $_SERVER['DOCUMENT_ROOT'].'/include/DBHandler.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/include/PassHash.php';

And this,but none of this solve the problem

require_once __DIR__."/../include/DBHandler.php";
require_once __DIR__."/../include/PassHash.php";

Someone please help!Give me the a right direction,so I can proceed


问:
Convert Grails Application to Plugin
I read this question but it didn't answer the way I was hoping so I'm posting a similar question with a few more details.

I have a grails application that I need to turn into a plugin, but I'd like to know if this can be done without creating a new plugin and copying files.  Assuming the application name is 'admin' I created a AdminGrailsPlugin.groovy file in the root and copied the contents of another plugin's file and changed names accordingly.  I ran a package-plugin which generated the plugin.xml and the zip file.  So I assumed things were going to work.  However, when I tried to use this plugin in an application using the inline plugin mechanism, I'm not able to access any of the plugin's controllers.  They all have their own URL Mappings in the plugin's URLMappings.groovy file.

Is there a piece to this puzzle that I am missing?

UPDATE: I added one of the admin plugin's URL Mappings to the applications URLMappings.groovy and things seem to work from there.  At least for that controller.  So not sure why the plugin's URLMappings.groovy is being ignored?

答: Ok, after some more searching I discovered that in a plugin, UrlMappings.groovy is ignored.  I renamed it to AdminUrlMappings.groovy and now it works like a champ.  I'm going to go check JIRA for a bug because my other plugin's mapping class is called UrlMappings when, in my opinion, if I run 'grails run-app common' I should get CommonUrlMappings.groovy.  But that doesn't happen. </p>

Title: Convert Grails Application to Plugin


问:
Disable autoclose in ng-select
I am using ng-select but when I click on an item, it closes automatically. I want it to stay open after selecting somethig.

what should I add to this code.

```<code><ng-select [items]="items"
       bindLabel="name"
       bindValue="id"
       [multiple]="true"
       placeholder="Select categories"
        [(ngModel)]="selectedCategories">
</ng-select>
</code>```

答:
Try using the isOpen property:

```<code><ng-select [items]="items"
       [isOpen]="true" // <--- This one
       bindLabel="name"
       bindValue="id"
       [multiple]="true"
       placeholder="Select categories"
        [(ngModel)]="selectedCategories">
</ng-select>
</code>```

Title: Disable autoclose in ng-select

Body:
I am using ng-select but when I click on an item, it closes automatically. I want it to stay open after selecting somethig.

what should I add to this code.

<ng-select [items]="items"
       bindLabel="name"
       bindValue="id"
       [multiple]="true"
       placeholder="Select categories"
        [(ngModel)]="selectedCategories">
</ng-select>

Body:
Try using the isOpen property:

<ng-select [items]="items"
       [isOpen]="true" // <--- This one
       bindLabel="name"
       bindValue="id"
       [multiple]="true"
       placeholder="Select categories"
        [(ngModel)]="selectedCategories">
</ng-select>


问:
How to tie fragment destination to menu items in bottom nav bar?
I want to use the navigation and destination system in android so when a menu item in the bottom nav bar is clicked it goes to a fragment.

I created 3 empty fragments and followed this guide to tie the items to the fragments but when I click the menu items, nothing happens.
https://developer.android.com/guide/navigation/navigation-ui

I made sure that the item id from the menu has the same id as the fragment too.
how can I make this work?

Here is my Activity:

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

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val navController = findNavController(R.id.nav_host_fragment)
    bottom_navigation
        .setupWithNavController(navController)
  }
 override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val navController = findNavController(R.id.nav_host_fragment)
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}

}
</code>```

This is the activity xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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="match_parent"
android:id="@+id/coordinator"
tools:context=".MainActivity">

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/navigation" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="@color/colorPrimary"
    app:itemIconTint="@color/colorPrimaryDark"
    app:itemTextColor="@color/colorPrimaryDark"
    app:menu="@menu/bottom_navigation_menu" />
</code>```

And this is the bottom nav bar menu:

```<code> <menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/fragment_home"
    android:icon="@drawable/ic_home_24px"
    android:title="Home" />
<item
    android:id="@+id/nav_search"
    android:icon="@drawable/ic_search_24px"
    android:title="Search" />
<item
    android:id="@+id/nav_profile"
    android:icon="@drawable/ic_face_24px"
    android:title="Profile" />
</code>```

Navigation.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/navigation"
app:startDestination="@id/homeFragment">
<fragment
    android:id="@+id/homeFragment"
    android:name="com.puntogris.herewego.home.HomeFragment"
    android:label="fragment_home"
    tools:layout="@layout/fragment_home" >
    <action
        android:id="@+id/action_homeFragment_to_profileFragment"
        app:destination="@id/profileFragment" />
</fragment>
<fragment
    android:id="@+id/profileFragment"
    android:name="com.puntogris.herewego.profile.ProfileFragment"
    android:label="fragment_profile"
    tools:layout="@layout/fragment_profile" >
    <action
        android:id="@+id/action_profileFragment_to_searchFragment"
        app:destination="@id/searchFragment" />
</fragment>
<fragment
    android:id="@+id/searchFragment"
    android:name="com.puntogris.herewego.search.SearchFragment"
    android:label="fragment_search"
    tools:layout="@layout/fragment_search" />
</code>```

答:
Your android:ids do not match.

Your menu XML uses android:id="@+id/fragment_home", but your navigation XML uses android:id="@+id/homeFragment".

These need to be the same name. For example, you could change your menu XML to be

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/homeFragment"
        android:icon="@drawable/ic_home_24px"
        android:title="Home" />
    <item
        android:id="@+id/searchFragment"
        android:icon="@drawable/ic_search_24px"
        android:title="Search" />
    <item
        android:id="@+id/profileFragment"
        android:icon="@drawable/ic_face_24px"
        android:title="Profile" />
</menu>
</code>```

Body:
I want to use the navigation and destination system in android so when a menu item in the bottom nav bar is clicked it goes to a fragment.

I created 3 empty fragments and followed this guide to tie the items to the fragments but when I click the menu items, nothing happens.
https://developer.android.com/guide/navigation/navigation-ui

I made sure that the item id from the menu has the same id as the fragment too.
how can I make this work?

Here is my Activity:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val navController = findNavController(R.id.nav_host_fragment)
    bottom_navigation
        .setupWithNavController(navController)
  }
 override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val navController = findNavController(R.id.nav_host_fragment)
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}

}

This is the activity xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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="match_parent"
android:id="@+id/coordinator"
tools:context=".MainActivity">

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/navigation" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="@color/colorPrimary"
    app:itemIconTint="@color/colorPrimaryDark"
    app:itemTextColor="@color/colorPrimaryDark"
    app:menu="@menu/bottom_navigation_menu" />

And this is the bottom nav bar menu:

 <menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/fragment_home"
    android:icon="@drawable/ic_home_24px"
    android:title="Home" />
<item
    android:id="@+id/nav_search"
    android:icon="@drawable/ic_search_24px"
    android:title="Search" />
<item
    android:id="@+id/nav_profile"
    android:icon="@drawable/ic_face_24px"
    android:title="Profile" />

Navigation.xml code:

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/navigation"
app:startDestination="@id/homeFragment">
<fragment
    android:id="@+id/homeFragment"
    android:name="com.puntogris.herewego.home.HomeFragment"
    android:label="fragment_home"
    tools:layout="@layout/fragment_home" >
    <action
        android:id="@+id/action_homeFragment_to_profileFragment"
        app:destination="@id/profileFragment" />
</fragment>
<fragment
    android:id="@+id/profileFragment"
    android:name="com.puntogris.herewego.profile.ProfileFragment"
    android:label="fragment_profile"
    tools:layout="@layout/fragment_profile" >
    <action
        android:id="@+id/action_profileFragment_to_searchFragment"
        app:destination="@id/searchFragment" />
</fragment>
<fragment
    android:id="@+id/searchFragment"
    android:name="com.puntogris.herewego.search.SearchFragment"
    android:label="fragment_search"
    tools:layout="@layout/fragment_search" />

Body:
Your android:ids do not match.

Your menu XML uses android:id="@+id/fragment_home", but your navigation XML uses android:id="@+id/homeFragment".

These need to be the same name. For example, you could change your menu XML to be

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/homeFragment"
        android:icon="@drawable/ic_home_24px"
        android:title="Home" />
    <item
        android:id="@+id/searchFragment"
        android:icon="@drawable/ic_search_24px"
        android:title="Search" />
    <item
        android:id="@+id/profileFragment"
        android:icon="@drawable/ic_face_24px"
        android:title="Profile" />
</menu>


问:
Not able to return palindromes
Here is my code:

```<code>def palin(n,m):
   palindromes=[]
   for i in range(n,m):                         #to check for all numbers less than r
       str_i = str(i)
       len_i = len(str_i)
       check = 0
       if len_i == 1:                           #for all numbers less than 10
           palindromes.append(i)

       elif len_i%2 == 0:                       #if length is even
           for a in range(int((len_i/2))):
               if str_i[a] == str_i[-a-1]:
                   check = check+1              #increments check by one if the ath digit is equal to len_i-ath digit

                if check == len_i/2:                #checks whether var check has value of half the length of number
                   palindromes.append(i)

       else:                                    #if length is odd
           for a in range(int((len_i -1)/2)):
               if str_i[a] == str_i[-a-1]:
                   check = check+1

               if check == (len_i-1)/2:
                   palindromes.append(i)

       return palindromes

  lst = palin(100,1000)
  print(lst)
  input("WOW!")
</code>```

When I run the following code, an empty list is printed instead of printing a list containing all the palindromes in the given range.
I've tried this code without defining palin() function ad it works just fine.

答:
The line with "return" is inside of your "for", so everytime it restarts the return of your function. Try to put that outside the return:</p>

```<code>def palin(n,m):
    palindromes=[]
    for i in range(10,100):                        #to check for all numbers from n to m
        str_i = str(i)
        len_i = len(str_i)
        check = 0
        if len_i == 1:                          #for all numbers less than 10
            palindromes.append(i)

        elif len_i%2 == 0:                      #if length is even
            for a in range(int((len_i/2))):
                if str_i[a] == str_i[-a-1]:
                    check = check+1             #increments check by one if the ath digit is equal to len_i-ath digit

            if check == len_i/2:                #checks whether var check has value of half the length of number
                palindromes.append(i)

        else:                                   #if length is odd
            for a in range(int((len_i -1)/2)):
                if str_i[a] == str_i[-a-1]:
                    check = check+1

                if check == (len_i-1)/2:
                    palindromes.append(i)

    # Here's the return is outside the for looping and keeps the list values
    return palindromes
</code>```

Title: Not able to return palindromes

Body:
Here is my code:

def palin(n,m):
   palindromes=[]
   for i in range(n,m):                         #to check for all numbers less than r
       str_i = str(i)
       len_i = len(str_i)
       check = 0
       if len_i == 1:                           #for all numbers less than 10
           palindromes.append(i)

       elif len_i%2 == 0:                       #if length is even
           for a in range(int((len_i/2))):
               if str_i[a] == str_i[-a-1]:
                   check = check+1              #increments check by one if the ath digit is equal to len_i-ath digit

                if check == len_i/2:                #checks whether var check has value of half the length of number
                   palindromes.append(i)

       else:                                    #if length is odd
           for a in range(int((len_i -1)/2)):
               if str_i[a] == str_i[-a-1]:
                   check = check+1

               if check == (len_i-1)/2:
                   palindromes.append(i)

       return palindromes

  lst = palin(100,1000)
  print(lst)
  input("WOW!")

When I run the following code, an empty list is printed instead of printing a list containing all the palindromes in the given range.
I've tried this code without defining palin() function ad it works just fine.

Body:
The line with "return" is inside of your "for", so everytime it restarts the return of your function. Try to put that outside the return:

def palin(n,m):
    palindromes=[]
    for i in range(10,100):                        #to check for all numbers from n to m
        str_i = str(i)
        len_i = len(str_i)
        check = 0
        if len_i == 1:                          #for all numbers less than 10
            palindromes.append(i)

        elif len_i%2 == 0:                      #if length is even
            for a in range(int((len_i/2))):
                if str_i[a] == str_i[-a-1]:
                    check = check+1             #increments check by one if the ath digit is equal to len_i-ath digit

            if check == len_i/2:                #checks whether var check has value of half the length of number
                palindromes.append(i)

        else:                                   #if length is odd
            for a in range(int((len_i -1)/2)):
                if str_i[a] == str_i[-a-1]:
                    check = check+1

                if check == (len_i-1)/2:
                    palindromes.append(i)

    # Here's the return is outside the for looping and keeps the list values
    return palindromes


问:
HTML binding in Angular 8
I am unable to display html content to Angular 8.

**Note: I am receiving html template which I need to display on Angular is coming from database as a JSON, which I am fetching it and saving it to a variable (e.g, plot) and then passing that variable to this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(this.plot)

For demo purpose I put a sample html template similar to my data which I am getting it from database.

HTML:

```<code><div [innerHTML]="myTemplate"></div>
</code>```

app.component.ts:

```<code>import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

myTemplate:SafeHtml;

constructor(private sanitizer: DomSanitizer) { }

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(`<html>
  <head>
    <!-- Load plotly.js into the DOM -->
    <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
<p>plot come below...</>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>

  <script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>
  </body>
  </html>`);

}
</code>```

When I run the code only the
 tag content "Plot come below.." is displaying to the Angular front-end but the Plotly chart which is inside

答:
It wont work.
First you are trying to put an entire HTML Page inside a div.
Second, you should first start the scripts,in your component, then load the html

in the component html. you can put in app.component.html or any other component you create in Angular. I would suggest you to create a new one and import in your app-component

```<code><p>plot come below...</>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</code>```

if you cant put the script in index.html as suggested by Çağrı TAÇYİLDİZ

or try this method:

```<code>import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

constructor() { }

   public loadScript(url) {
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        node.async = true;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }

ngOnInit(){
  this.loadScript('https://cdn.plot.ly/plotly-latest.min.js');
}

}
</code>```

the script tag you can put inside /data-decomposition.component.html, but i suggest you to put on your index.html, or.. you can save a new js file, and import in the index.html, or use the loadScript method in the class to import it.

```<code><script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>
</code>```

Title: HTML binding in Angular 8

Body:
I am unable to display html content to Angular 8.

**Note: I am receiving html template which I need to display on Angular is coming from database as a JSON, which I am fetching it and saving it to a variable (e.g, plot) and then passing that variable to this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(this.plot)

For demo purpose I put a sample html template similar to my data which I am getting it from database.

HTML:

app.component.ts:

import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

myTemplate:SafeHtml;

constructor(private sanitizer: DomSanitizer) { }

this.myTemplate = this.sanitizer.bypassSecurityTrustHtml(`

plot come below...</>

  `);

}

When I run the code only the
 tag content "Plot come below.." is displaying to the Angular front-end but the Plotly chart which is inside

Body:
It wont work.
First you are trying to put an entire HTML Page inside a div.
Second, you should first start the scripts,in your component, then load the html

in the component html. you can put in app.component.html or any other component you create in Angular. I would suggest you to create a new one and import in your app-component

<p>plot come below...</>
    <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>

if you cant put the script in index.html as suggested by Çağrı TAÇYİLDİZ

or try this method:

import { Component, OnInit} from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';

@Component({
  selector: 'app-data-decomposition',
  templateUrl: './data-decomposition.component.html',
  styleUrls: ['./data-decomposition.component.css']

})

export class DataDecompositionComponent implements OnInit {

constructor() { }

   public loadScript(url) {
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        node.async = true;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }

ngOnInit(){
  this.loadScript('https://cdn.plot.ly/plotly-latest.min.js');
}

}

the script tag you can put inside /data-decomposition.component.html, but i suggest you to put on your index.html, or.. you can save a new js file, and import in the index.html, or use the loadScript method in the class to import it.

<script type="text/javascript">
  var data = [
    {
      x: ['giraffes', 'orangutans', 'monkeys'],
      y: [20, 14, 23],
      type: 'bar'
    }
  ];

  Plotly.newPlot('myDiv', data);

  </script>


问:
How i can do a *ngFor in a array of objects that i don't know the name property?
I have this array called dadosRelatorio that i need to iterate in my template, this array i get in a http request:

```<code>[{"id": 1,
  "name": "a",
  "class":[{
     "Inglês":[{
        "id": 1,
        "code": "teste"
     },
     {
        "id": 2,
        "code": "teste 2"
     }],
     "Espanhol":[{
        "id": 1,
        "code": "a"
     }]
   }]
}]
</code>```

How i can iterate the objects inside class if they have different names property? Sometimes the name can be "Inglês" and sometimes can be "Espanhol" and other names...

When i know the name of the property i do this way:

```<code><div *ngFor="let aluno of dadosRelatorio" class="div-aluno">
       <span>Aluno: {{ aluno.name }}</span>
       <div *ngFor="let classe of aluno.class">
          <div *ngFor="let idioma of classe. ???>

          </div>
       </div>
</div>
</code>```

But how i can iterate the object inside class?

答:
You can enumerate an object keys using Object.keys.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys.

edit: You can also use the keyvalue pipe as describe in the official documentation: https://angular.io/api/common/KeyValuePipe

I thought there was a ngForIn directive as well, but I cant find the doc.

Body:
I have this array called dadosRelatorio that i need to iterate in my template, this array i get in a http request:

[{"id": 1,
  "name": "a",
  "class":[{
     "Inglês":[{
        "id": 1,
        "code": "teste"
     },
     {
        "id": 2,
        "code": "teste 2"
     }],
     "Espanhol":[{
        "id": 1,
        "code": "a"
     }]
   }]
}]

How i can iterate the objects inside class if they have different names property? Sometimes the name can be "Inglês" and sometimes can be "Espanhol" and other names...

When i know the name of the property i do this way:

       Aluno: {{ aluno.name }}

But how i can iterate the object inside class?


问:
Python scrapy submitting form data
Good day. So i'm trying to figure out how submitting form data works.

So this is the form that i want to submit

This is how the network process looks

This is the code

```<code>class OutletBot(CrawlSpider):
    name = 'hun73r'
    start_urls = ['https://www.laptopoutlet.co.uk/']
    allowed_domains = ['laptopoutlet.co.uk/']

    def parse(self, response):

        z = response.css('.header-bottom-wrap>div>div>div>form')
        type = ''
        brand = ''
        core = ''
        screensize = ''
        for option in z.css('#brand_div>select>option').extract():
            if 'APPLE' in option:
                brand = option.split('"')[1]
                print(brand)
        for option in z.css('#processor_div>select>option').extract_first():
            if 'i5' in option:
                core = option.split('"')[1]
                print(core)

        formdata = {'type': type,
                    'brand': brand,
                    'core': core,
                    'screensize': screensize}

        yield scrapy.FormRequest.from_response(
            response,
            clickdata={'type': 'submit'},
            # callback=self.parse_form,
            formdata=formdata,
            method='GET')
</code>```

When i test this code in the terminal for a response, it yields the /checkout/cart/ form.
How can i get to sumbit the /categorysearch/advanced/result/ form?
 What am i missing?

答:
So i found out that the from_response has a argument formid which i set to the id of the form

```<code>formid='search_filter_form',
</code>```

Title: Python scrapy submitting form data

Body:
Good day. So i'm trying to figure out how submitting form data works.

So this is the form that i want to submit

This is how the network process looks

This is the code

class OutletBot(CrawlSpider):
    name = 'hun73r'
    start_urls = ['https://www.laptopoutlet.co.uk/']
    allowed_domains = ['laptopoutlet.co.uk/']

    def parse(self, response):

        z = response.css('.header-bottom-wrap>div>div>div>form')
        type = ''
        brand = ''
        core = ''
        screensize = ''
        for option in z.css('#brand_div>select>option').extract():
            if 'APPLE' in option:
                brand = option.split('"')[1]
                print(brand)
        for option in z.css('#processor_div>select>option').extract_first():
            if 'i5' in option:
                core = option.split('"')[1]
                print(core)

        formdata = {'type': type,
                    'brand': brand,
                    'core': core,
                    'screensize': screensize}

        yield scrapy.FormRequest.from_response(
            response,
            clickdata={'type': 'submit'},
            # callback=self.parse_form,
            formdata=formdata,
            method='GET')

When i test this code in the terminal for a response, it yields the /checkout/cart/ form.
How can i get to sumbit the /categorysearch/advanced/result/ form?
 What am i missing?

Body:
So i found out that the from_response has a argument formid which i set to the id of the form

formid='search_filter_form',


问:
How to export Visual Studio Code Color Scheme to JetBrains IDEs (for example, CLion)?
I really love Atom One Dark theme shown in the picture. I would really like to export that to have it in its full form in CLion. Is this possible? Because that theme in CLion's marketplace doesn't have coloring for all the things that the one in VSC does. (I need it for C++)

https://marketplace.visualstudio.com/items?itemName=akamud.vscode-theme-onedark

答:
As stated by rioV8, to get the exact behavior from Visual Studio's theme to CLION you have to copy the theme, as there is no theme importer between Visual Studio Code and JetBrains CLion.

The process to do so would be as follows:

Get the source of your Visual Studio Color Scheme:

You can get the source code from this repo (VSCode There One Dark) and open it at your preferred editor or download it from the Visual Studio Marketplace.

Customize your CLION's Theme:

Select a Theme at Settings/Preferences

Clone using the Duplicate option at the config icon if you don't want to override the existing one

Enable/Edit the Semantic Highlighting: Editor -> Color Scheme -> Language Defaults -> Semantic highlighting.

Edit the Color Scheme by expanding the Editor -> Color Scheme and editing as you like.

You can find more detailed instructions at the docs: Configuring colors and fonts

** Alternative:

You also can pick a similar JetBrains theme; there are many apart from the default ones at the JetBrains Plugins directory.

For example, this JetBrains Dark theme similar to Atom One Dark.


问:
Invalid attempt to call FieldCount when reader is closed
The error above occurs when I try to do a dataReader.Read on the data recieved from the database. I know there are two rows in there so it isnt because no data actually exists.

Could it be the CommandBehavior.CloseConnection, causing the problem? I was told you had to do this right after a ExecuteReader? Is this correct?

```<code>        try
        {
            _connection.Open();
            using (_connection)
            {
                SqlCommand command = new SqlCommand("SELECT * FROM Structure", _connection);
                SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

                if (dataReader == null) return null;

                var newData = new List<Structure>();
                while (dataReader.Read())
                {
                    var entity = new Structure
                    {
                        Id = (int)dataReader["StructureID"],
                        Path = (string)dataReader["Path"],
                        PathLevel = (string)dataReader["PathLevel"],
                        Description = (string)dataReader["Description"]
                    };

                    newData.Add(entity);
                }
                dataReader.Close();

                return newData;
            }
        }
        catch (SqlException ex)
        {
            AddError(new ErrorModel("An SqlException error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        finally
        {
            _connection.Close();
        }
    }
</code>```

Thanks in advance for any help.

Clare

答: I got this exception while using the VS.NET debugger and trying to examine some IQueryable results. Bad decision because the IQueryable resulted in a large table scan.  Stopping and restarting the debugger and NOT trying to preview this particular IQueryable  was the workaround.  </p>

ContentLicense: CC BY-SA 2.5

Body:
The error above occurs when I try to do a dataReader.Read on the data recieved from the database. I know there are two rows in there so it isnt because no data actually exists.

Could it be the CommandBehavior.CloseConnection, causing the problem? I was told you had to do this right after a ExecuteReader? Is this correct?

        try
        {
            _connection.Open();
            using (_connection)
            {
                SqlCommand command = new SqlCommand("SELECT * FROM Structure", _connection);
                SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

                if (dataReader == null) return null;

                var newData = new List<Structure>();
                while (dataReader.Read())
                {
                    var entity = new Structure
                    {
                        Id = (int)dataReader["StructureID"],
                        Path = (string)dataReader["Path"],
                        PathLevel = (string)dataReader["PathLevel"],
                        Description = (string)dataReader["Description"]
                    };

                    newData.Add(entity);
                }
                dataReader.Close();

                return newData;
            }
        }
        catch (SqlException ex)
        {
            AddError(new ErrorModel("An SqlException error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        finally
        {
            _connection.Close();
        }
    }

Thanks in advance for any help.

Clare


问:
IoT device recognition on connection. Blob storage sends a configuration file as a response
I have a doubt about how to do this.
I have various iot devices that send telemetry data using different variables, as each customer personalizes his own devices. Each device communicates with the iot hub and sends messages via endpoint to various different azure services which are then processed for statistical purposes. my goal would be that every time a new device connects to the network it is provided with a file (CSV or other type) for that device, containing all the variables to be used for that particular customer. How could I make it happen?
thanks in advance for the help</p>

答: Don't know if you had a look on Device Twins https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins</p>


问:
I can't import pygame inside pycharm
I can't import pygame inside pycharm.

I've been using Linux Mint 19, Anaconda 3, Pycharm 2019.3.1.

I've created a conda environment and install pygame: conda install pygame -c cogsci

Then I ran (my_env) tiago@tiago-XPS-8700:~$ python3 mycode.py. And I got the following error:

teste.py:3: RuntimeWarning: use mixer: libSDL_mixer-1.2.so.0: cannot
  open shared object file: No such file or directory (ImportError:
  libSDL_mixer-1.2.so.0: cannot open shared object file: No such file or
  directory)   pygame.mixer.music.load('bat.mp3') Traceback (most recent
  call last):   File "teste.py", line 3, in
      pygame.mixer.music.load('bat.mp3')   File "/home/tiago/anaconda3/envs/pycharm/lib/python3.5/site-packages/pygame/init.py",
  line 105, in getattr
      raise NotImplementedError(MissingPygameModule) NotImplementedError: mixer module not available (ImportError:
  libSDL_mixer-1.2.so.0: cannot open shared object file: No such file or
  directory)

After reading some blog at internet I installed sudo apt install libsdl-mixer1.2.

After that if I run (my_env) tiago@tiago-XPS-8700:~$ python3 mycode.py at Linux terminal at my conda environment, my code run successfully.

But If I try to run the same code inside Pycharm I get the following error:

/home/tiago/anaconda3/envs/pycharm/bin/python
  /home/tiago/Documentos/PYTHON/cursoemvideo/exercicios/ex_021.py
  Traceback (most recent call last):   File
  "/home/tiago/Documentos/PYTHON/cursoemvideo/exercicios/ex_021.py",
  line 3, in
      import pygame   File "/home/tiago/anaconda3/envs/pycharm/lib/python3.5/site-packages/pygame/init.py",
  line 133, in
      from pygame.base import * ImportError: libSDL-1.2.so.0: cannot open shared object file: No such file or directory

Process finished with exit code 1

What am I missing?

答:
Inspired by this questions Tensorflow and Pycharm, I ran Pychram from the Linux Terminal at my conda environment and it worked! If I run Pycharm from Linux Mint Menu I still can't import pygame.
Addicionally, I inserted the following statement at my .bashrc so that I can run pycharm from anywhere in the Linux Terminal.

```<code># Open bashrc to edit
nano .bashrc

# Add the comand line below to the end of file
# You should adapt to your path to "pycharm.sh', mine is "/opt/pycharm-community-anaconda-2019.1.3/bin". In another computer I found it at "/var/lib/flatpak/app/com.jetbrains.PyCharm-Community/current/active/files/pycharm/bin"
export PATH=$PATH:/opt/pycharm-community-anaconda-2019.1.3/bin

# Then close the terminal and reopen it in order to the modifications in .bashrc take effect
# At terminal you run
pycharm.sh
</code>```

Title: I can't import pygame inside pycharm

Body:
Inspired by this questions Tensorflow and Pycharm, I ran Pychram from the Linux Terminal at my conda environment and it worked! If I run Pycharm from Linux Mint Menu I still can't import pygame.
Addicionally, I inserted the following statement at my .bashrc so that I can run pycharm from anywhere in the Linux Terminal.

# Open bashrc to edit
nano .bashrc

# Add the comand line below to the end of file
# You should adapt to your path to "pycharm.sh', mine is "/opt/pycharm-community-anaconda-2019.1.3/bin". In another computer I found it at "/var/lib/flatpak/app/com.jetbrains.PyCharm-Community/current/active/files/pycharm/bin"
export PATH=$PATH:/opt/pycharm-community-anaconda-2019.1.3/bin

# Then close the terminal and reopen it in order to the modifications in .bashrc take effect
# At terminal you run
pycharm.sh


问:
How can I modify text that is already printed?
I am aware that this has been posted many times, but I can't find a working solution for my problem. Here is my script:

from time import sleep
x = 100
for i in range(0, 100):
    print(x, end="\r")
    x -=1
    sleep(1)
```

<p>When I run this it prints:</p>

```100
990
980
970
```

<p>except on one line and the text gets replaced and it continues. I want it to do this:</p>

```100
99
98
97
```

on one line and it goes all the way to zero and the text gets replaced. How can I do this?

答:
Formatting your string works:

```<code>import time

for x in range(100, 0, -1):
    time.sleep(1)
    print(f'{x:3d}', end='\r')
</code>```

This formats you integers right adjusted with a width of three digits and you can see the "shorter" numbers. Or, use f'{x: <3d}' to have the numbers line up at the left (as @Olvin Roght suggested). The f in front makes it it a format string. The content inside the {} will be replaced, in this case with the value of x. The part after the : is the formatting. Here: a decimal integer with three digits.

Body:
I am aware that this has been posted many times, but I can't find a working solution for my problem. Here is my script:

from time import sleep
x = 100
for i in range(0, 100):
    print(x, end="\r")
    x -=1
    sleep(1)

When I run this it prints:

100
990
980
970

except on one line and the text gets replaced and it continues. I want it to do this:

100
99
98
97

on one line and it goes all the way to zero and the text gets replaced. How can I do this?

Body:
Formatting your string works:

import time

for x in range(100, 0, -1):
    time.sleep(1)
    print(f'{x:3d}', end='\r')

This formats you integers right adjusted with a width of three digits and you can see the "shorter" numbers. Or, use f'{x: <3d}' to have the numbers line up at the left (as @Olvin Roght suggested). The f in front makes it it a format string. The content inside the {} will be replaced, in this case with the value of x. The part after the : is the formatting. Here: a decimal integer with three digits.


问:
Java Object Serialization Performance tips
I must serialize a huge tree of objects (7,000) into disk.  Originally we kept this tree in a database with Kodo, but it would make thousands upon thousands of Queries to load this tree into memory, and it would take a good part of the local universe available time.

I tried serialization for this and indeed I get a performance improvement.  However, I get the feeling that I could improve this by writing my own, custom serialization code.  I need to make loading this serialized object as fast as possible.

In my machine, serializing / deserializing these objects takes about 15 seconds.  When loading them from the database, it takes around 40 seconds.

Any tips on what could I do to improve this performance, taking into consideration that because objects are in a tree, they reference each other?

答: Also, have a look at XStream, a library to serialize objects to XML and back again.</p>

OwnerDisplayName: Mario Ortegón

LastEditorDisplayName: Mario Ortegón

OwnerDisplayName: cherouvim


问:
Error on Conversion from NVARCHAR TO ASCII
I am having some issues with a table (view?) in SAS Enterprise Guide.

When running below code I get the following error:

```<code>DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
RUN;
</code>```

Error message:

ERROR: CLI cursor extended fetch error: [SAP AG][LIBODBCHDB
  DLL][HDBODBC] General error;-10427 Conversion of parameter/column (2)
         from data type NVARCHAR to ASCII failed

Seemingly I get the error at arbitrary points, i.e. for several tries it might return 302,400 observations, then suddenly that number increases to 1,320,000 observations before it terminates with the error. It always terminates with the error however.

Is there some way to ignore and skip the rows that returns the error and just keep all the rest?

I have no control of neither SAP nor the underlying data, so my only solution is somehow handle the errors directly in the script and ignore the rows that have the error. It is not important to my project if I lose the rows that give the error.

Thanks!

答:
What version of SAS Enterprise Guide are you using ?

Your SAS admin may have to modify how the server libname SAPFolder is set up for the workstation sessions that EG starts when it connects to a profile.  If not immediately possible you try to perform pass through queries that use SAP functions to either remove certain characters or filter rows (i.e. where statement) so no 'unconvertable' data reaches the SAS library engine.

If you can determine where criteria for one row that SAS can not convert, and you have an alternate SAP way to view the same row, you will gain insight on what data content is the cause and how to 'strip' it out (if that is possible).

Body:
I am having some issues with a table (view?) in SAS Enterprise Guide.

When running below code I get the following error:

DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
RUN;

Error message:

ERROR: CLI cursor extended fetch error: [SAP AG][LIBODBCHDB
  DLL][HDBODBC] General error;-10427 Conversion of parameter/column (2)
         from data type NVARCHAR to ASCII failed

Seemingly I get the error at arbitrary points, i.e. for several tries it might return 302,400 observations, then suddenly that number increases to 1,320,000 observations before it terminates with the error. It always terminates with the error however.

Is there some way to ignore and skip the rows that returns the error and just keep all the rest?

I have no control of neither SAP nor the underlying data, so my only solution is somehow handle the errors directly in the script and ignore the rows that have the error. It is not important to my project if I lose the rows that give the error.

Thanks!


问:
c# enumerable class - compatible with VBA
Can anyone instruct me on how to code a C# enumerable class such that the "for each" construct in Excel VBA works properly?  I tried this out with a test class called People that implements IEnumerable and contains an array of Person objects.  The "foreach" construct works fine in C#, but in VBA I am only able to loop the old fashioned way.

This VBA code works just fine:

```<code>Dim P As Person
Dim PP As New People

For i = 0 To PP.Count - 1
    Set P = PP(i)
    Debug.Print P.firstName + " " + P.lastName
Next i
</code>```

But this fails at run time ("Object doesn't support this property or method"):

```<code>For Each P In PP
    Debug.Print P.firstName + " " + P.lastName
Next P
</code>```

Here is the C# code (compiled COM visible in VS 2008 for use with Excel VBA  - Office 2010):

```<code>using System;
using System.Collections;
using System.Runtime.InteropServices;

public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }
    public string firstName;
    public string lastName;
}

public class People : IEnumerable
{
    private Person[] _people;                           // array of people
    public Int32 Count() { return _people.Length; }     // method to return array size

    // indexer method to enable People[i] construct, or in VBA: People(i)
    public Person this[Int32 PersonNo] { get { return _people[PersonNo]; } }

    // constructor - hardcode to initialize w 3 people (for testing)
    public People()
    {
        _people = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };
    }

    // test method just to make sure the c# foreach construct works ok
    public void Test()
    {
        foreach (Person P in this) System.Diagnostics.Debug.WriteLine(P.firstName + " " + P.lastName);
    }

    //implementation of basic GetEnumerator
    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }

    //implementation of People GetEnumerator
    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

// People Enumerator class definition
public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}
</code>```

答:
I came across this thread in Feb 2020 whilst experiencing the same problem with a class I wrote as a wrapper for a C# Dictionary.

The get enumerator method in the class is

```<code>    public IEnumerator GetEnumerator()
    {
        foreach (KeyValuePair<dynamic, dynamic> myPair in MyKvp)
        {
            yield return new dynamic[] { myPair.Key, myPair.Value };
        }
    }
</code>```

I found that the DispId(-4) was successful when I added the attribute to the signature in the Interface.

Before (in interface)

```<code>IEnumerator GetEnumerator();
</code>```

Which prodeced an object does not know this methos error in VBA

After (in interface)

```<code>[DispId(-4)]
IEnumerator GetEnumerator();
</code>```

This update allowed me to iterate using a For Each loop in VBA.

Body:
Can anyone instruct me on how to code a C# enumerable class such that the "for each" construct in Excel VBA works properly?  I tried this out with a test class called People that implements IEnumerable and contains an array of Person objects.  The "foreach" construct works fine in C#, but in VBA I am only able to loop the old fashioned way.

This VBA code works just fine:

Dim P As Person
Dim PP As New People

For i = 0 To PP.Count - 1
    Set P = PP(i)
    Debug.Print P.firstName + " " + P.lastName
Next i

But this fails at run time ("Object doesn't support this property or method"):

For Each P In PP
    Debug.Print P.firstName + " " + P.lastName
Next P

Here is the C# code (compiled COM visible in VS 2008 for use with Excel VBA  - Office 2010):

using System;
using System.Collections;
using System.Runtime.InteropServices;

public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }
    public string firstName;
    public string lastName;
}

public class People : IEnumerable
{
    private Person[] _people;                           // array of people
    public Int32 Count() { return _people.Length; }     // method to return array size

    // indexer method to enable People[i] construct, or in VBA: People(i)
    public Person this[Int32 PersonNo] { get { return _people[PersonNo]; } }

    // constructor - hardcode to initialize w 3 people (for testing)
    public People()
    {
        _people = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };
    }

    // test method just to make sure the c# foreach construct works ok
    public void Test()
    {
        foreach (Person P in this) System.Diagnostics.Debug.WriteLine(P.firstName + " " + P.lastName);
    }

    //implementation of basic GetEnumerator
    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }

    //implementation of People GetEnumerator
    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

// People Enumerator class definition
public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

Body:
I came across this thread in Feb 2020 whilst experiencing the same problem with a class I wrote as a wrapper for a C# Dictionary.

The get enumerator method in the class is

    public IEnumerator GetEnumerator()
    {
        foreach (KeyValuePair<dynamic, dynamic> myPair in MyKvp)
        {
            yield return new dynamic[] { myPair.Key, myPair.Value };
        }
    }

I found that the DispId(-4) was successful when I added the attribute to the signature in the Interface.

Before (in interface)

IEnumerator GetEnumerator();

Which prodeced an object does not know this methos error in VBA

After (in interface)

[DispId(-4)]
IEnumerator GetEnumerator();

This update allowed me to iterate using a For Each loop in VBA.