问:
Combine 2 map columns in spark sql
Hello I am using the combine udf from brickhouse to combine to maps for the below example

select combine(map('a',1,'b',0),map('a',0,'c',1))

If does combine the maps but I want to keep the highest value while combining the maps. is the possible?

答:
You can use udf to concat the map to get the key having max value as below-

       val mapConcat = udf((map1: Map[String, Int], map2: Map[String, Int]) => {

      val finalMap = mutable.Map.empty[String, mutable.ArrayBuffer[Int]]
      map1.foreach { case (key: String, value: Int) =>
        if (finalMap.contains(key))
          finalMap(key) :+ key
        else finalMap.put(key, mutable.ArrayBuffer(value))
      }
      map2.foreach { case (key: String, value: Int) =>
        if (finalMap.contains(key))
          finalMap(key) :+ key
        else finalMap.put(key, mutable.ArrayBuffer(value))
      }
      finalMap.mapValues(_.max)
    })
    spark.udf.register("my_map_concat", mapConcat)
    spark.range(2).selectExpr("map('a',1,'b',0)","map('a',0,'c',1)",
      "my_map_concat(map('a',1,'b',0),map('a',0,'c',1))")
      .show(false)
```

<p>Output-</p>

```+----------------+----------------+-------------------------------------+
|map(a, 1, b, 0) |map(a, 0, c, 1) |UDF(map(a, 1, b, 0), map(a, 0, c, 1))|
+----------------+----------------+-------------------------------------+
|[a -> 1, b -> 0]|[a -> 0, c -> 1]|[b -> 0, a -> 1, c -> 1]             |
|[a -> 1, b -> 0]|[a -> 0, c -> 1]|[b -> 0, a -> 1, c -> 1]             |
+----------------+----------------+-------------------------------------+

```

Title: Combine 2 map columns in spark sql

Body:
You can use udf to concat the map to get the key having max value as below-

       val mapConcat = udf((map1: Map[String, Int], map2: Map[String, Int]) => {

      val finalMap = mutable.Map.empty[String, mutable.ArrayBuffer[Int]]
      map1.foreach { case (key: String, value: Int) =>
        if (finalMap.contains(key))
          finalMap(key) :+ key
        else finalMap.put(key, mutable.ArrayBuffer(value))
      }
      map2.foreach { case (key: String, value: Int) =>
        if (finalMap.contains(key))
          finalMap(key) :+ key
        else finalMap.put(key, mutable.ArrayBuffer(value))
      }
      finalMap.mapValues(_.max)
    })
    spark.udf.register("my_map_concat", mapConcat)
    spark.range(2).selectExpr("map('a',1,'b',0)","map('a',0,'c',1)",
      "my_map_concat(map('a',1,'b',0),map('a',0,'c',1))")
      .show(false)

Output-

+----------------+----------------+-------------------------------------+
|map(a, 1, b, 0) |map(a, 0, c, 1) |UDF(map(a, 1, b, 0), map(a, 0, c, 1))|
+----------------+----------------+-------------------------------------+
|[a -> 1, b -> 0]|[a -> 0, c -> 1]|[b -> 0, a -> 1, c -> 1]             |
|[a -> 1, b -> 0]|[a -> 0, c -> 1]|[b -> 0, a -> 1, c -> 1]             |
+----------------+----------------+-------------------------------------+


来源: stackexchange

问:
terraform copy/upload files to aws ec2 instance
We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.

we tried

file provisioner :
but its not wokring , and read this option does not work with all terraform version

```<code>      provisioner "file" {
        source      = "abc.sh"
        destination = "/home/ec2-user/basic2.sh"
      }
</code>```

tried data template file option

```<code>    data "template_file" "userdata_line" {
      template = <<EOF
    #!/bin/bash
    mkdir /home/ec2-user/files2
    cd /home/ec2-user/files2
    sudo touch basic2.sh
    sudo chmod 777 basic2.sh
    base64 basic.sh |base64 -d >basic2.sh
    EOF
    }
</code>```

tried all option but none of them working.

could u please help or advise .

I am new to terraform so struggling on this from long time.

答:
I used provisioner "file" just for that, no issues...

but you do have to provide a connection:

```<code>resource "aws_instance" "foo" {
...
  provisioner "file" {
    source      = "~/foobar"
    destination = "~/foobar"

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/Downloads/AWS_keys/test.pem")}"
      host        = "${self.public_dns}"
    }
  }
...
}
</code>```

here are some code examples:

https://github.com/heldersepu/hs-scripts/blob/master/TerraForm/ec2_ubuntu.tf#L21

ContentLicense: CC BY-SA 4.0

Body:
We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.

we tried

file provisioner :
but its not wokring , and read this option does not work with all terraform version

      provisioner "file" {
        source      = "abc.sh"
        destination = "/home/ec2-user/basic2.sh"
      }

tried data template file option

    data "template_file" "userdata_line" {
      template = <<EOF
    #!/bin/bash
    mkdir /home/ec2-user/files2
    cd /home/ec2-user/files2
    sudo touch basic2.sh
    sudo chmod 777 basic2.sh
    base64 basic.sh |base64 -d >basic2.sh
    EOF
    }

tried all option but none of them working.

could u please help or advise .

I am new to terraform so struggling on this from long time.

Body:
I used provisioner "file" just for that, no issues...

but you do have to provide a connection:

resource "aws_instance" "foo" {
...
  provisioner "file" {
    source      = "~/foobar"
    destination = "~/foobar"

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/Downloads/AWS_keys/test.pem")}"
      host        = "${self.public_dns}"
    }
  }
...
}

here are some code examples:

https://github.com/heldersepu/hs-scripts/blob/master/TerraForm/ec2_ubuntu.tf#L21


问:
Returning a vector of references from a Class
I have a function called FunctionCombiner (of base type ValuationFunction) which contains other valuationFunctions like so:

```<code>class FunctionCombiner : public valuationFunction
{
public:
    FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
    void ValueInstrument();
    std::vector<std::string> GetuniqueIdentifier() const;
    void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor);
    void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor);
    virtual valuationFunction* clone() const;
private:
    std::vector<std::shared_ptr<valuationFunction>> Inner;
};
</code>```

What I need to do is create a function that returns references to these "inner" functions but I'm unsure how to go about it, everything I've tried seems to fail syntactically. If I was returning just a refence (not inside a vector) I would go about it like this:

```<code>valuationFunction& FunctionCombiner ::GetInner()
{
    return *this;
}
</code>```

I've tried returning something like std::vector< valuationFunction&> but the compiler doesn't seem to like that very much. What is the correct way to go about this?

The end goal is to collect all these references to the inner functions (from several FunctionCombiners or different valuationFunctions) in order to compare them and sort out duplicates later on.

EDIT: From the answer I've now implemented the function that returns the inner reference like follows:
My functions look like this now for the "inner" classes:

```<code>std::vector<std::reference_wrapper<valuationFunction>> StockPriceFunction::GetInnerReference()
    {
        std::vector<std::reference_wrapper<valuationFunction>> innerVector(1);
        innerVector.push_back(std::ref(*this));
        return innerVector;
    }
</code>```

And like this for the combiner:

```<code>std::vector<std::reference_wrapper<valuationFunction>> FunctionCombiner::GetInnerReference()
{
    std::vector<std::reference_wrapper<valuationFunction>> innerVector(Inner.size());
    for (unsigned long i = 0; i < Inner.size(); ++i) {
        std::vector<std::reference_wrapper<valuationFunction>> innerInnerVector = Inner[i]->GetInnerReference();
        innerVector.insert(innerVector.end(), innerInnerVector.begin(), innerInnerVector.end());
    }
    return innerVector;
}
</code>```

But it's not compiling and giving me strange errors, what am I doing wrong here?

答:
In order to store references in a std::vector you'll have to use an std::reference_wrapper.

```<code>#include <functional>
#include <vector>

int main( )
{
    std::vector<int> ints{ 1, 2, 3, 4, 5 };
    std::vector<std::reference_wrapper<int>> references;

    for( auto& i : ints )
        references.push_back( i );

    auto& ref{ references[ 1 ].get( ) };
    ref += 20;

    // Prints 22.
    std::cout << ints[ 1 ] << '\n';
}
</code>```

Here is another example which more closely resembles what you're trying to do (I also included what headers you need).

```<code>#include <iostream>
#include <functional>
#include <vector>
#include <memory>

struct ValuationFunction
{
    ValuationFunction( int prop )
        : property{ prop } { }
    int property;
};

// Converts the vector of pointers to a vector
// of references.
static std::vector<std::reference_wrapper<ValuationFunction>>
    ToReference( const std::vector<std::shared_ptr<ValuationFunction>>& pointers )
{
    std::vector<std::reference_wrapper<ValuationFunction>> references;
    references.reserve( pointers.size( ) );

    for ( auto& pointer : pointers )
        references.emplace_back( *pointer );

    return references;
}

int main( )
{
    std::vector<std::shared_ptr<ValuationFunction>> pointers
    {
        std::make_shared<ValuationFunction>( 1 ),
        std::make_shared<ValuationFunction>( 2 ),
        std::make_shared<ValuationFunction>( 3 ),
        std::make_shared<ValuationFunction>( 4 )
    };

    auto references{ ToReference( pointers ) };

    // Use 'std::reference_wrapper.get( )' to get
    // access to the contained reference.
    for ( auto& ref : references )
        std::cout << "Before: " << ref.get( ).property << '\n';

    // Change the property value of each 'ValuationFunction'
    // in the original list.
    for ( auto& pointer : pointers )
        pointer->property += 10;

    // Re-print the property value of each reference and see
    // how they have all increased by 10.
    for ( auto& ref : references )
        std::cout << "After: " << ref.get( ).property << '\n';
}
</code>```

Body:
I have a function called FunctionCombiner (of base type ValuationFunction) which contains other valuationFunctions like so:

class FunctionCombiner : public valuationFunction
{
public:
    FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
    void ValueInstrument();
    std::vector<std::string> GetuniqueIdentifier() const;
    void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor);
    void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor);
    virtual valuationFunction* clone() const;
private:
    std::vector<std::shared_ptr<valuationFunction>> Inner;
};

What I need to do is create a function that returns references to these "inner" functions but I'm unsure how to go about it, everything I've tried seems to fail syntactically. If I was returning just a refence (not inside a vector) I would go about it like this:

valuationFunction& FunctionCombiner ::GetInner()
{
    return *this;
}

I've tried returning something like std::vector< valuationFunction&> but the compiler doesn't seem to like that very much. What is the correct way to go about this?

The end goal is to collect all these references to the inner functions (from several FunctionCombiners or different valuationFunctions) in order to compare them and sort out duplicates later on.

EDIT: From the answer I've now implemented the function that returns the inner reference like follows:
My functions look like this now for the "inner" classes:

std::vector<std::reference_wrapper<valuationFunction>> StockPriceFunction::GetInnerReference()
    {
        std::vector<std::reference_wrapper<valuationFunction>> innerVector(1);
        innerVector.push_back(std::ref(*this));
        return innerVector;
    }

And like this for the combiner:

std::vector<std::reference_wrapper<valuationFunction>> FunctionCombiner::GetInnerReference()
{
    std::vector<std::reference_wrapper<valuationFunction>> innerVector(Inner.size());
    for (unsigned long i = 0; i < Inner.size(); ++i) {
        std::vector<std::reference_wrapper<valuationFunction>> innerInnerVector = Inner[i]->GetInnerReference();
        innerVector.insert(innerVector.end(), innerInnerVector.begin(), innerInnerVector.end());
    }
    return innerVector;
}

But it's not compiling and giving me strange errors, what am I doing wrong here?

Body:
In order to store references in a std::vector you'll have to use an std::reference_wrapper.

#include <functional>
#include <vector>

int main( )
{
    std::vector<int> ints{ 1, 2, 3, 4, 5 };
    std::vector<std::reference_wrapper<int>> references;

    for( auto& i : ints )
        references.push_back( i );

    auto& ref{ references[ 1 ].get( ) };
    ref += 20;

    // Prints 22.
    std::cout << ints[ 1 ] << '\n';
}

Here is another example which more closely resembles what you're trying to do (I also included what headers you need).

#include <iostream>
#include <functional>
#include <vector>
#include <memory>

struct ValuationFunction
{
    ValuationFunction( int prop )
        : property{ prop } { }
    int property;
};

// Converts the vector of pointers to a vector
// of references.
static std::vector<std::reference_wrapper<ValuationFunction>>
    ToReference( const std::vector<std::shared_ptr<ValuationFunction>>& pointers )
{
    std::vector<std::reference_wrapper<ValuationFunction>> references;
    references.reserve( pointers.size( ) );

    for ( auto& pointer : pointers )
        references.emplace_back( *pointer );

    return references;
}

int main( )
{
    std::vector<std::shared_ptr<ValuationFunction>> pointers
    {
        std::make_shared<ValuationFunction>( 1 ),
        std::make_shared<ValuationFunction>( 2 ),
        std::make_shared<ValuationFunction>( 3 ),
        std::make_shared<ValuationFunction>( 4 )
    };

    auto references{ ToReference( pointers ) };

    // Use 'std::reference_wrapper.get( )' to get
    // access to the contained reference.
    for ( auto& ref : references )
        std::cout << "Before: " << ref.get( ).property << '\n';

    // Change the property value of each 'ValuationFunction'
    // in the original list.
    for ( auto& pointer : pointers )
        pointer->property += 10;

    // Re-print the property value of each reference and see
    // how they have all increased by 10.
    for ( auto& ref : references )
        std::cout << "After: " << ref.get( ).property << '\n';
}


问:
React loop with useState
I'm trying to grab a todo and add it to an object of todos, can you tell me what's the problem here?

Newbie in React.

```<code>import React, { useState } from "react"

function Content() {
  const [todo, setTodo] = useState("") // todo: user input
  const [todos, setTodos] = useState({}) // todos: object

  function handleClick(e) {
    e.preventDefault()
    setTodos({ ...todo, todos })
  }
  return (
    <>
      <h1>Todos</h1>
      <form>
        <input onChange={(e) => setTodo(e.target.value)} type="text" placeholder="Add Todo Here" />
        <button onClick={handleClick}>Add</button>
      </form>
      {console.log(todos)}
      {todos.map((todo) => todo)}
    </>
  )
}

export default Content
</code>```

答:
```<code>    function Content() {
  const [todo, setTodo] = useState("") // todo: user input
  const [todos, setTodos] = useState([]) // todos: object

  function handleClick(e) {
    e.preventDefault()
    setTodos([ ...todos, todo ])
  }
  return (
    <>
      <h1>Todos</h1>
      <form>
        <input onChange={(e) => setTodo(e.target.value)} type="text" placeholder="Add Todo Here" />
        <button onClick={handleClick}>Add</button>
      </form>
      {console.log(todos)}
      {todos.map((todo) => todo)}
    </>
  )
}

export default function App() {
  return (
    <div className="App">
      <Content />
    </div>
  );
}
</code>```

You've mixed todos and todo.. You were trying to spread todo which is a string not an array.

and also, you've not set array right. it should be [] not {}.
:)

here's a code sandbox with a working example:
https://codesandbox.io/s/modest-cerf-soxii

here's the diff between your code and mine:
https://www.diffchecker.com/nBReZt19

Title: React loop with useState

Body:
I'm trying to grab a todo and add it to an object of todos, can you tell me what's the problem here?

Newbie in React.

import React, { useState } from "react"

function Content() {
  const [todo, setTodo] = useState("") // todo: user input
  const [todos, setTodos] = useState({}) // todos: object

  function handleClick(e) {
    e.preventDefault()
    setTodos({ ...todo, todos })
  }
  return (
    <>

Todos

      <form>
        <input onChange={(e) => setTodo(e.target.value)} type="text" placeholder="Add Todo Here" />
        <button onClick={handleClick}>Add</button>
      </form>
      {console.log(todos)}
      {todos.map((todo) => todo)}
    </>
  )
}

export default Content

Body:
    function Content() {
  const [todo, setTodo] = useState("") // todo: user input
  const [todos, setTodos] = useState([]) // todos: object

  function handleClick(e) {
    e.preventDefault()
    setTodos([ ...todos, todo ])
  }
  return (
    <>
      <h1>Todos</h1>
      <form>
        <input onChange={(e) => setTodo(e.target.value)} type="text" placeholder="Add Todo Here" />
        <button onClick={handleClick}>Add</button>
      </form>
      {console.log(todos)}
      {todos.map((todo) => todo)}
    </>
  )
}

export default function App() {
  return (
    <div className="App">
      <Content />
    </div>
  );
}

You've mixed todos and todo.. You were trying to spread todo which is a string not an array.

and also, you've not set array right. it should be [] not {}.
:)

here's a code sandbox with a working example:
https://codesandbox.io/s/modest-cerf-soxii

here's the diff between your code and mine:
https://www.diffchecker.com/nBReZt19


问:
Why is border collapse and spacing not working when you target only the Table Head (TH) inside a Table?
My HTML:

```<code><table style="width:100%">

    <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>

    </tr>

    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>

    </tr>

    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>

    </tr>

</table>
</code>```

My CSS:

```<code>table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}
</code>```

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

答:
The border-collapse property can only be applied to
 elements - not individual rows or cells

https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse

Body:
My HTML:

        First name
        Last name
        Age

        Jill
        Smith
        50

        Eve
        Jackson
        94

My CSS:

table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

Body:
The border-collapse property can only be applied to <table> elements - not individual rows or cells

https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse


问:
LARAVEL 7 - How to pass variables to views
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

```<code>protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}
</code>```

Project.php model

```<code>protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}
</code>```

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

```<code><div class="jumbotron">
     <h1>{{ $company->name }}</h1>
       <p class="lead">{{ $company->description }}</p>
    </div>

<div class="row">
    @foreach($company->projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

```<code>public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}
</code>```

And access variable in show.blade.php like so

```<code>    <div class="jumbotron">

    <h1>{{ $company->name }}</h1>
    <p class="lead">{{ $company->description }}</p>
</div>
<div class="row">

    @foreach($projects as $project)
    <div class="col-lg-4">
        <h2>{{ $project->name }}</h2>
        <p class="text-danger">{{ $project->description }}</p>
        <p><a class="btn btn-primary" href="/projects/{{ $project->id }}" role="button">View Projects »</a></p>
    </div>
    @endforeach
</div>
</code>```

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

```<code>    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');
</code>```

答:
You have to namespace Project class properly

Make sure file name is Project.php

Make sure inside Project.php namespace declaration is correct: namespace App;

Make sure class name inside Project.php is 'Project' : class Project extends Model { ...

Make sure you have imported it in controller. use App\Project

After all that done you will not get error:

Class 'App/Project' not found

You have correctly done passing variable in view but have a look here for another examples and methods passing about it:
https://laravel.com/docs/7.x/views

Hope this helps you

Body:
I have two tables, Companies and Projects. A company hasMany projects and a project belongsTo a company.

Company.php model

protected $fillable = [
    'id', 'name', 'description'
];

public function projects()
{
    return $this->hasMany('App/Project');
}

Project.php model

protected $fillable = [
    'name', 'description', 'company_id', 'days'
];

public function company()
{
    return $this->belongsTo('App/Company');
}

From my index.blade.php, I list the companies only and I have made them clickable so that when a user clicks on a company listed, they are taken to show.blade.php where the name of the company and the projects that belong to that company are displayed like so.

{{ $company->name }}

{{ $company->description }}

    @foreach($company->projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting an undefined variable $project error. So I decided to declare variable in my show() function of the CompaniesController.php like so

public function show(Company $company)
{
    $company = Company::find($company->id);
    $projects = Company::find(1)->projects;

    return view('companies.show', ['company' => $company, 'projects' => $projects]);
}

And access variable in show.blade.php like so

{{ $company->name }}

{{ $company->description }}

    @foreach($projects as $project)

{{ $project->name }}

{{ $project->description }}

id }}" role="button">View Projects »

    @endforeach

Now am getting a Class 'App/Project' not found error when I access show.blade.php. I am having a challenge passing company projects to the view. Any help will be appreciated. Here are my routes;

    Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::resource('companies', 'CompaniesController');
Route::resource('projects', 'ProjectsController');


问:
Would like to know how expensive is SpriteRenderer.color as I am planning to use it to tint all of the sprites on my screen?
I am working on a 2D project and I need to change the tint of all sprites on the screen. I am planning to user SpriteRenderer's color property. But I am not sure if it will be cost-effective to do so or a shader will be a good choice. It is a sidescrolling platformer project and I don't want the framerate to drop significantly.

PS: I am planning to develop this game for mobile devices

答:
In short yes this is a good and efficient way to set your sprites color. So you know setting the sprite render's color set the color on each vertex. The upside is less draw calls which is usually an issue on mobile especially android.

It's always a good thing to double check your draw calls often by opening the Stats tab in the game view window (Batches). Changing color of individual sprites via the property shouldn't increment that number.


问:
on languages that can link to c++
As I was reflecting on this subject, it seemed to me that if a language is implemented in C++, it might well have a mechanism for linking to C++. As I recall, Java is this way through JNI, though I don't really remember if it goes through C++ or plain C.

However, it seems that in general languages don't link to C++, and are accessible to C++ only through C for various reasons.

So, out of curiosity,

What languages are there that can link to C++ and how and to what extent?

(No credit for the aforementioned C bridge unless it is done in an elegant or interesting way, like Boost.Python)

答: Looked at SWIG lately?</p>

OwnerDisplayName: Ellery Newcomer

ContentLicense: CC BY-SA 2.5

Title: on languages that can link to c++

Body: Looked at SWIG lately?

OwnerDisplayName: greyfade


问:
XCode needs to be installed every time to detect iOS devices! Why? Any Solution?
XCode needs to be installed on every start up to detect iOS devices. Otherwise devices didn't  get detect. Why is it so? What to do? Any solutions?</p>

答:
You will have to register the UDID of every iOS device used for development, in the provisioning profile provided in apple developer account.

After registering the device, download the provisioning profile and add to your device.

ContentLicense: CC BY-SA 3.0


问:
set column width of a gridview in asp.net
I dragged and dropped a GridView from toolbox to Aspx page.the design code looks like this

```<code><asp:GridView ID="gridview1" runat="server"   style="text-align:center;width: 1327px;"
    CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True"
    EnableSortingAndPagingCallbacks="True" PageSize="50" AutoGenerateEditButton="True">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"
        Height="12px" VerticalAlign="Bottom" Width="12px" Wrap="False" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</code>```

I have a column by name Address in database.The table is bound to this grid view using following VB.NET code

```<code> Dim ds as Data.DataSet
 Dim da As New OleDbDataAdapter("select col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,Address from table, con)
        da.Fill(ds)
        gridviewrealestate.DataSource = ds
        gridviewrealestate.DataBind()
</code>```

Now,When the gridview is displayed,the columns are very close to each other due to large information present in Address Column.I want to set the Address Column to a particular width.
Please help me how to do this.

答:
There are two steps:

You must set an appropriate width for GridView like this: Width="2000px".

You can set width of Colum by setting [ItemStyle-Width] Like this: ItemStyle-Width="300px".

**  You can set width by setting fixed Pixels like "150 px" or by percentage like"10%".

Body:
I dragged and dropped a GridView from toolbox to Aspx page.the design code looks like this

<asp:GridView ID="gridview1" runat="server"   style="text-align:center;width: 1327px;"
    CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True"
    EnableSortingAndPagingCallbacks="True" PageSize="50" AutoGenerateEditButton="True">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"
        Height="12px" VerticalAlign="Bottom" Width="12px" Wrap="False" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>

I have a column by name Address in database.The table is bound to this grid view using following VB.NET code

 Dim ds as Data.DataSet
 Dim da As New OleDbDataAdapter("select col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,Address from table, con)
        da.Fill(ds)
        gridviewrealestate.DataSource = ds
        gridviewrealestate.DataBind()

Now,When the gridview is displayed,the columns are very close to each other due to large information present in Address Column.I want to set the Address Column to a particular width.
Please help me how to do this.


问:
Xcode - Find references to Swift variable
How can you find all references to a Swift class variable in Xcode?

The answers I've seen (such as the selected answer of Finding all references of a variable or a method in Xcode4) are only applicable to Objective C.

答: Control-click on the symbol and click Find > Find Selected Symbol in Workspace.


问:
Surprising performance degradation with std::vector and std::string
I am processing really large text file in following way:

```<code>class Loader{
    template<class READER>
    bool loadFile(READER &reader){
        /* for each line of the input file */ {
            processLine_(line);
        }
    }

    bool processLine_(std::string_view line){
        std::vector<std::string> set; // <-- here
        std::string buffer;           // <-- here

        // I can not do set.reserve(),
        // because I have no idea how much items I will put.

        // do something...
    }

    void printResult(){
        // print aggregated result
    }
}
</code>```

The processing of 143,000,000 records take around 68 minutes.

So I decided to do some very tricky optimizations with several std::array buffers. Result was about 62 minutes.

However the code become very unreadable so I decided not to use them in production.

Then I decided to do partial optimization, e.g.

```<code>class Loader{
    template<class READER>
    bool loadFile(READER &reader);

    std::vector<std::string> set; // <-- here
    std::string buffer;           // <-- here

    bool processLine_(std::string_view line){
        set.clear();

        // do something...
    }

    void printResult();
}
</code>```

I was hoping this will reduce malloc / free (new[] / delete[]) operation from buffer and from the set vector. I realize the strings inside the set vector still dynamically allocate memory.

However result went to 83 minutes.

Note I do not change anything except I move set and buffer on "class" level. I use them only inside processLine_ method.

Why is that?
Locality of reference?

Only explanation I think about is some strings to be small enough and to fit in SSO, but this sounds unlikely.

Using clang with -O3

答:
I did profile and I found that most of the time is spent in a third party C library.

I supposed this library to be very fast, but this was not the case.

I am still puzzling with the slowdown, but even if I optimize it, it wont make such a big difference.

Body:
I am processing really large text file in following way:

class Loader{
    template<class READER>
    bool loadFile(READER &reader){
        /* for each line of the input file */ {
            processLine_(line);
        }
    }

    bool processLine_(std::string_view line){
        std::vector<std::string> set; // <-- here
        std::string buffer;           // <-- here

        // I can not do set.reserve(),
        // because I have no idea how much items I will put.

        // do something...
    }

    void printResult(){
        // print aggregated result
    }
}

The processing of 143,000,000 records take around 68 minutes.

So I decided to do some very tricky optimizations with several std::array buffers. Result was about 62 minutes.

However the code become very unreadable so I decided not to use them in production.

Then I decided to do partial optimization, e.g.

class Loader{
    template<class READER>
    bool loadFile(READER &reader);

    std::vector<std::string> set; // <-- here
    std::string buffer;           // <-- here

    bool processLine_(std::string_view line){
        set.clear();

        // do something...
    }

    void printResult();
}

I was hoping this will reduce malloc / free (new[] / delete[]) operation from buffer and from the set vector. I realize the strings inside the set vector still dynamically allocate memory.

However result went to 83 minutes.

Note I do not change anything except I move set and buffer on "class" level. I use them only inside processLine_ method.

Why is that?
Locality of reference?

Only explanation I think about is some strings to be small enough and to fit in SSO, but this sounds unlikely.

Using clang with -O3


问:
Javascript equivalent for .width() and .height()
What is javascript equivalent for the following jquery code</p>

```<code>  $(document).on({
    mousemove: function(event) {
        widget = $('.widget').last();
        x = event.pageX;
        y = event.pageY;

        widget.width(x); // here is the real problem
        widget.height(y); // here is the real problem
      }
    },
  });
</code>```

答:
Try this one:</p>

```<code>widget = $('.widget').last()[0];
x = event.pageX;
y = event.pageY;

widget.style.width  = `${x}px`;
widget.style.height = `${y}px`;
</code>```

Body:
What is javascript equivalent for the following jquery code

  $(document).on({
    mousemove: function(event) {
        widget = $('.widget').last();
        x = event.pageX;
        y = event.pageY;

        widget.width(x); // here is the real problem
        widget.height(y); // here is the real problem
      }
    },
  });

Body:
Try this one:

widget = $('.widget').last()[0];
x = event.pageX;
y = event.pageY;

widget.style.width  = `${x}px`;
widget.style.height = `${y}px`;


问:
Deploy Lambda in root rather than in 'latest' with claudiajs
According to claudiajs tutorial and many other tutorials, by default, it's always deployed in latest folder rather than the root.

Is there a way to deploy to the root (i.e. https://8x7uh8ho5k.execute-api.us-east-1.amazonaws.com), rather than in latest folder (i.e. https://8x7uh8ho5k.execute-api.us-east-1.amazonaws.com/latest)?

答:
I'm not familiar with Claudia.js, I'll explain this from the API Gateway perspective. The latest value after the API Gateway invoke URL is actually the API Gateway Stage. A stage is used to deploy the changes made to the API Gateway's resources so that it is available when you hit the invoke URL. You can create multiple stages so as to maintain different versions of your API, say "dev" and "production". However, a stage is required and you cannot deploy changes to "root". The invoke URL would look like:

```<code>https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/
</code>```

If you don't want to specify the stage name when invoking the API, you could look into using Custom Domain Names.

If you'd like to change the stage name when deploying the API with Claudia.js, look into the documentation for Claudia to check if that is possible.

Body:
I'm not familiar with Claudia.js, I'll explain this from the API Gateway perspective. The latest value after the API Gateway invoke URL is actually the API Gateway Stage. A stage is used to deploy the changes made to the API Gateway's resources so that it is available when you hit the invoke URL. You can create multiple stages so as to maintain different versions of your API, say "dev" and "production". However, a stage is required and you cannot deploy changes to "root". The invoke URL would look like:

https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/

If you don't want to specify the stage name when invoking the API, you could look into using Custom Domain Names.

If you'd like to change the stage name when deploying the API with Claudia.js, look into the documentation for Claudia to check if that is possible.


问:
shacl validation error for a property which points to external file
data_file is at this url: https://schema.repronim.org/rl/activities/PHQ-9/items/phq9_8

I've written a shacl shape for the above data file. however, i get an error when i try to validate. In the above data file, the key responseOptions points to an external jsonld file --  which is when the error occurs. if i embed the external file in the data file itself, there is no error.
I've used this shape for responseOptions:

```<code> sh:property [
        sh:path reproterms:valueconstraints ;
        sh:or ( [ sh:nodeKind sh:IRI ] [ sh:node reproterms:ResponseOptionsShape ] ) ;
   ] .
</code>```

The error thrown is:

```<code>Traceback (most recent call last):
  File "validation/test.py", line 146, in <module>
    serialize_report_graph=True)
  File "/Users/sanuann/envs/trial/lib/python3.7/site-packages/pyshacl/validate.py", line 259, in validate
    do_owl_imports=False)  # no imports on data_graph
  File "~/envs/trial/lib/python3.7/site-packages/pyshacl/rdfutil/load.py", line 110, in load_from_source
    first_char = source[0]
IndexError: string index out of range
</code>```

Is the above shape correct? What am I doing wrong?

答: Your datatype constraint sh:datatype sh:IRI is off. The object of a sh:datatype triple must be an rdf datatype, such as xsd:string. I think you wanted to check for sh:nodeKind sh:IRI.

Body:
data_file is at this url: https://schema.repronim.org/rl/activities/PHQ-9/items/phq9_8

I've written a shacl shape for the above data file. however, i get an error when i try to validate. In the above data file, the key responseOptions points to an external jsonld file --  which is when the error occurs. if i embed the external file in the data file itself, there is no error.
I've used this shape for responseOptions:

 sh:property [
        sh:path reproterms:valueconstraints ;
        sh:or ( [ sh:nodeKind sh:IRI ] [ sh:node reproterms:ResponseOptionsShape ] ) ;
   ] .

The error thrown is:

Traceback (most recent call last):
  File "validation/test.py", line 146, in <module>
    serialize_report_graph=True)
  File "/Users/sanuann/envs/trial/lib/python3.7/site-packages/pyshacl/validate.py", line 259, in validate
    do_owl_imports=False)  # no imports on data_graph
  File "~/envs/trial/lib/python3.7/site-packages/pyshacl/rdfutil/load.py", line 110, in load_from_source
    first_char = source[0]
IndexError: string index out of range

Is the above shape correct? What am I doing wrong?


问:
Java function to detect valid webpage
I am trying to write a Java program that will load pages pointed to by valid links and report other links as broken. My problem is that the Java URL will download the appropriate page if the url is valid, and the search-engine results for the url if the url is invalid.

Is there a Java function that detects if the url resolves to a legitimate page . . . thanks very much,

Joel

答: HttpURLConnection#getResponseCode will give you an HTTP status code</p>

Title: Java function to detect valid webpage


问:
right to left direction not working properly on urdu font
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <span class='r2l'>خدا کرے کے میری عرض پاک پے اترے</span>
  <span class='r2l'>وہ فصل گل جسے </span>
  <span class='r2l'>اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو</span>
  <span class='r2l'>یہاں جو سبزہ اگے ہمیشہ سبز رہے</span>
  <span class='r2l'>اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا</span>
  <span class='r2l'> اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</span>
</body>

</html></code>```

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

答:
I worked around the problem using float:right. This doesn't completely qualifies to what i need, but i worked somehow in my scenario.

.r2l {
  direction: rtl;
  float:right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <span class='r2l'>خدا کرے کے میری عرض پاک پے اترے</span>
  <span class='r2l'>وہ فصل گل جسے </span>
  <span class='r2l'>اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو</span>
  <span class='r2l'>یہاں جو سبزہ اگے ہمیشہ سبز رہے</span>
  <span class='r2l'>اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا</span>
  <span class='r2l'> اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</span>
</body>

</html></code>```

Body:
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}

  خدا کرے کے میری عرض پاک پے اترے
  وہ فصل گل جسے
  اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو
  یہاں جو سبزہ اگے ہمیشہ سبز رہے
  اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا
   اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

Body:
I worked around the problem using float:right. This doesn't completely qualifies to what i need, but i worked somehow in my scenario.

.r2l {
  direction: rtl;
  float:right;
}

<html>

<head>
</head>

<body>
  <span class='r2l'>خدا کرے کے میری عرض پاک پے اترے</span>
  <span class='r2l'>وہ فصل گل جسے </span>
  <span class='r2l'>اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو</span>
  <span class='r2l'>یہاں جو سبزہ اگے ہمیشہ سبز رہے</span>
  <span class='r2l'>اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا</span>
  <span class='r2l'> اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</span>
</body>

</html>


问:
How do I turn colon separated values into comma separated values in python?
If i have a string of words separated by colons or hyphens what would be the best method of putting them into a list? </p>

```<code>string = ('car:boat:motorcycle:plane')
</code>```

<p>into </p>

```<code>list = ['car', 'boat', 'motorcycle', 'plane']
</code>```

答:
Use the split method and pass the separator

string.split(":")

Default separator is any whitespace.

An optional second argument, maxsplit, will tell Python to split only that number of times:

string.split(":", 2) results in ['car', 'boat', 'motorcycle:plane']

Body:
If i have a string of words separated by colons or hyphens what would be the best method of putting them into a list?

string = ('car:boat:motorcycle:plane')

into

list = ['car', 'boat', 'motorcycle', 'plane']


问:
Avoid duplicated code if the only diffence is a method call in a for loop
I have this two methods written in java:

```<code>public void fillRect(float x, float y, float width, float height, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++){
                // here is the difference between the other method
                setPixel(xx,yy,color);

            }
        }
    }
</code>```

```<code>public void fillRect(float x, float y, float width, float height,float transparency, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++) {
                // here is the difference between the other method
                // this Method is slower then setPixel()
                plot(xx,yy,transparency,color);
            }
        }
    }
</code>```

I'm used to write a method like this validateBoundary(float* x,float* y, float* width, float *height): void which includes the 'if-statments' and call it instead but clearly this won't be happen in Java.
What is the solution for problems like this? We could write a Methode validateBoundaryWidthf(xi, widhtf, pixelWitdth) which returns the  the new value for widthf. But something like this:

```<code>if (xi < 0) {
     widthf += xi;
     xi = 0;
}
</code>```

can't be a solved by this because there is only one return value. Sure I could create a POJO with the attributes widthf and xi an return this instead but I assume this is comes expensive in terms of cpu / memory. So what is the proper way solving this duplicated code issue?

答: You can define public void fillRect(bool plot, float x, float y, float width, float height,float transparency, Color color) where plot indicates which implementation should be used. When false use the first option. When true use the second option.

Body:
I have this two methods written in java:

public void fillRect(float x, float y, float width, float height, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++){
                // here is the difference between the other method
                setPixel(xx,yy,color);

            }
        }
    }

public void fillRect(float x, float y, float width, float height,float transparency, Color color) {
        int xi = mapX(x);
        int yi = mapY(y);

        int heightf =  mapHeight(height);
        int widthf  = mapWidth(width);

        if (xi + widthf > pixelWidth){
            widthf -= xi + widthf - pixelWidth;
        }
        if (yi + heightf > pixelHeight){
            heightf -= yi + heightf - pixelHeight;
        }

        if (xi < 0) {
            widthf += xi;
            xi = 0;

        }
        if (yi < 0) {
            heightf += yi;
            yi = 0;
        }

        for (int xx = xi; xx < xi + widthf; xx++){
            for (int yy = yi; yy < yi + heightf; yy++) {
                // here is the difference between the other method
                // this Method is slower then setPixel()
                plot(xx,yy,transparency,color);
            }
        }
    }

I'm used to write a method like this validateBoundary(float* x,float* y, float* width, float *height): void which includes the 'if-statments' and call it instead but clearly this won't be happen in Java.
What is the solution for problems like this? We could write a Methode validateBoundaryWidthf(xi, widhtf, pixelWitdth) which returns the  the new value for widthf. But something like this:

if (xi < 0) {
     widthf += xi;
     xi = 0;
}

can't be a solved by this because there is only one return value. Sure I could create a POJO with the attributes widthf and xi an return this instead but I assume this is comes expensive in terms of cpu / memory. So what is the proper way solving this duplicated code issue?


问:
Why does Java's BitSet internally store long array but use int for set method?
According to the BitSet implementation, it internally uses an array of longs:

```<code>/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;
</code>```

But for the set method it uses int:

```<code>public void set(int bitIndex) {...}
</code>```

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.

答:
Usually you use bit sets to index into something else. Let’s say you use this bitset to index into an array.

```<code>BitSet b = new BitSet();
b.set(2147483647);
ArrayList<X> items = new ArrayList<X>();
// ...add a looot of elements to the ArrayList...
// then:
X item = items.get(b.nextSetBit(0));
</code>```

To make this work, the array list must contain 2,147,483,648 elements, and it would at least use 2GB of RAM (assuming each element requires at least 1 byte of storage), which would crash Java.

Body:
According to the BitSet implementation, it internally uses an array of longs:

/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;

But for the set method it uses int:

public void set(int bitIndex) {...}

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.

Body:
Usually you use bit sets to index into something else. Let’s say you use this bitset to index into an array.

BitSet b = new BitSet();
b.set(2147483647);
ArrayList<X> items = new ArrayList<X>();
// ...add a looot of elements to the ArrayList...
// then:
X item = items.get(b.nextSetBit(0));

To make this work, the array list must contain 2,147,483,648 elements, and it would at least use 2GB of RAM (assuming each element requires at least 1 byte of storage), which would crash Java.


问:
I can't get json.loads to work - don't understand error message
New to development and python and trying to create a json file.

I'm trying to generate a list of people with a start time and onboarding time and incident time:

```<code>import datetime
import random
import math
import json
import numpy as np

# generate list of candidates

cand = input("Enter number of candidates: ")
cand = int(cand)
startRange = 0.06 # standard deviation (scale)
startTime = 9.30 #mean (loc)
onboardRange = 0.5
onboardTime = 4.5
incidenceRatio = [0,0,0,0,1] #1 in 5 chance an incident arises

def calCan(): # creates a dictionary of candidates with start times, onboarding, incident times.
    candattr = []
    candidates = {"candidates":candattr}
    a = 1
    while a <= cand:
        b = np.random.normal(loc=startTime, scale=startRange, size=(1, 1)) # startime
        c = np.random.normal(loc=onboardTime, scale=onboardRange, size=(1, 1)) # onboarding time
        d = random.choice(incidenceRatio) * np.random.normal(loc=onboardTime, scale=onboardRange, size=(1, 1)) # incident time - random.choice(incidenceRatio) - takes a random selection from incidenceRation list defined above.
        btime = datetime.time(int(b//1),int(math.ceil(100 * (59 * (b % 1))/100)), 0)#converts bnum into time
        ctime = datetime.time(0,int(c//1),int(math.ceil(100 * (59 * (c % 1))/100)))
        dtime = datetime.time(0,int(d//1) ,int(math.ceil(100 * (59 * (d % 1))/100)))
        candattr.append({
        "name": "candidate {}".format(a),
        "startTime": "{}".format(btime),#json doesn't recognize time so have to store as a string
        "onboardTime": "{}".format(ctime),
        "incidentTime": "{}".format(dtime)
        })
        a = a + 1
    return candidates

</code>```

And then I'm trying to put this into a Json.

I can get the JSON to print just fine using

```<code>candidateList = calCan()

print(json.dumps(candidateList, indent=4))
</code>```

it returns something like this:

```<code>{
    "candidates": [
        {
            "name": "candidate 1",
            "startTime": "09:17:00",
            "onboardTime": "00:03:37",
            "incidentTime": "00:04:04"
        },
        {
            "name": "candidate 2",
            "startTime": "09:16:00",
            "onboardTime": "00:04:19",
            "incidentTime": "00:00:00"
        },
        {
            "name": "candidate 3",
            "startTime": "09:15:00",
            "onboardTime": "00:04:13",
            "incidentTime": "00:03:25"
        }
    ]
}
</code>```

but when i try to manipulate it using json.loads with

```<code>candidateList = calCan()
candidateList = str(candidateList)
data = json.loads((candidateList)
</code>```

I get all sorts of horrible errors that I can't make heads nor tail of:

```<code>Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.loads(candidateList)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

</code>```

If I try and add double quotes to (candidateList):

```<code>data = json.loads("candidateList")
</code>```

It still doesn't get me anywhere

```<code>Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.loads(("candidateList"))
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

Following some advice below - i have stopped converting candidateList into a string and am using json.load instead.

```<code>candidateList = calCan()
data = json.load(candidateList)
</code>```

this returns:

```<code>Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.load(candidateList)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'
</code>```

答:
In a properly formatted JSON, strings need to be double-quoted but in a string literal for a dictionary, string keys and values are given as single-quoted strings. This is the key difference between json.dumps(candidateList) and str(candidateList) (where candidateList = calCan()).

The first is

```<code>'{"candidates": [{"name": "candidate 1", "startTime": "09:18:00", "onboardTime": "00:04:10", "incidentTime": "00:00:00"}, {"name": "candidate 2", "startTime": "09:18:00", "onboardTime": "00:04:23", "incidentTime": "00:00:00"}, {"name": "candidate 3", "startTime": "09:19:00", "onboardTime": "00:05:08", "incidentTime": "00:00:00"}, {"name": "candidate 4", "startTime": "09:14:00", "onboardTime": "00:05:17", "incidentTime": "00:00:00"}, {"name": "candidate 5", "startTime": "09:12:00", "onboardTime": "00:04:38", "incidentTime": "00:00:00"}]}'
</code>```

and the second is

```<code>"{'candidates': [{'name': 'candidate 1', 'startTime': '09:18:00', 'onboardTime': '00:04:10', 'incidentTime': '00:00:00'}, {'name': 'candidate 2', 'startTime': '09:18:00', 'onboardTime': '00:04:23', 'incidentTime': '00:00:00'}, {'name': 'candidate 3', 'startTime': '09:19:00', 'onboardTime': '00:05:08', 'incidentTime': '00:00:00'}, {'name': 'candidate 4', 'startTime': '09:14:00', 'onboardTime': '00:05:17', 'incidentTime': '00:00:00'}, {'name': 'candidate 5', 'startTime': '09:12:00', 'onboardTime': '00:04:38', 'incidentTime': '00:00:00'}]}"
</code>```

both

```<code>data = json.loads(json.dumps(candidateList))
</code>```

as well as

```<code>data = json.dumps(str(candidateList).replace("'",'"'))
</code>```

work as expected.

Body:
New to development and python and trying to create a json file.

I'm trying to generate a list of people with a start time and onboarding time and incident time:

import datetime
import random
import math
import json
import numpy as np

# generate list of candidates

cand = input("Enter number of candidates: ")
cand = int(cand)
startRange = 0.06 # standard deviation (scale)
startTime = 9.30 #mean (loc)
onboardRange = 0.5
onboardTime = 4.5
incidenceRatio = [0,0,0,0,1] #1 in 5 chance an incident arises

def calCan(): # creates a dictionary of candidates with start times, onboarding, incident times.
    candattr = []
    candidates = {"candidates":candattr}
    a = 1
    while a <= cand:
        b = np.random.normal(loc=startTime, scale=startRange, size=(1, 1)) # startime
        c = np.random.normal(loc=onboardTime, scale=onboardRange, size=(1, 1)) # onboarding time
        d = random.choice(incidenceRatio) * np.random.normal(loc=onboardTime, scale=onboardRange, size=(1, 1)) # incident time - random.choice(incidenceRatio) - takes a random selection from incidenceRation list defined above.
        btime = datetime.time(int(b//1),int(math.ceil(100 * (59 * (b % 1))/100)), 0)#converts bnum into time
        ctime = datetime.time(0,int(c//1),int(math.ceil(100 * (59 * (c % 1))/100)))
        dtime = datetime.time(0,int(d//1) ,int(math.ceil(100 * (59 * (d % 1))/100)))
        candattr.append({
        "name": "candidate {}".format(a),
        "startTime": "{}".format(btime),#json doesn't recognize time so have to store as a string
        "onboardTime": "{}".format(ctime),
        "incidentTime": "{}".format(dtime)
        })
        a = a + 1
    return candidates

And then I'm trying to put this into a Json.

I can get the JSON to print just fine using

candidateList = calCan()

print(json.dumps(candidateList, indent=4))

it returns something like this:

{
    "candidates": [
        {
            "name": "candidate 1",
            "startTime": "09:17:00",
            "onboardTime": "00:03:37",
            "incidentTime": "00:04:04"
        },
        {
            "name": "candidate 2",
            "startTime": "09:16:00",
            "onboardTime": "00:04:19",
            "incidentTime": "00:00:00"
        },
        {
            "name": "candidate 3",
            "startTime": "09:15:00",
            "onboardTime": "00:04:13",
            "incidentTime": "00:03:25"
        }
    ]
}

but when i try to manipulate it using json.loads with

candidateList = calCan()
candidateList = str(candidateList)
data = json.loads((candidateList)

I get all sorts of horrible errors that I can't make heads nor tail of:

Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.loads(candidateList)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

If I try and add double quotes to (candidateList):

data = json.loads("candidateList")

It still doesn't get me anywhere

Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.loads(("candidateList"))
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Following some advice below - i have stopped converting candidateList into a string and am using json.load instead.

candidateList = calCan()
data = json.load(candidateList)

this returns:

Traceback (most recent call last):
  File "queue.py", line 56, in <module>
    data = json.load(candidateList)
  File "C:\Users\Gordon Rose\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'

Body:
In a properly formatted JSON, strings need to be double-quoted but in a string literal for a dictionary, string keys and values are given as single-quoted strings. This is the key difference between json.dumps(candidateList) and str(candidateList) (where candidateList = calCan()).

The first is

'{"candidates": [{"name": "candidate 1", "startTime": "09:18:00", "onboardTime": "00:04:10", "incidentTime": "00:00:00"}, {"name": "candidate 2", "startTime": "09:18:00", "onboardTime": "00:04:23", "incidentTime": "00:00:00"}, {"name": "candidate 3", "startTime": "09:19:00", "onboardTime": "00:05:08", "incidentTime": "00:00:00"}, {"name": "candidate 4", "startTime": "09:14:00", "onboardTime": "00:05:17", "incidentTime": "00:00:00"}, {"name": "candidate 5", "startTime": "09:12:00", "onboardTime": "00:04:38", "incidentTime": "00:00:00"}]}'

and the second is

"{'candidates': [{'name': 'candidate 1', 'startTime': '09:18:00', 'onboardTime': '00:04:10', 'incidentTime': '00:00:00'}, {'name': 'candidate 2', 'startTime': '09:18:00', 'onboardTime': '00:04:23', 'incidentTime': '00:00:00'}, {'name': 'candidate 3', 'startTime': '09:19:00', 'onboardTime': '00:05:08', 'incidentTime': '00:00:00'}, {'name': 'candidate 4', 'startTime': '09:14:00', 'onboardTime': '00:05:17', 'incidentTime': '00:00:00'}, {'name': 'candidate 5', 'startTime': '09:12:00', 'onboardTime': '00:04:38', 'incidentTime': '00:00:00'}]}"

both

data = json.loads(json.dumps(candidateList))

as well as

data = json.dumps(str(candidateList).replace("'",'"'))

work as expected.


问:
Use String value instead of Constant String in flutter
This is the function I want to run on button press, it requires const String value in data field.

When I use packageNameImported instead of packageName it gives an error that String has to be constant.

Is there any way i can pass value from button to this function on press?

```<code>  deleteApp(String packageNameImported) {
    const packageName = 'package.name.app';
    final AndroidIntent intent = const AndroidIntent(
      action: 'action_delete',
      data: 'package:' + packageName,
    );
    intent.launch();
  }
</code>```

答:
Constant functions require constant values

Change

```<code>final AndroidIntent intent = const AndroidIntent(
</code>```

to

```<code>final AndroidIntent intent = AndroidIntent(
</code>```

Body:
This is the function I want to run on button press, it requires const String value in data field.

When I use packageNameImported instead of packageName it gives an error that String has to be constant.

Is there any way i can pass value from button to this function on press?

  deleteApp(String packageNameImported) {
    const packageName = 'package.name.app';
    final AndroidIntent intent = const AndroidIntent(
      action: 'action_delete',
      data: 'package:' + packageName,
    );
    intent.launch();
  }

Body:
Constant functions require constant values

Change

final AndroidIntent intent = const AndroidIntent(

to

final AndroidIntent intent = AndroidIntent(


问:
Read output from exec kotlin
I need to exec a jar file and redirect the output from my executed process to the output of my main process.

I using the following code :

```<code>val command = "java.exe -version"
val p = Runtime.getRuntime().exec(command)
val buf = p.getInputStream()
val inputAsString = buf.bufferedReader().use { it.readText() }
println(inputAsString)
</code>```

I have no output...

I have tested this code :

```<code>val command = "cmd /c chcp"
val p = Runtime.getRuntime().exec(command)
val sc = Scanner(p.inputStream)
println(sc.nextLine())
sc.close()
</code>```

I have an output but when I replace "cmd /c chcp" I have an error...

How can I read the output of "test.jar" which write "ok" for example ?

答:
```<code>    val p = Runtime.getRuntime().exec(command)
    p.waitFor()
    val stdOut = IOUtils.toString(p.inputStream, Charsets.UTF_8)
    val stdErr = IOUtils.toString(p.errorStream, Charsets.UTF_8)
</code>```

using org.apache.commons.io for IOUtils

Title: Read output from exec kotlin

Body:
I need to exec a jar file and redirect the output from my executed process to the output of my main process.

I using the following code :

val command = "java.exe -version"
val p = Runtime.getRuntime().exec(command)
val buf = p.getInputStream()
val inputAsString = buf.bufferedReader().use { it.readText() }
println(inputAsString)

I have no output...

I have tested this code :

val command = "cmd /c chcp"
val p = Runtime.getRuntime().exec(command)
val sc = Scanner(p.inputStream)
println(sc.nextLine())
sc.close()

I have an output but when I replace "cmd /c chcp" I have an error...

How can I read the output of "test.jar" which write "ok" for example ?

Body:
    val p = Runtime.getRuntime().exec(command)
    p.waitFor()
    val stdOut = IOUtils.toString(p.inputStream, Charsets.UTF_8)
    val stdErr = IOUtils.toString(p.errorStream, Charsets.UTF_8)

using org.apache.commons.io for IOUtils


问:
Django-Filter FilterSet Show Only User Generated Objects
I'm using a django-filter form and it's filtering all objects for 'associated_portfolios' how can I make it so it only shows the user the objects they created?

Error message:

```<code>'StatsFilter' object has no attribute 'fields'
</code>```

Filters.py

```<code>class StatsFilter(django_filters.FilterSet):
    associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios)

    class Meta:
        model = Trade
        fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']

    def __init__(self, request, *args, **kwargs):
        super(StatsFilter, self).__init__(*args, **kwargs)
        self.fields['associated_portfolios'].queryset = Trade.objects.filter(user=request.user)]
</code>```

views.py

```<code>class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_context_data(self, **kwargs):
        filter = StatsFilter(self.request.GET, queryset=self.get_queryset())
        context = super().get_context_data(**kwargs)
        context['filter'] = filter
        context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
        context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
        return context
</code>```

答:
Ah, now I remember: set the queryset argument of ModelMultipleChoiceFilter to a callable that accepts request as it's only argument:

def portfolio_filtered_queryset(request):
    return Trade.objects.filter(user=request.user)

class StatsFilter(django_filters.FilterSet):
    associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=porfolio_filtered_queryset)

The view:
class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_context_data(self, **kwargs):
        # Must pass in request!
        filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
        context = super().get_context_data(**kwargs)
        context['filter'] = filter
        context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
        context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
        return context
```

In django_filters.filters.QuerySetRequestMixin.get_request() the request instance is obtained from the parent. But I see no logic in django_filters.filterset.BaseFilterSet or concretes that tries to obtain the request through other means. So you must pass the request to the StatsFilter if you wish to make use of QuerySetRequestMixin.

Body:
I'm using a django-filter form and it's filtering all objects for 'associated_portfolios' how can I make it so it only shows the user the objects they created?

Error message:

'StatsFilter' object has no attribute 'fields'

Filters.py

class StatsFilter(django_filters.FilterSet):
    associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios)

    class Meta:
        model = Trade
        fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']

    def __init__(self, request, *args, **kwargs):
        super(StatsFilter, self).__init__(*args, **kwargs)
        self.fields['associated_portfolios'].queryset = Trade.objects.filter(user=request.user)]

views.py

class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_context_data(self, **kwargs):
        filter = StatsFilter(self.request.GET, queryset=self.get_queryset())
        context = super().get_context_data(**kwargs)
        context['filter'] = filter
        context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
        context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
        return context

Body:
Ah, now I remember: set the queryset argument of ModelMultipleChoiceFilter to a callable that accepts request as it's only argument:

def portfolio_filtered_queryset(request):
    return Trade.objects.filter(user=request.user)

class StatsFilter(django_filters.FilterSet):
    associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=porfolio_filtered_queryset)

The view:
class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_context_data(self, **kwargs):
        # Must pass in request!
        filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
        context = super().get_context_data(**kwargs)
        context['filter'] = filter
        context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
        context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
        return context

In django_filters.filters.QuerySetRequestMixin.get_request() the request instance is obtained from the parent. But I see no logic in django_filters.filterset.BaseFilterSet or concretes that tries to obtain the request through other means. So you must pass the request to the StatsFilter if you wish to make use of QuerySetRequestMixin.


问:
Ionic Geolocation always falls into error method
I'm continuously failing to achieve my desired results. All I want is to fetch the geolocation coordinates, if the device location is turned off, a prompt is show to enable the location without leaving the app, and device location gets turn on I've verified it manually.

But the problem is every time I try, I get fall into the error method

```<code>import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;

this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).
then(() => {

      Geolocation.getCurrentPosition({ enableHighAccuracy: true }).then(loc => {

        alert('Position detected successfully' + loc);

      }).catch(error => {

        alert(error);

      });

    }).catch(deny => {

      alert('You denied the location');

    });
</code>```

But there is something very strange, and that is just before launching the app, If I run google maps and locate my self, then my app works without any issue, otherwise it keep falling into error method.

答:
I don't think you need cordova-plugin-request-location-accuracy. Here is how you get the current location with Capacitor:

Page class (updated with error handling):

```<code>import { Component } from '@angular/core';

import { GeolocationPosition, Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  currentPos: GeolocationPosition;
  waitingForCurrentPosition = false;

  constructor() {
  }

  async getCurrentPos() {
    try {
      this.waitingForCurrentPosition = true;
      this.currentPos = await Geolocation.getCurrentPosition();
      console.log(this.currentPos);
    } catch (err) {
      console.error('Failed to get current position.', err);
    } finally {
      this.waitingForCurrentPosition = false;
    }
  }

}
</code>```

Page template:

```<code><ion-header>
  <ion-toolbar>
    <ion-title>
      Capacitor Geolocation
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-button (click)="getCurrentPos()" expand="block">
    <ion-spinner *ngIf="waitingForCurrentPosition"></ion-spinner>
    Get Current position
  </ion-button>

  <ul *ngIf="currentPos">
    <li>timestamp: {{ currentPos.timestamp }}</li>
    <li>coords:
      <ul>
        <li>latitude: {{ currentPos.coords.latitude }}</li>
        <li>longitude: {{ currentPos.coords.longitude }}</li>
        <li>accuracy: {{ currentPos.coords.accuracy }}</li>
        <li>altitudeAccuracy: {{ currentPos.coords.altitudeAccuracy }}</li>
        <li>altitude: {{ currentPos.coords.altitude }}</li>
        <li>speed: {{ currentPos.coords.speed }}</li>
        <li>heading: {{ currentPos.coords.heading }}</li>
      </ul>
    </li>
  </ul>
</ion-content>
</code>```

The app will request permissions when you try to get a position (click on button).

This works on 2 test devices :

OnePlus 6 (Android 10)

BlackView A60 (Android Go)

I have tested it before on an iPhone 6S so it should also work for iOS.

I created a basic demo in this repo.

Body:
I'm continuously failing to achieve my desired results. All I want is to fetch the geolocation coordinates, if the device location is turned off, a prompt is show to enable the location without leaving the app, and device location gets turn on I've verified it manually.

But the problem is every time I try, I get fall into the error method

import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;

this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).
then(() => {

      Geolocation.getCurrentPosition({ enableHighAccuracy: true }).then(loc => {

        alert('Position detected successfully' + loc);

      }).catch(error => {

        alert(error);

      });

    }).catch(deny => {

      alert('You denied the location');

    });

But there is something very strange, and that is just before launching the app, If I run google maps and locate my self, then my app works without any issue, otherwise it keep falling into error method.

Body:
I don't think you need cordova-plugin-request-location-accuracy. Here is how you get the current location with Capacitor:

Page class (updated with error handling):

import { Component } from '@angular/core';

import { GeolocationPosition, Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  currentPos: GeolocationPosition;
  waitingForCurrentPosition = false;

  constructor() {
  }

  async getCurrentPos() {
    try {
      this.waitingForCurrentPosition = true;
      this.currentPos = await Geolocation.getCurrentPosition();
      console.log(this.currentPos);
    } catch (err) {
      console.error('Failed to get current position.', err);
    } finally {
      this.waitingForCurrentPosition = false;
    }
  }

}

Page template:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Capacitor Geolocation
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-button (click)="getCurrentPos()" expand="block">
    <ion-spinner *ngIf="waitingForCurrentPosition"></ion-spinner>
    Get Current position
  </ion-button>

  <ul *ngIf="currentPos">
    <li>timestamp: {{ currentPos.timestamp }}</li>
    <li>coords:
      <ul>
        <li>latitude: {{ currentPos.coords.latitude }}</li>
        <li>longitude: {{ currentPos.coords.longitude }}</li>
        <li>accuracy: {{ currentPos.coords.accuracy }}</li>
        <li>altitudeAccuracy: {{ currentPos.coords.altitudeAccuracy }}</li>
        <li>altitude: {{ currentPos.coords.altitude }}</li>
        <li>speed: {{ currentPos.coords.speed }}</li>
        <li>heading: {{ currentPos.coords.heading }}</li>
      </ul>
    </li>
  </ul>
</ion-content>

The app will request permissions when you try to get a position (click on button).

This works on 2 test devices :

OnePlus 6 (Android 10)

BlackView A60 (Android Go)

I have tested it before on an iPhone 6S so it should also work for iOS.

I created a basic demo in this repo.


问:
How to get char[] to work with std::map
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

```<code>#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}
</code>```

```<code>/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
</code>```

It seems it has something to do with comparison, but I am still in the dark.

答:
You need to implement the < operator

```<code>class id {
public:
    char v [30];
    bool operator<(const id &rhs) const{
        return strcmp(v,rhs.v) < 0;
    }
};
</code>```

EDIT: As a side note your code is a very poor way of doing things.  See some of the answers for an explanation why.

Title: How to get char[] to work with std::map

Body:
EDIT after answered:

< should be provided for std::map. For more information about best practice, go for James McNellis's answer.

The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but it turned out to be not fast enough.

Thank you.

I know I cannot use char[] directly with map, such as map<char[], int>. Thus I put it in a class. But it still can go through compilation. How to deal with that?

#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}

/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’

It seems it has something to do with comparison, but I am still in the dark.

Body:
You need to implement the < operator

class id {
public:
    char v [30];
    bool operator<(const id &rhs) const{
        return strcmp(v,rhs.v) < 0;
    }
};

EDIT: As a side note your code is a very poor way of doing things.  See some of the answers for an explanation why.


问:
White blank screen issue with cordova ios with cordova-plugin-ionic-webview or cordova-plugin-wkwebview-engine plugins
There will an issue with UIWebview in ios. Apple is going to reject app using this. So we decided to use WKWebview for our cordova ios app. I installed cordova-plugin-wkwebview-engine and added <preference name="WKWebViewOnly" value="true" /> in config.xml file.
The issue is after the splash screen Its showing white blank screen.

```<code>    <?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloCordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <plugin name="cordova-plugin-ionic-webview" spec="^4.1.3" />
    <preference name="WKWebViewOnly" value="true" />
    <engine name="ios" spec="~5.1.1" />
    <plugin name="cordova-plugin-background-mode" spec="^0.7.3" />
    <plugin name="cordova-plugin-badge" spec="^0.8.8" />
    <plugin name="cordova-plugin-camera" spec="^4.1.0" />
    <plugin name="cordova-plugin-device" spec="^2.0.3" />
    <plugin name="cordova-plugin-geolocation" spec="^4.0.2" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.3" />
    <plugin name="cordova-plugin-x-toast" spec="^2.7.2" />
</widget>

</code>```

答:
remember to add this plugins:

```<code><plugin name="cordova-plugin-wkwebview-engine"  source="npm" />
<plugin name="cordova-plugin-wkwebview-file-xhr"  source="npm" />
</code>```

and add this

```<code><preference name="WKWebViewOnly" value="true" />
<feature name="CDVWKWebViewEngine">
    <param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<preference name="AllowBackForwardNavigationGestures" value="true" />
<preference name="Allow3DTouchLinkPreview" value="false" />
</code>```

compile with cordova-ios@5.1.1

To build it with cordova-ios@6.1.0+

remove splash plugin (now is integrated)

upgrade the inappbrowser plugin to v4.0.0

remove all wkwebview related plugins

add scheme and host to config.xml:

```<code>    <preference name="scheme" value="app" />
    <preference name="hostname" value="localhost"  />
</code>```

Body:
There will an issue with UIWebview in ios. Apple is going to reject app using this. So we decided to use WKWebview for our cordova ios app. I installed cordova-plugin-wkwebview-engine and added <preference name="WKWebViewOnly" value="true" /> in config.xml file.
The issue is after the splash screen Its showing white blank screen.

    <?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloCordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <plugin name="cordova-plugin-ionic-webview" spec="^4.1.3" />
    <preference name="WKWebViewOnly" value="true" />
    <engine name="ios" spec="~5.1.1" />
    <plugin name="cordova-plugin-background-mode" spec="^0.7.3" />
    <plugin name="cordova-plugin-badge" spec="^0.8.8" />
    <plugin name="cordova-plugin-camera" spec="^4.1.0" />
    <plugin name="cordova-plugin-device" spec="^2.0.3" />
    <plugin name="cordova-plugin-geolocation" spec="^4.0.2" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.3" />
    <plugin name="cordova-plugin-x-toast" spec="^2.7.2" />
</widget>

Body:
remember to add this plugins:

<plugin name="cordova-plugin-wkwebview-engine"  source="npm" />
<plugin name="cordova-plugin-wkwebview-file-xhr"  source="npm" />

and add this

<preference name="WKWebViewOnly" value="true" />
<feature name="CDVWKWebViewEngine">
    <param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<preference name="AllowBackForwardNavigationGestures" value="true" />
<preference name="Allow3DTouchLinkPreview" value="false" />

compile with cordova-ios@5.1.1

To build it with cordova-ios@6.1.0+

remove splash plugin (now is integrated)

upgrade the inappbrowser plugin to v4.0.0

remove all wkwebview related plugins

add scheme and host to config.xml:

    <preference name="scheme" value="app" />
    <preference name="hostname" value="localhost"  />


问:
Downloading excel file from url in pandas (post authentication)
I am facing a strange problem, I dont know much about for my lack of knowledge of html.

 I want to download an excel file post login from a website.
The file_url is:

```<code>file_url="https://xyz.xyz.com/portal/workspace/IN AWP ABRL/Reports & Analysis Library/CDI Reports/CDI_SM_Mar'20.xlsx"
</code>```

There is a share button for the file which gives the link2 (For the same file):

```<code>file_url2='http://xyz.xyz.com/portal/traffic/4a8367bfd0fae3046d45cd83085072a0'
</code>```

When I use requests.get to read link 2 (post login to a session) I am able to read the excel into pandas. However, link 2 does not serve my purpose as I cant schedule my report on this on a periodic basis (by changing Mar'20 to Apr'20 etc). Link1 suits my purpose but gives the following on passing r=requests.get in the r.content method:

```<code>b'\n\n\n\n\n\n\n\n\n\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t\n\t<body bgcolor="#FFFFFF">\n\t\n\n\t<script language="javascript">\n\t\t<!-- \n\t\t\ttop.location.href="https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar\'20.xlsx";\t\n\t\t-->\n\t</script>\n\t</body>\n</html>'
</code>```

I have tried all encoding decoding of url but cant understand this alphanumeric url (link2).

My python code (working) is:

```<code>import requests
url = 'http://xyz.xyz.com/portal/site'
username=''
password=''
s = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
r = s.get(url,auth=(username, password),verify=False,headers=headers)
r2 = s.get(file_url,verify=False,allow_redirects=True)
r2.content
# df=pd.read_excel(BytesIO(r2.content))
</code>```

答:
You get HTML with JavaScript which redirects browser to new url. But requests can't run JavaScript. it is simple methods to block some simple scripts/bots.

But HTML is only string so you can use string's functions to get url from string and use this url with requests to get file.

```<code>content = b'\n\n\n\n\n\n\n\n\n\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t\n\t<body bgcolor="#FFFFFF">\n\t\n\n\t<script language="javascript">\n\t\t<!-- \n\t\t\ttop.location.href="https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar\'20.xlsx";\t\n\t\t-->\n\t</script>\n\t</body>\n</html>'

text = content.decode()
print(text)
print('\n---\n')

start = text.find('href="') + len('href="')
end   = text.find('";', start)

url = text[start:end]
print('url:', url)

response = s.get(url)
</code>```

Results:

```<code><html>
    <head>
        <title></title>
    </head>

    <body bgcolor="#FFFFFF">

    <script language="javascript">
        <!--
            top.location.href="https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar'20.xlsx";
        -->
    </script>
    </body>
</html>

---

url: https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar'20.xlsx
</code>```

Body:
I am facing a strange problem, I dont know much about for my lack of knowledge of html.

 I want to download an excel file post login from a website.
The file_url is:

file_url="https://xyz.xyz.com/portal/workspace/IN AWP ABRL/Reports & Analysis Library/CDI Reports/CDI_SM_Mar'20.xlsx"

There is a share button for the file which gives the link2 (For the same file):

file_url2='http://xyz.xyz.com/portal/traffic/4a8367bfd0fae3046d45cd83085072a0'

When I use requests.get to read link 2 (post login to a session) I am able to read the excel into pandas. However, link 2 does not serve my purpose as I cant schedule my report on this on a periodic basis (by changing Mar'20 to Apr'20 etc). Link1 suits my purpose but gives the following on passing r=requests.get in the r.content method:

b'\n\n\n\n\n\n\n\n\n\n\n\t\n\t\t<title></title>\n\t\n\t\n\t\n\t\n\n\t\n\t\n'

I have tried all encoding decoding of url but cant understand this alphanumeric url (link2).

My python code (working) is:

import requests
url = 'http://xyz.xyz.com/portal/site'
username=''
password=''
s = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
r = s.get(url,auth=(username, password),verify=False,headers=headers)
r2 = s.get(file_url,verify=False,allow_redirects=True)
r2.content
# df=pd.read_excel(BytesIO(r2.content))

Body:
You get HTML with JavaScript which redirects browser to new url. But requests can't run JavaScript. it is simple methods to block some simple scripts/bots.

But HTML is only string so you can use string's functions to get url from string and use this url with requests to get file.

content = b'\n\n\n\n\n\n\n\n\n\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t\n\t<body bgcolor="#FFFFFF">\n\t\n\n\t<script language="javascript">\n\t\t<!-- \n\t\t\ttop.location.href="https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar\'20.xlsx";\t\n\t\t-->\n\t</script>\n\t</body>\n</html>'

text = content.decode()
print(text)
print('\n---\n')

start = text.find('href="') + len('href="')
end   = text.find('";', start)

url = text[start:end]
print('url:', url)

response = s.get(url)

Results:

<html>
    <head>
        <title></title>
    </head>

    <body bgcolor="#FFFFFF">

    <script language="javascript">
        <!--
            top.location.href="https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar'20.xlsx";
        -->
    </script>
    </body>
</html>

---

url: https://xyz.xyz.com/portal/workspace/IN%20AWP%20ABRL/Reports%20&%20Analysis%20Library/CDI%20Reports/CDI_SM_Mar'20.xlsx


问:
How to feed trained Python TensorFlow model with batches?
I have created an own model and I trained it with ImageTrainGenerator- from Keras using flow_from_directory.

Like this: how to train model with batches. Everything works fine, I checked the generated batches, and the pictures are as it has to be.

My problem is, that I want to use this trained model in online face detection. I crop the faces on desired width and height, I convert it into array, but the prediction is horrible.

I think that the live streamed image has to be the same as what the Imagetraingenerator creates (batches). Any idea how can I convert cv2.imread(path) image into batch to predict the class?

答: You just have to add the batch dimensions to convert it to a batch with 1 sample: np.expand_dims(img, axis=0).