问:
Couldn't require openssl in ruby
I have openssl installed in my virtual machine ubuntu12.04lts.

When I run the gem command it gives error.

Error: while executing gem (Gem::Exception)

        Unable to require openssl. install openSSL and rebuilt ruby (preferred) or use non HTTPs sources

And I also test require openssl in irb mode.
it gives error.

Loaderror: cannot load such file --openssl

      from /usr/local/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55 `require'

I have openssl

```<code>$openssl version
OpenSSL 1.0.1 14 mar 2012
</code>```

How to fix the error?

答:
i had similar issue and tried to solve it by following guides. The "rebuild ruby" is an important step!

after openssl_devel is installed

```<code>cd folder_of_ruby_source_code/ext/openssl
ruby ./extconf.rb
make
make install

cd folder_of_ruby_source_code
./configure
make clean       <= clean is important here
make
make install
</code>```

Title: Couldn't require openssl in ruby

Body:
I have openssl installed in my virtual machine ubuntu12.04lts.

When I run the gem command it gives error.

Error: while executing gem (Gem::Exception)

        Unable to require openssl. install openSSL and rebuilt ruby (preferred) or use non HTTPs sources

And I also test require openssl in irb mode.
it gives error.

Loaderror: cannot load such file --openssl

      from /usr/local/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55 `require'

I have openssl

$openssl version
OpenSSL 1.0.1 14 mar 2012

How to fix the error?

Body:
i had similar issue and tried to solve it by following guides. The "rebuild ruby" is an important step!

after openssl_devel is installed

cd folder_of_ruby_source_code/ext/openssl
ruby ./extconf.rb
make
make install

cd folder_of_ruby_source_code
./configure
make clean       <= clean is important here
make
make install


来源: stackexchange

问:
pure javascript, filter box doesn't filter properly
I have an array of devices, each device has own unique id, I wish to make searchBox which will filter by this id. So far I managed it partly, so it checks if character from input match character from device-id. However not in way I would want that, example below:

id =35678; input.value = 5

it shouldn't work as first character is 3

id = 35679; input.value= 35

it should work as first character is same

Problem is in match/include function, but no really idea how to replace it to make it work

```<code>input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"
        }
     })
 })
</code>```

答:
You can use startsWith instead of match

let arr = ['35678', '451234', '45454', '56565']

let find = (value) =>{
  return arr.filter(id=> id.startsWith(value))
}

console.log(find(5))
console.log(find(35))
console.log(find(46))```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of devices, each device has own unique id, I wish to make searchBox which will filter by this id. So far I managed it partly, so it checks if character from input match character from device-id. However not in way I would want that, example below:

id =35678; input.value = 5

it shouldn't work as first character is 3

id = 35679; input.value= 35

it should work as first character is same

Problem is in match/include function, but no really idea how to replace it to make it work

input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"
        }
     })
 })


问:
Fatal error: Call to undefined function imagefilter()
What is causing this error?

```
Fatal error: Call to undefined function imagefilter() in /var/www/polaroid.php on line 5
```

```<code>  1 <?PHP
  2   $img_addr = $_GET['image_address'];
  3   $img = imagecreatefromjpeg($img_addr);
  4
      /* everything works as expected without this line */
  5   imagefilter($img, IMG_FILTER_GRAYSCALE);
  6
  7   if ($img)
  8   {
        /* I moved the header function here so I can see errors in the browser.
           If I leave it at the top of the file, the browser expects an image
           and doesn't print the error messages. */
  9     header('Content-type: image/jpeg');
 10     imagejpeg($img);
 11   }
 12 ?>
 13
</code>```

This is the URL I use:

```
http://localhost/polaroid.php?image_address=http://mattnelsoninfo.files.wordpress.com/2008/04/ceiling_cat1.jpg
```

NOTE: gd is listed in the output from phpinfo().

EDIT: I'm using PHP Version 5.2.6-2ubuntu4.1

Another EDIT:

phpinfo() yields this in the gd section

```<code>gd
GD Support  enabled
GD Version  2.0 or higher
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.3.7
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled
</code>```

Thanks!

答:
What version of PHP are you using?  It looks like imagefilter is a PHP5 function ... http://us3.php.net/manual/en/function.imagefilter.php

EDIT:
Your code works on my version of PHP.  For reference, here's my phpinfo:

```<code>gd
GD Support  enabled
**GD Version    bundled (2.0.34 compatible)**
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.1.9
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled
XBM Support     enabled
</code>```

You might want to make sure that the GD Version is bundled.  I've seen installations that say GD Support is enabled but not bundled.  Not sure if that makes a difference though.

OwnerDisplayName: ThomasGHenry

ContentLicense: CC BY-SA 2.5

Body:
What is causing this error?

Fatal error: Call to undefined function imagefilter() in /var/www/polaroid.php on line 5

  1 <?PHP
  2   $img_addr = $_GET['image_address'];
  3   $img = imagecreatefromjpeg($img_addr);
  4
      /* everything works as expected without this line */
  5   imagefilter($img, IMG_FILTER_GRAYSCALE);
  6
  7   if ($img)
  8   {
        /* I moved the header function here so I can see errors in the browser.
           If I leave it at the top of the file, the browser expects an image
           and doesn't print the error messages. */
  9     header('Content-type: image/jpeg');
 10     imagejpeg($img);
 11   }
 12 ?>
 13

This is the URL I use:

http://localhost/polaroid.php?image_address=http://mattnelsoninfo.files.wordpress.com/2008/04/ceiling_cat1.jpg

NOTE: gd is listed in the output from phpinfo().

EDIT: I'm using PHP Version 5.2.6-2ubuntu4.1

Another EDIT:

phpinfo() yields this in the gd section

gd
GD Support  enabled
GD Version  2.0 or higher
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.3.7
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled

Thanks!

LastEditorDisplayName: ThomasGHenry

Body:
What version of PHP are you using?  It looks like imagefilter is a PHP5 function ... http://us3.php.net/manual/en/function.imagefilter.php

EDIT:
Your code works on my version of PHP.  For reference, here's my phpinfo:

gd
GD Support  enabled
**GD Version    bundled (2.0.34 compatible)**
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.1.9
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPG Support     enabled
PNG Support     enabled
WBMP Support    enabled
XBM Support     enabled

You might want to make sure that the GD Version is bundled.  I've seen installations that say GD Support is enabled but not bundled.  Not sure if that makes a difference though.

OwnerDisplayName: bryan

LastEditorDisplayName: bryan


问:
Is there a way to make a trait that contain an vector of itself?
I'm quite new to rust and I have the following problems: I want to have trait that I call Artifact and the definition of an Artifact is that it can contains multiples Artifact.

My first idea was to make an Artifact trait that contains a vector of the Artifact trait:

trait Artifact
{
    type artifacts = Vec<Box<dyn Artifact>>;
}
```

<p>I got the following error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0191]: the value of the associated type `artifacts` (from the trait `Artifact::Artifact`) must be specified
 --> src/Artifact.rs:4:30
  |
4 |     type artifacts = Vec<Box<dyn Artifact>>;
  |     -------------------------^^^^^^^^^^^^---
  |     |                        |
  |     |                        associated type `artifacts` must be specified
  |     `artifacts` defined here
</code>```

Is there a way in rust to make this kind of design?

答:
If you define type definition in the trait as dyn trait, then it is an associated type and you need to specify that type on the implementation of that trait.

Is there a way in rust to make this kind of design?

In the current stable release channel default associated types are not supported. But you can achieve what you need with nightly release channel like following:

```<code>#![feature(associated_type_defaults)]
trait Artifact {
    type artifacts = Vec<Box<dyn Artifact<artifacts = Self>>>;
}
</code>```

Playground

In stable release channel you can implement the closest idea like following:

```<code>trait Artifact {
    fn artifact_call(&self);
}

struct Artifact1 {
    inners: Vec<Box<dyn Artifact>>,
}

struct Artifact2;
struct Artifact3;

impl Artifact for Artifact1 {
    fn artifact_call(&self) {
        self.inners
            .iter()
            .for_each(|artifact| artifact.artifact_call());
    }
}

impl Artifact for Artifact2 {
    fn artifact_call(&self) {
        println!("Artifact 2 Call");
    }
}

impl Artifact for Artifact3 {
    fn artifact_call(&self) {
        println!("Artifact 3 Call");
    }
}

fn main() {
    let container_artifact = Artifact1 {
        inners: vec![Box::new(Artifact2), Box::new(Artifact3)],
    };
    container_artifact.artifact_call();
}
</code>```

Playground

Body:
I'm quite new to rust and I have the following problems: I want to have trait that I call Artifact and the definition of an Artifact is that it can contains multiples Artifact.

My first idea was to make an Artifact trait that contains a vector of the Artifact trait:

trait Artifact
{
    type artifacts = Vec<Box<dyn Artifact>>;
}

I got the following error:

error[E0191]: the value of the associated type `artifacts` (from the trait `Artifact::Artifact`) must be specified
 --> src/Artifact.rs:4:30
  |
4 |     type artifacts = Vec<Box<dyn Artifact>>;
  |     -------------------------^^^^^^^^^^^^---
  |     |                        |
  |     |                        associated type `artifacts` must be specified
  |     `artifacts` defined here

Is there a way in rust to make this kind of design?

Body:
If you define type definition in the trait as dyn trait, then it is an associated type and you need to specify that type on the implementation of that trait.

Is there a way in rust to make this kind of design?

In the current stable release channel default associated types are not supported. But you can achieve what you need with nightly release channel like following:

#![feature(associated_type_defaults)]
trait Artifact {
    type artifacts = Vec<Box<dyn Artifact<artifacts = Self>>>;
}

Playground

In stable release channel you can implement the closest idea like following:

trait Artifact {
    fn artifact_call(&self);
}

struct Artifact1 {
    inners: Vec<Box<dyn Artifact>>,
}

struct Artifact2;
struct Artifact3;

impl Artifact for Artifact1 {
    fn artifact_call(&self) {
        self.inners
            .iter()
            .for_each(|artifact| artifact.artifact_call());
    }
}

impl Artifact for Artifact2 {
    fn artifact_call(&self) {
        println!("Artifact 2 Call");
    }
}

impl Artifact for Artifact3 {
    fn artifact_call(&self) {
        println!("Artifact 3 Call");
    }
}

fn main() {
    let container_artifact = Artifact1 {
        inners: vec![Box::new(Artifact2), Box::new(Artifact3)],
    };
    container_artifact.artifact_call();
}

Playground


问:
Set up kubernetes cluster with multiple pods automatically
Sorry if the question is a bit abstract but I am currently getting into GCP.

First of all my goal - I want to set up automatic creation of kubernetes cluster with a number of pods.

What I have so far - I have past few days looking in the GCP and Kubernetes documentation as well as some examples. I have two working bits:

I have created a cluster config with yaml and jinja files and I
can use deployment manager to set them up.

```<code>gcloud deployment-manager deployments create my-config --config my-config.yaml
</code>```

I have created another configuration yaml file which uses a docker image stored in the GCP Container Registry to start some pods on the cluster above (which again works fine)

kubectl apply -f image-config.yaml --record

My question is is it possible to combine somehow the above into a single config file and start everything up with a single command?
Or if you can point me in the direction of some appropriate example.

答:
The Agones project accomplishes this task using a combination of Terraform and Helm as described in the Install with Terraform documentation. There is a single command which builds a GKE cluster and also installs an application into the cluster (e.g. runs some pods). </p>

<p>If you don't want to use Helm and build a full installer for your pods, you can also look at using the Kubernetes Provider to run some simple applications once the cluster has been deployed (check out the google_container_cluster configuration in the GCP provider). </p>

Body:
Sorry if the question is a bit abstract but I am currently getting into GCP.

First of all my goal - I want to set up automatic creation of kubernetes cluster with a number of pods.

What I have so far - I have past few days looking in the GCP and Kubernetes documentation as well as some examples. I have two working bits:

I have created a cluster config with yaml and jinja files and I
can use deployment manager to set them up.

gcloud deployment-manager deployments create my-config --config my-config.yaml

I have created another configuration yaml file which uses a docker image stored in the GCP Container Registry to start some pods on the cluster above (which again works fine)

kubectl apply -f image-config.yaml --record

My question is is it possible to combine somehow the above into a single config file and start everything up with a single command?
Or if you can point me in the direction of some appropriate example.

Body:
The Agones project accomplishes this task using a combination of Terraform and Helm as described in the Install with Terraform documentation. There is a single command which builds a GKE cluster and also installs an application into the cluster (e.g. runs some pods).

If you don't want to use Helm and build a full installer for your pods, you can also look at using the Kubernetes Provider to run some simple applications once the cluster has been deployed (check out the google_container_cluster configuration in the GCP provider).


问:
How can I import functions from an other javascript file?
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

```<code>export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}
</code>```

--- main.js ---

```<code>import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();
</code>```

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.

答: in es6 you can use import { getAllPlanetDataFromAPI } from './dataManager' otherwise you should import ./dataManage </p>

Body:
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}

--- main.js ---

import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.


问:
It is ok to have long running processes in NServiceBus with SQL Server transport?
I have long running process running in the message handler, I noticed that I can't read from the table while the task is in process.

Is this ok?

Or is there a better way to handle long running processes?

My transport is SQL Server.

Thanks in advance :)

```<code>public class HandlerAwaitsTheTask : IHandleMessages<CommandMessage>
{
    public async Task Handle(CommandMessage message, IMessageHandlerContext context)
    {
        await SomeLibrary.VeryVeryVeryLongTask(message);
    }
}
</code>```

答:
It depends. :-)

How long is "VeryVeryVeryLong"? 2 minutes? 2 hours? 2 days?
Which table is being locked? Locking an entire table feels like something is off. It hardly can be the queue, because it should only lock one or a few rows for pulling messages. So it is likely your own table.

Besides that, the lock is probably a serializable lock. Which is likely caused by a distributed transaction. So maybe you're using different connection strings at the least, or different databases for business and NServiceBus data.

It's not like you absolutely cannot have very long tasks and long locks, but depending on how long it is, SQL Server or other things might start complaining. Throughput can also be limited. We probably need more context to see what is happening and what you need.

You can also contact support@particular.net for more information and support.

Body:
I have long running process running in the message handler, I noticed that I can't read from the table while the task is in process.

Is this ok?

Or is there a better way to handle long running processes?

My transport is SQL Server.

Thanks in advance :)

public class HandlerAwaitsTheTask : IHandleMessages<CommandMessage>
{
    public async Task Handle(CommandMessage message, IMessageHandlerContext context)
    {
        await SomeLibrary.VeryVeryVeryLongTask(message);
    }
}


问:
How to capture browser tab close event?
I have a link in my application on click of which new tab will get open. I want to capture the event when newly opened tab will be closed to show some indication in my application.
I am using Ext JS 3.4 version. I have tried focus, blur and unload events but dint able to capture. Any hints will be really helpful.

Note: I want to capture event on my application not on the new tab.

答:
You Can try this out..</p>

```<code>var new_window = null;
function openWindow(url) {
   new_window = window.open(url);

  new_window.onbeforeunload = function(){
    new_window.opener.postMessage('closed','*');
  }
  window.onmessage = function(event){
    alert(event.data);
  }

}
openWindow(url);
</code>```

Title: How to capture browser tab close event?

Body:
You Can try this out..

var new_window = null;
function openWindow(url) {
   new_window = window.open(url);

  new_window.onbeforeunload = function(){
    new_window.opener.postMessage('closed','*');
  }
  window.onmessage = function(event){
    alert(event.data);
  }

}
openWindow(url);


问:
Where to store html code for jQuery?
In some scripts long html blocks are added to selector. For example

```<code>$("#test").prepend($('<div id="tester">..long html tags..</div>').hide().fadeIn(2000));
</code>```

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.

答:
If that long html is not dynamic, then you can put them(div) into your main html itself and make it as hidden.

```<code>   <div id="testerouter" style="display:none>
     <div id="tester">..long html tags..</div>
   </div>
</code>```

then you can able to retrieve them using

```<code> $("#testerouter").html();
</code>```

and prepend with your id(test)

ContentLicense: CC BY-SA 3.0

Title: Where to store html code for jQuery?

Body:
In some scripts long html blocks are added to selector. For example

$("#test").prepend($('
..long html tags..
').hide().fadeIn(2000));

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.

Body:
If that long html is not dynamic, then you can put them(div) into your main html itself and make it as hidden.

   <div id="testerouter" style="display:none>
     <div id="tester">..long html tags..</div>
   </div>

then you can able to retrieve them using

 $("#testerouter").html();

and prepend with your id(test)


问:
What does this style of writing mean?

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function(start: number) {
        return start.toString();
    };
    counter.interval = 123;
    counter.reset = function() {
        this.interval = 0;
    };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

```

<p>I want to know:</p>

<ol>
<li><p><code>(start: number): string;</code> a anonymous function here? </p></li>
<li><p>the meaning of <code><Counter></code> in</p>

```let counter = <Counter>function(start: number) {
  return start.toString();
};
```

I don't understand what c is in let c = getCounter();

It's not a object , not a class , and its type is Counter which means a interface (but why assigned to a function?) So is c an instance of Counter? And the interface is equal to function?

答:
1st answer:
 its the call signature (something like the constructor) and it means this interface is a function and when ever you implement it, it should have a function that get a number and returns a string and when you want to create an instance of your implementation you should call it.

2nd answer:
 that function is defining the interface constructor and return the instance of your interface implementation.

3rd answer :
 related to second answer the instance that created should be put in the variable.

I hope I explained it clearly

Title: What does this style of writing mean?

Body:
interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function(start: number) {
        return start.toString();
    };
    counter.interval = 123;
    counter.reset = function() {
        this.interval = 0;
    };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

I want to know:

(start: number): string; a anonymous function here?

the meaning of <Counter> in

let counter = <Counter>function(start: number) {
  return start.toString();
};

I don't understand what c is in let c = getCounter();

It's not a object , not a class , and its type is Counter which means a interface (but why assigned to a function?) So is c an instance of Counter? And the interface is equal to function?


问:
The requested resource(/solr/update) is not available
I have deployed solr 3.6.1 in Centos.Now I can search document,But I fail to delete document in solr.

The relevant part of solrconfig.xml like this:

```<code>  <requestHandler name="/update" class="solr.UpdateRequestHandler">
  </requestHandler>
  <requestHandler name="/update/csv" class="solr.CSVRequestHandler" >
     <lst name="defaults">
      <str name="seperator">,</str>
      <str name="header">true</str>
      <str name="encapsulator">"</str>
     </lst>
  </requestHandler>
</code>```

When I enter this url

```<code>http://localhost:8080/solr/update/?stream.body=<delete><id>123</id></delete>&stream.contentType=text/xml;charset=utf-8&commit=true
</code>```

in my browser,the result is:

```<code>type Status report

message: /solr/update

description: The requested resource is not available
</code>```

However, the update/csv handler works fine.

I'm wondering is there something wrong with the configuration in solrconfig.xml?

Any advice is appreciated!

答:
Maybe you can try update as json;

```<code>curl 'http://<your_url>/solr/<yourcorename>/update?commit=true' -H 'Content-type:application/json' -d '[{"id":"123","field_1":{"set":899.99}, "field_2":{"set":123}}]'
</code>```

id is a must field for update..

Body:
I have deployed solr 3.6.1 in Centos.Now I can search document,But I fail to delete document in solr.

The relevant part of solrconfig.xml like this:

  <requestHandler name="/update" class="solr.UpdateRequestHandler">
  </requestHandler>
  <requestHandler name="/update/csv" class="solr.CSVRequestHandler" >
     <lst name="defaults">
      <str name="seperator">,</str>
      <str name="header">true</str>
      <str name="encapsulator">"</str>
     </lst>
  </requestHandler>

When I enter this url

http://localhost:8080/solr/update/?stream.body=<delete><id>123</id></delete>&stream.contentType=text/xml;charset=utf-8&commit=true

in my browser,the result is:

type Status report

message: /solr/update

description: The requested resource is not available

However, the update/csv handler works fine.

I'm wondering is there something wrong with the configuration in solrconfig.xml?

Any advice is appreciated!

Body:
Maybe you can try update as json;

curl 'http://<your_url>/solr/<yourcorename>/update?commit=true' -H 'Content-type:application/json' -d '[{"id":"123","field_1":{"set":899.99}, "field_2":{"set":123}}]'

id is a must field for update..


问:
Group multidimensional array by key and sum values in PHP
There are similar questions on Stack Overflow but nothing quite like mine, and I also want to double check that I am doing this the most efficient way (resource wise).

I have surveys that are submitted and I want to tally the results. Each survey is saved in a multidimensional array like so:

Array ( [name] => Clark Kent [rating] => 5 )

These are coming from a loop as they are separate database entries.

So I am beginning by creating a new array with all these combined:

```<code>$mods = array();
$index = -1;
foreach($fields as $field) {
  $index++;
  $mods[$index]['name'] = $field['name'];
  $mods[$index]['rating'] = $field['rating'];
}
</code>```

Then I am grouping these so that all the ratings for the same name are together, so I can sum them later.

```<code>$groups = array();
foreach ($mods as $value) {
  $groups[$value['name']][] = $value;
}
</code>```

This produces the following:

```<code>Array (
  [Clark Kent] => Array (
    [0] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    [1] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    )
[Peter Parker] => Array (
    [0] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    [1] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    )
[Bruce Wayne] => Array (
    [0] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    )
[Bruce Banner] => Array (
    [0] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    )
)
</code>```

What I am trying to accomplish would be something like this:

```<code><table>
  <tr>
    <td>Clark Kent</td>
    <td>{average of all ratings}</td>
  </tr>
</table>
</code>```

I'm most of the way there, but I am stuck! I'm not sure how to get the grouped name that doesn't have any type of index or key so I can use that value for my table. Then I need to sum each grouped values.

答:
I would do all the necessary math in the loop that reads the data from the database. Something like this:

```<code>$ratings = array();
while ($row = $result->fetch_assoc()) {
    $name = $row['name'];
    if (!isset($ratings[$name])) {
        $ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
    }
    else {
        $ratings[$name]['count']++;
        $ratings[$name]['sum'] += $row['rating'];
    }
}
</code>```

Then you can just output your table like so:

```<code>echo "<table>";
foreach ($ratings as $name => $r) {
    echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";
</code>```

Body:
There are similar questions on Stack Overflow but nothing quite like mine, and I also want to double check that I am doing this the most efficient way (resource wise).

I have surveys that are submitted and I want to tally the results. Each survey is saved in a multidimensional array like so:

Array ( [name] => Clark Kent [rating] => 5 )

These are coming from a loop as they are separate database entries.

So I am beginning by creating a new array with all these combined:

$mods = array();
$index = -1;
foreach($fields as $field) {
  $index++;
  $mods[$index]['name'] = $field['name'];
  $mods[$index]['rating'] = $field['rating'];
}

Then I am grouping these so that all the ratings for the same name are together, so I can sum them later.

$groups = array();
foreach ($mods as $value) {
  $groups[$value['name']][] = $value;
}

This produces the following:

Array (
  [Clark Kent] => Array (
    [0] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    [1] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    )
[Peter Parker] => Array (
    [0] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    [1] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    )
[Bruce Wayne] => Array (
    [0] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    )
[Bruce Banner] => Array (
    [0] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    )
)

What I am trying to accomplish would be something like this:

    Clark Kent
    {average of all ratings}

I'm most of the way there, but I am stuck! I'm not sure how to get the grouped name that doesn't have any type of index or key so I can use that value for my table. Then I need to sum each grouped values.

Body:
I would do all the necessary math in the loop that reads the data from the database. Something like this:

$ratings = array();
while ($row = $result->fetch_assoc()) {
    $name = $row['name'];
    if (!isset($ratings[$name])) {
        $ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
    }
    else {
        $ratings[$name]['count']++;
        $ratings[$name]['sum'] += $row['rating'];
    }
}

Then you can just output your table like so:

echo "<table>";
foreach ($ratings as $name => $r) {
    echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";


问:
How to update summary state of data changes without subscribing to every input/component change in angular?
I have a rather complex modal to manage some data state. It has a lot of inputs, selections, checkboxes and other custom components.

Now I would like to show the user some summary hints about what data has been updated during the time modal has been opened and what consequences it would lead.
For example, on some actions, I would like to change the color of the "Update" button, on some actions not to show it at all and for all states show some summary (in a tooltip, for example) of what has been changed. Important thing is that it's not just showing that some input fileds were touched and others not, it's again some combination of their state change.

The problem that I don't use <form> tag at all since most of custom components just don't have name attributes to support it. So I can't write a custom form validator, the main side effect of which will be updating state summary variable (since I need something more complex that just form valid-invalid summary flag).

I also consider an approach of attaching valueChange or ngModelChange callbacks to all inputs and components to be rather complex in implementation at the current state of development.

So there is a question how can I continuously update state summary variable based on data change.

I could use setInterval() to update state but its update delay will be something completely arbitrary from the angular update cycle.

Update state result is used in several places so creating just a function calculating it on request and putting it in all needed places is very ineffective.
I've tried a hack to use such function only in one place, put the result in a variable and in all other places use the variable but it leads to angular smth like "variable is updated after it was used" error.

Is there any better approach to the problem?

答:
I second Maryannah's idea of switching to reactive forms, with the addition of subscribing to the form's valueChanges Observable (or that of any form control) and using RxJS operators as required. For example:

```<code>// watch first name field for changes
this.userForm.get('firstName').valueChanges.pipe(
    debounceTime(300),
    distinctUntilChanged()
).subscribe(newFirstNameValue => {
    // do stuff with new value here
});

// watch whole form for compound checks
this.userForm.valueChanges.pipe(
    map(formData => {
        importantCheckbox: formData.importantCheckbox,
        desiredInput: formData.desiredInput
    })
).subscribe(formData => {
    // react to compound check here
});
</code>```

RxJS is incredibly powerful in this kind of situation. Definitely something to look into.

Body:
I second Maryannah's idea of switching to reactive forms, with the addition of subscribing to the form's valueChanges Observable (or that of any form control) and using RxJS operators as required. For example:

// watch first name field for changes
this.userForm.get('firstName').valueChanges.pipe(
    debounceTime(300),
    distinctUntilChanged()
).subscribe(newFirstNameValue => {
    // do stuff with new value here
});

// watch whole form for compound checks
this.userForm.valueChanges.pipe(
    map(formData => {
        importantCheckbox: formData.importantCheckbox,
        desiredInput: formData.desiredInput
    })
).subscribe(formData => {
    // react to compound check here
});

RxJS is incredibly powerful in this kind of situation. Definitely something to look into.


问:
SQL Differences between stored procedure and triggers
I'm having trouble understanding the difference between a stored procedure and a trigger in sql.
If someone could be kind enough to explain it to me that would be great.</p>

答:
Difference Between a Stored Procedure and a Trigger

We can define a trigger as a database object just like a stored procedure, or we can say it is a special kind of stored procedure which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when an event is fired.

```<code>    Triggers are fired implicitly while stored procedures are fired explicitly.
</code>```

Body:
Difference Between a Stored Procedure and a Trigger

We can define a trigger as a database object just like a stored procedure, or we can say it is a special kind of stored procedure which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when an event is fired.

    Triggers are fired implicitly while stored procedures are fired explicitly.


问:
Quantile random forests from scikit-garden very slow at making predictions
I've started working with quantile random forests (QRFs) from the scikit-garden package. Previously I was creating regular random forests using RandomForestRegresser from sklearn.ensemble.

It appears that the speed of the QRF is comparable to the regular RF with small dataset sizes, but that as the size of the data increases, the QRF becomes MUCH slower at making predictions than the RF.

Is this expected? If so, could someone please explain why it takes such a long time to make these predictions and/or give any suggestions as to how I could get quantile predictions in a more timely manner.

See below for a toy example, where I test the training and predictive times for a variety of dataset sizes.

```<code>import matplotlib as mpl
mpl.use('Agg')
from sklearn.ensemble import RandomForestRegressor
from skgarden import RandomForestQuantileRegressor
from sklearn.model_selection import train_test_split
import numpy as np
import time
import matplotlib.pyplot as plt

log_ns = np.arange(0.5, 5, 0.5) # number of observations (log10)
ns = (10 ** (log_ns)).astype(int)
print(ns)
m = 14 # number of covariates
train_rf = []
train_qrf = []
pred_rf = []
pred_qrf = []

for n in ns:
    # create dataset
    print('n = {}'.format(n))
    print('m = {}'.format(m))
    rndms = np.random.normal(size=n)
    X = np.random.uniform(size=[n,m])
    betas = np.random.uniform(size=m)
    y = 3 +  np.sum(betas[None,:] * X, axis=1) + rndms

    # split test/train
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

    # random forest
    rf = RandomForestRegressor(n_estimators=1000, random_state=0)
    st = time.time()
    rf.fit(X_train, y_train)
    en = time.time()
    print('Fit time RF = {} secs'.format(en - st))
    train_rf.append(en - st)

    # quantile random forest
    qrf = RandomForestQuantileRegressor(random_state=0, min_samples_split=10, n_estimators=1000)
    qrf.set_params(max_features = X.shape[1] // 3)
    st = time.time()
    qrf.fit(X_train, y_train)
    en = time.time()
    print('Fit time QRF = {} secs'.format(en - st))
    train_qrf.append(en - st)

    # predictions
    st = time.time()
    preds_rf = rf.predict(X_test)
    en = time.time()
    print('Prediction time RF = {}'.format(en - st))
    pred_rf.append(en - st)

    st = time.time()
    preds_qrf = qrf.predict(X_test, quantile=50)
    en = time.time()
    print('Prediction time QRF = {}'.format(en - st))
    pred_qrf.append(en - st)

fig, ax = plt.subplots()
ax.plot(np.log10(ns), train_rf, label='RF train', color='blue')
ax.plot(np.log10(ns), train_qrf, label='QRF train', color='red')
ax.plot(np.log10(ns), pred_rf, label='RF predict', color='blue', linestyle=':')
ax.plot(np.log10(ns), pred_qrf, label='QRF predict', color='red', linestyle =':')
ax.legend()
ax.set_xlabel('log(n)')
ax.set_ylabel('time (s)')
fig.savefig('time_comparison.png')
</code>```

Here is the output:
Time comparison of RF and QRF training and predictions

答:
I am not a developer on this or any quantile regression package, but I've looked at the source code for both scikit-garden and quantRegForest/ranger, and I have some idea of why the R versions are so much faster:

EDIT: On a related github issue, lmssdd mentions how this method performs significantly worse than the 'standard procedure' from the paper. I haven't read the paper in detail, so take this answer with a grain of skepticism.

Explanation of difference in skgarden/quantregforest methods

The basic idea of the skgarden predict function is to save all the y_train values corresponding to all of the leaves. Then, when predicting a new sample, you gather the relevant leaves and corresponding y_train values, and compute the (weighted) quantile of that array. The R versions take a shortcut: they only save a single, randomly chosen y_train value per leaf node. This has two advantages: it makes the gathering of relevant y_train values a lot simpler since there is always exactly one value in every leaf node. Secondly, it makes the quantile calculation a lot simpler since every leaf has the exact same weight.

Since you only use a single (random) value per leaf instead of all of them, this is an approximation method. In my experience, if you have enough trees, (at least 50-100 or so), this has very little effect on the result. However, I don't know enough about the math to say how good the approximation is exactly.

TL;DR: how to make skgarden predict faster

Below is an implementation of the simpler R method of quantile prediction, for a RandomForestQuantileRegressor model. Note that the first half of the function is the (one-time) process of selecting a random y_train value per leaf. If the author were to implement this method in skgarden, they would logically move this part to the fit method, leaving only the last 6 or so lines, which makes for a much faster predict method. Also in my example, I am using quantiles from 0 to 1, instead of from 0 to 100.

def predict_approx(model, X_test, quantiles=[0.05, 0.5, 0.95]):
    """
    Function to predict quantiles much faster than the default skgarden method
    This is the same method that the ranger and quantRegForest packages in R use
    Output is (n_samples, n_quantiles) or (n_samples, ) if a scalar is given as quantiles
    """
    # Begin one-time calculation of random_values. This only depends on model, so could be saved.
    n_leaves = np.max(model.y_train_leaves_) + 1  # leaves run from 0 to max(leaf_number)
    random_values = np.zeros((model.n_estimators, n_leaves))
    for tree in range(model.n_estimators):
        for leaf in range(n_leaves):
            train_samples = np.argwhere(model.y_train_leaves_[tree, :] == leaf).reshape(-1)
            if len(train_samples) == 0:
                random_values[tree, leaf] = np.nan
            else:
                train_values = model.y_train_[train_samples]
                random_values[tree, leaf] = np.random.choice(train_values)
    # Optionally, save random_values as a model attribute for reuse later

    # For each sample, get the random leaf values from all the leaves they land in
    X_leaves = model.apply(X_test)
    leaf_values = np.zeros((X_test.shape[0], model.n_estimators))
    for i in range(model.n_estimators):
        leaf_values[:, i] = random_values[i, X_leaves[:, i]]

    # For each sample, calculate the quantiles of the leaf_values
    return np.quantile(leaf_values, np.array(quantiles), axis=1).transpose()
```

Body:
I've started working with quantile random forests (QRFs) from the scikit-garden package. Previously I was creating regular random forests using RandomForestRegresser from sklearn.ensemble.

It appears that the speed of the QRF is comparable to the regular RF with small dataset sizes, but that as the size of the data increases, the QRF becomes MUCH slower at making predictions than the RF.

Is this expected? If so, could someone please explain why it takes such a long time to make these predictions and/or give any suggestions as to how I could get quantile predictions in a more timely manner.

See below for a toy example, where I test the training and predictive times for a variety of dataset sizes.

import matplotlib as mpl
mpl.use('Agg')
from sklearn.ensemble import RandomForestRegressor
from skgarden import RandomForestQuantileRegressor
from sklearn.model_selection import train_test_split
import numpy as np
import time
import matplotlib.pyplot as plt

log_ns = np.arange(0.5, 5, 0.5) # number of observations (log10)
ns = (10 ** (log_ns)).astype(int)
print(ns)
m = 14 # number of covariates
train_rf = []
train_qrf = []
pred_rf = []
pred_qrf = []

for n in ns:
    # create dataset
    print('n = {}'.format(n))
    print('m = {}'.format(m))
    rndms = np.random.normal(size=n)
    X = np.random.uniform(size=[n,m])
    betas = np.random.uniform(size=m)
    y = 3 +  np.sum(betas[None,:] * X, axis=1) + rndms

    # split test/train
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

    # random forest
    rf = RandomForestRegressor(n_estimators=1000, random_state=0)
    st = time.time()
    rf.fit(X_train, y_train)
    en = time.time()
    print('Fit time RF = {} secs'.format(en - st))
    train_rf.append(en - st)

    # quantile random forest
    qrf = RandomForestQuantileRegressor(random_state=0, min_samples_split=10, n_estimators=1000)
    qrf.set_params(max_features = X.shape[1] // 3)
    st = time.time()
    qrf.fit(X_train, y_train)
    en = time.time()
    print('Fit time QRF = {} secs'.format(en - st))
    train_qrf.append(en - st)

    # predictions
    st = time.time()
    preds_rf = rf.predict(X_test)
    en = time.time()
    print('Prediction time RF = {}'.format(en - st))
    pred_rf.append(en - st)

    st = time.time()
    preds_qrf = qrf.predict(X_test, quantile=50)
    en = time.time()
    print('Prediction time QRF = {}'.format(en - st))
    pred_qrf.append(en - st)

fig, ax = plt.subplots()
ax.plot(np.log10(ns), train_rf, label='RF train', color='blue')
ax.plot(np.log10(ns), train_qrf, label='QRF train', color='red')
ax.plot(np.log10(ns), pred_rf, label='RF predict', color='blue', linestyle=':')
ax.plot(np.log10(ns), pred_qrf, label='QRF predict', color='red', linestyle =':')
ax.legend()
ax.set_xlabel('log(n)')
ax.set_ylabel('time (s)')
fig.savefig('time_comparison.png')

Here is the output:
Time comparison of RF and QRF training and predictions


问:
Problems importing pandas.plotting
When I import pandas, everything is fine and working. Yet, when I try to import something from pandas.plotting im getting an error. What could be the source of this?

Here is how the output looks like:

```<code>>>> import pandas
>>> from pandas.plotting import scatter_matrix
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named plotting
</code>```

The pandas version Im using is: 0.19.2

答:
I figured out that most cases when the errors come up on the import scatter_matrix, it is because you have not restarted your jupyter notebooks for a while.
Before I run the code;
from pandas.tools.plotting import scatter_matrix
I make sure I restart my jupyter notebook and run the code. Everything works just fine from then on.</p>

Title: Problems importing pandas.plotting

Body:
When I import pandas, everything is fine and working. Yet, when I try to import something from pandas.plotting im getting an error. What could be the source of this?

Here is how the output looks like:

>>> import pandas
>>> from pandas.plotting import scatter_matrix
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named plotting

The pandas version Im using is: 0.19.2


问:
How can I paste data from one spreadsheet to the last column of another?
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

EDIT: Error occurs on this line:

```<code>Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
</code>```

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

```<code>Dest.Cells(1, colDest) = "Test"
</code>```

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

答:
Try this basically what you need to do is add 1 to the colDest to give you the next empty column.

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

EDIT: Error occurs on this line:

Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

Dest.Cells(1, colDest) = "Test"

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

Body:
Try this basically what you need to do is add 1 to the colDest to give you the next empty column.

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


问:
java equivalent to php "fnum" unpack function to convert hexadecimal to float IEEE 754 in java
I have this function in PHP:

```<code>function hex2float($strHex) {
   $array = unpack("fnum", pack("H*", $strHex));
   return $array['num'];
}
</code>```

How can I write that in java?

答:
I figured to convert this function in that way:</p>

```<code>private Float hex2float(String hexStr) {
    Float result = null;
    try {
        byte[] decodes = Hex.decodeHex(hexStr.toCharArray());
        result = getFloat(decodes, 0);
    } catch (DecoderException e) {
        // log error
    }
    return result;
}

private float getFloat(byte[] b, int index) {
    int l;
    l = b[index + 0];
    l &= 0xff;
    l |= ((long) b[index + 1] << 8);
    l &= 0xffff;
    l |= ((long) b[index + 2] << 16);
    l &= 0xffffff;
    l |= ((long) b[index + 3] << 24);
    return Float.intBitsToFloat(l);
}
</code>```

Body:
I have this function in PHP:

function hex2float($strHex) {
   $array = unpack("fnum", pack("H*", $strHex));
   return $array['num'];
}

How can I write that in java?

Body:
I figured to convert this function in that way:

private Float hex2float(String hexStr) {
    Float result = null;
    try {
        byte[] decodes = Hex.decodeHex(hexStr.toCharArray());
        result = getFloat(decodes, 0);
    } catch (DecoderException e) {
        // log error
    }
    return result;
}

private float getFloat(byte[] b, int index) {
    int l;
    l = b[index + 0];
    l &= 0xff;
    l |= ((long) b[index + 1] << 8);
    l &= 0xffff;
    l |= ((long) b[index + 2] << 16);
    l &= 0xffffff;
    l |= ((long) b[index + 3] << 24);
    return Float.intBitsToFloat(l);
}


答:
You could simplify the problem in the first place in the structure you are using to handle those date

```<code>foreach($fields as $field) {
     $mods[$field['name']][] = $field['rating'];
}
</code>```

then just foreach with the key parameter

```<code>foreach($mods as $name => $mod) {
     echo $name;
     echo array_sum($mod) / count($mod);
}
</code>```

Title: Group multidimensional array by key and sum values in PHP

Body:
You could simplify the problem in the first place in the structure you are using to handle those date

foreach($fields as $field) {
     $mods[$field['name']][] = $field['rating'];
}

then just foreach with the key parameter

foreach($mods as $name => $mod) {
     echo $name;
     echo array_sum($mod) / count($mod);
}


问:
Click mat-checkbox programmatically by getElementById
I would like to trigger a click event in ngAfterContentInit().

Running the code below, I got the error:

```<code>ERROR TypeError: Cannot read property 'click' of null
</code>```

Since I use NgFor to print out all the mat-checkbox,

I am afraid I can't use the method - ViewChild to achieve my purpose.

Component:

```<code><div *ngFor="let item of NationlityList.NationlityList; let i = index">
  <div *ngIf="i % 6 == 0" class="row">
      <mat-checkbox id="{{'Id'+i}}" *ngIf="i + 0 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i].Nationality)"> {{ NationlityList.NationlityList[i].Nationality }} </mat-checkbox>
      <mat-checkbox id="{{'Id'+(i+1)}}" *ngIf="i + 1 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+1].Nationality)"> {{ NationlityList.NationlityList[i+1].Nationality }} </mat-checkbox>
  </div>
</div>
</code>```

TS:

```<code>ngAfterContentInit() {
if (this.passedData.SelectedNationlity[0] !== 'All') {
  let element: HTMLElement = document.getElementById('Id21');
  element.click();
  }
}
</code>```

答:
You can do this:</p>

```<code>document.getElementById('checkboxID').setAttribute('checked','true')
</code>```

Body:
I would like to trigger a click event in ngAfterContentInit().

Running the code below, I got the error:

ERROR TypeError: Cannot read property 'click' of null

Since I use NgFor to print out all the mat-checkbox,

I am afraid I can't use the method - ViewChild to achieve my purpose.

Component:

      <mat-checkbox id="{{'Id'+i}}" *ngIf="i + 0 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i].Nationality)"> {{ NationlityList.NationlityList[i].Nationality }} </mat-checkbox>
      <mat-checkbox id="{{'Id'+(i+1)}}" *ngIf="i + 1 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+1].Nationality)"> {{ NationlityList.NationlityList[i+1].Nationality }} </mat-checkbox>

TS:

ngAfterContentInit() {
if (this.passedData.SelectedNationlity[0] !== 'All') {
  let element: HTMLElement = document.getElementById('Id21');
  element.click();
  }
}

Body:
You can do this:

document.getElementById('checkboxID').setAttribute('checked','true')


问:
How to limit what the Linux Teminal prints by defaults (prompt)? (i.e. number of subfolder)
Context:

The problem comes from the work folder location: if I should work in a subfolder of a subfolder of a subfolder et cetera... The command line of the shell bask in Linux is so long that can use two lines to be correctly printed.

Question:

Is there a way of showing only the last (or the few last) working subfolder?

Example:

What is actually printed:

```<code>user@user-pc:~/Documents/robotic_arm/Monitoring/difference/develop/component/example/subfolder/subexample/module$
</code>```

What I would love to see:

```<code>user@user-pc:~/.../subexample/module$
</code>```

More Info:

Xubuntu 16.04

Terminator is used instead of the default "Linux Terminal Emulator"

I had a look on this Stackoverflow's question but it is for the input and not for the default line printed by the shell

答:
Have a look at the PROMPTING section of man bash. You configure the prompt by setting PS1, and I suspect your current setting is something like this:

$ echo $PS1
\u@\h:\w\$
```

<p>If you change it to</p>

<pre class="lang-sh prettyprint-override"><code>$ PS1='\u@\h:\W\$ '
</code>```

it will only print the basename of the current working directory.

Body:
Context:

The problem comes from the work folder location: if I should work in a subfolder of a subfolder of a subfolder et cetera... The command line of the shell bask in Linux is so long that can use two lines to be correctly printed.

Question:

Is there a way of showing only the last (or the few last) working subfolder?

Example:

What is actually printed:

user@user-pc:~/Documents/robotic_arm/Monitoring/difference/develop/component/example/subfolder/subexample/module$

What I would love to see:

user@user-pc:~/.../subexample/module$

More Info:

Xubuntu 16.04

Terminator is used instead of the default "Linux Terminal Emulator"

I had a look on this Stackoverflow's question but it is for the input and not for the default line printed by the shell

Body:
Have a look at the PROMPTING section of man bash. You configure the prompt by setting PS1, and I suspect your current setting is something like this:

$ echo $PS1
\u@\h:\w\$

If you change it to

$ PS1='\u@\h:\W\$ '

it will only print the basename of the current working directory.


问:
How to fix tkinter cursor vertical offset while in full screen on macOS?
I am having a problem with Tkinter detecting the wrong cursor position when the application is in fullscreen mode on macOS.

I have created a Python 3 application with a Tkinter GUI on macOS (Mojave). The application works well until the green full screen button is pressed. After this the menu bar is hidden as expected, but the window only expands to 2560x1395 on a 2560x1440 display. The interface also detects the mouse cursor above where it appears on the screen, which makes the application impossible to use. I have tried forcing the application to expand to the full height of 1440, but it immediately changes back to 1395.

Here is a minimal case demonstrating the problem:

import tkinter as tk

def test():
    print("Test")

root = tk.Tk()
tk.Button(root, text="Test", width=20, command=test).pack()
root.mainloop()
```

While in normal windowed mode, clicking the button causes "Test" to be printed. While in full screen the user must click below the button for the click to be registered. Exiting the application while in full screen mode also causes a segmentation fault.

In my application, clicking where the red dot is causes the OptionMenu to open:

答:
The applications which support macOS properly opens in a separate Desktop tab when used in fullscreen. As far as I observed this is not case with tkinter, the window expands to fit completely with the screen size onto the main Desktop tab.

Why there is an offset when in fullscreen mode?

The offset is of the titlebar which hides in fullscreen mode but doesn't register and shifts all the widgets accordingly. That's why mouse clicks register + 24 (height of the titlebar) from the click. To avoid this we use root.attributes('-fullscreen', 1).

To exit fullscreen we can use <Escape> bind as Escape key in most application is to exit from fullscreen like in Safari. You can also use a Button.

```<code>root.bind('<Escape>', lambda e: root.attributes('-fullscreen', 0))
</code>```

I couldn't find an event handler for fullscreen mode on Mac so I used <Configure> with condition root.attributes('-fullscreen') to check if the user clicked for fullscreen or not.

This is what I come up with.

```<code>from tkinter import *

root = Tk()
Button(root, width=20, text='Hello').pack()

def full_screen(evt=None):
    # checks if the window is in fullscreen
    if root.attributes('-fullscreen'):
        root.attributes('-fullscreen',1)
        # Remove the borders and titlebar
        root.overrideredirect(True)
        root.overrideredirect(False)

root.bind('<Configure>', full_screen)
# Escape bind to exit fullscreen.
root.bind('<Escape>', lambda e: root.attributes('-fullscreen', 0))
root.mainloop()
</code>```

Body:
I am having a problem with Tkinter detecting the wrong cursor position when the application is in fullscreen mode on macOS.

I have created a Python 3 application with a Tkinter GUI on macOS (Mojave). The application works well until the green full screen button is pressed. After this the menu bar is hidden as expected, but the window only expands to 2560x1395 on a 2560x1440 display. The interface also detects the mouse cursor above where it appears on the screen, which makes the application impossible to use. I have tried forcing the application to expand to the full height of 1440, but it immediately changes back to 1395.

Here is a minimal case demonstrating the problem:

import tkinter as tk

def test():
    print("Test")

root = tk.Tk()
tk.Button(root, text="Test", width=20, command=test).pack()
root.mainloop()

While in normal windowed mode, clicking the button causes "Test" to be printed. While in full screen the user must click below the button for the click to be registered. Exiting the application while in full screen mode also causes a segmentation fault.

In my application, clicking where the red dot is causes the OptionMenu to open:

Body:
The applications which support macOS properly opens in a separate Desktop tab when used in fullscreen. As far as I observed this is not case with tkinter, the window expands to fit completely with the screen size onto the main Desktop tab.

Why there is an offset when in fullscreen mode?

The offset is of the titlebar which hides in fullscreen mode but doesn't register and shifts all the widgets accordingly. That's why mouse clicks register + 24 (height of the titlebar) from the click. To avoid this we use root.attributes('-fullscreen', 1).

To exit fullscreen we can use <Escape> bind as Escape key in most application is to exit from fullscreen like in Safari. You can also use a Button.

root.bind('<Escape>', lambda e: root.attributes('-fullscreen', 0))

I couldn't find an event handler for fullscreen mode on Mac so I used <Configure> with condition root.attributes('-fullscreen') to check if the user clicked for fullscreen or not.

This is what I come up with.

from tkinter import *

root = Tk()
Button(root, width=20, text='Hello').pack()

def full_screen(evt=None):
    # checks if the window is in fullscreen
    if root.attributes('-fullscreen'):
        root.attributes('-fullscreen',1)
        # Remove the borders and titlebar
        root.overrideredirect(True)
        root.overrideredirect(False)

root.bind('<Configure>', full_screen)
# Escape bind to exit fullscreen.
root.bind('<Escape>', lambda e: root.attributes('-fullscreen', 0))
root.mainloop()


问:
How to read excel file in Java when the file is located within the java project?
What should be the syntax when the excel file that I'm trying to call is imported within the project.

答:
The syntax you are using is correct but make sure your using the correct path of your local file.

When your local file is in the same package/folder where you write your codes.Just write down its file name.

var file = new FileInputStream("Dashboard.xlsx");

or try using Absolute path of your filename.

var file = new FileInputStream("M3A FrontEndPoc/Dashboard.xlsx");


问:
is it possible to cast Dword to Type Name?
Let's take a look at this kind of code :

```<code>// Return me Dword of int
dword t = GetValueTypeNo<int>();
//here trying to tell to GetValue that my template is int (since t is dword of int)
int test5 = myVector.GetValue<t>("test5");
</code>```

Of course this kind of code is not working and it's actually useless. But it is possible to do something like that? cast a dword to a type name like int?

答:
You can use the decltype keyword:

```<code>dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<decltype(t)>("test5");
</code>```

But the here the template parameter of GetValue will be dword instead of int.

Body:
Let's take a look at this kind of code :

// Return me Dword of int
dword t = GetValueTypeNo<int>();
//here trying to tell to GetValue that my template is int (since t is dword of int)
int test5 = myVector.GetValue<t>("test5");

Of course this kind of code is not working and it's actually useless. But it is possible to do something like that? cast a dword to a type name like int?

Body:
You can use the decltype keyword:

dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<decltype(t)>("test5");

But the here the template parameter of GetValue will be dword instead of int.


问:
Android Activity lifecycle issue
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }
</code>```

In Cart activity when I press a button it comes to activity Home.

For That

```<code> public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }
</code>```

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?

答: Consider using TabHost if you have two activities run simultaneously.</p>

Title: Android Activity lifecycle issue

Body:
I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.

For that I used the following Code

 public void onClick(View v) {
     Intent intent = new Intent(this, Cart.class);
     startActivity(intent);
 }

In Cart activity when I press a button it comes to activity Home.

For That

 public void onClick(View v) {
     Intent intent = new Intent(this, Home.class);
     startActivity(intent);
 }

Activities are changing fine but the onCreate method calls every time the activity starts.

Is that a fine life cycle of Activity or not? If not, how can I solve this?


问:
how to get all value from while loop not just 1st iteration?
The final is the numpy array with 4 rows and I need to get all value from nested while loop, but this code just returns 1st row of final or 1st iteration of loop.</p>

```<code>def amir2 (final):
    i = 0
    j = 0
    temp = []
    temp2 = []
    temp3 = []
    while i < len(final):
        while j < len(final):
            cos_lib = coss(final[i] , final[j])
            temp.append(cos_lib)
            j += 1
        temp2.append(temp)
        i += 1
    return temp2
</code>```

答: for numpy use temp2 = np.append(temp2,temp)</p>

Body:
The final is the numpy array with 4 rows and I need to get all value from nested while loop, but this code just returns 1st row of final or 1st iteration of loop.

def amir2 (final):
    i = 0
    j = 0
    temp = []
    temp2 = []
    temp3 = []
    while i < len(final):
        while j < len(final):
            cos_lib = coss(final[i] , final[j])
            temp.append(cos_lib)
            j += 1
        temp2.append(temp)
        i += 1
    return temp2


问:
Maven dependency errors
After importing the project from GitHub, getting the maven dependency error

```<code>Following the S4HANA Cloud SDK SAP Press book exercises. After importing the project into intellij IDE, it thorows maven dependency errors.  Here are the steps-
1. Download the project to do unit test. Link: https://github.com/SAP/cloud-s4-sdk-book/tree/course/2_5_testing
2. Imported the project into IntelliJIDE
3. Renamed the folder to address-manager (from cloud-s4-sdk-book-course-2_5_testing)
4. After importing went to the folder address-manager --> unit-tests --> src ---> test --> java --> com.sap.cloud.s4hana.examples.addressmgr --> commands --> GetAllBusinessPartnersCommandTest
</code>```

After this, as soon we now open the command, we get these dependency errors
All the piece of code like google, sdk and so on comes red and is not able to identify.

答:
The mentioned artifacts are available here.
So you either have a setup issue or a connection issue.

Please make sure that:

your POM file does not contain any syntax errors

you can connect to Maven Central (you may have to check your proxy settings)

I also recommend to consult the Maven documentation for further help:
https://maven.apache.org/guides/

Finally, please also make sure to use the latest SDK version.

Title: Maven dependency errors

Body:
After importing the project from GitHub, getting the maven dependency error

Following the S4HANA Cloud SDK SAP Press book exercises. After importing the project into intellij IDE, it thorows maven dependency errors.  Here are the steps-
1. Download the project to do unit test. Link: https://github.com/SAP/cloud-s4-sdk-book/tree/course/2_5_testing
2. Imported the project into IntelliJIDE
3. Renamed the folder to address-manager (from cloud-s4-sdk-book-course-2_5_testing)
4. After importing went to the folder address-manager --> unit-tests --> src ---> test --> java --> com.sap.cloud.s4hana.examples.addressmgr --> commands --> GetAllBusinessPartnersCommandTest

After this, as soon we now open the command, we get these dependency errors
All the piece of code like google, sdk and so on comes red and is not able to identify.


问:
How can one route a search URL which has a query string embedded?
I am working on an express application and I have two GET URLs. One fetches all resources in the database but is right-protected(needs authentication and admin access) while the other fetches resources based on a search parameter(query string).

The route that requires authentication looks like so:

carRouter.get('/car', verifyToken, isAdmin, fetchAllCarAds);

This means that the admin has to be logged in first and then a check is carried out to ascertain whether he is truly an admin before he is given access. Now I have another GET route that doesn't require authentication like so
:

carRouter.get('/car?status=unsold', filterUnsoldCars);.

I understand that express does not allow routing based on query strings so how do I ensure that the request that does not require authentication(query string) is accessible in the one without query string?

答:
I dont think you are building a proper routing but, you can use a middleware to check query params and bypasses to the next route assigned. check below routing explanation for next('route')

Express Routing

```<code>carRouter.get('/car', hasParams, verifyToken, isAdminDummy, fetchAllCarAds);
carRouter.get('/car?status=unsold', filterUnsoldCars);
</code>```

if hasParams true, next('route')

if hasParams false, next()

Body:
I dont think you are building a proper routing but, you can use a middleware to check query params and bypasses to the next route assigned. check below routing explanation for next('route')

Express Routing

carRouter.get('/car', hasParams, verifyToken, isAdminDummy, fetchAllCarAds);
carRouter.get('/car?status=unsold', filterUnsoldCars);

if hasParams true, next('route')

if hasParams false, next()


问:
Can a REST API built with Flask and Python be accessed from an external network?
I'm trying to use a REST API, built using Flask and Python, to create a server from my Raspberry Pi and access it from my iPhone. I have a very simple question: can I access the server from a network other than the one it is created on? So, for example, if the server is created on my home wifi, can I access it from my workplace wifi? If so, how?

Currently, I can access the server from any device connected to the same network. I have seen many similar posts online about similar problems, but I cannot find a direct answer to my question above.

Here is my code:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/test")
def hello():
    return jsonify({"about":"Hello World"})

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=2000,debug=True)
```

If I go onto Safari on my iPhone when connected to mobile data and type in "http://RaspberryPiIP:2000/test", then the page will not load and "take too long to respond." However, if I do the same thing on my home wifi, which the raspberry pi is also connected to, the page will load as expected.

答:
This has nothing to do with your code. You just need to route the requests from your external (public) IP address to the internal IP address of the server in your network. If you are at home, you need to configurate your router. This is often called port forwarding or port mapping.
You may also want to use a dynamic dns service, because most external ips will be changed frequently by your ISP.</p>

Body:
I'm trying to use a REST API, built using Flask and Python, to create a server from my Raspberry Pi and access it from my iPhone. I have a very simple question: can I access the server from a network other than the one it is created on? So, for example, if the server is created on my home wifi, can I access it from my workplace wifi? If so, how?

Currently, I can access the server from any device connected to the same network. I have seen many similar posts online about similar problems, but I cannot find a direct answer to my question above.

Here is my code:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/test")
def hello():
    return jsonify({"about":"Hello World"})

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=2000,debug=True)

If I go onto Safari on my iPhone when connected to mobile data and type in "http://RaspberryPiIP:2000/test", then the page will not load and "take too long to respond." However, if I do the same thing on my home wifi, which the raspberry pi is also connected to, the page will load as expected.


问:
How to get the content of the element using explicit wait instead of sleep() using Selenium and Java
I'm trying to get the content of an element. I've implemented an explicit wait of 20 seconds before the statement of getting content. But I can't get the content. I can get the content of the element if I use sleep() for 2 seconds. The code I tried is:

```<code>WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is :
</code>```

The code with sleep():

```<code>WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : $0.00
</code>```

I'm not getting the value if I use implicit wait also. It is recommended not to use sleep(). Using explicit wait is always the best practice. Why am I not getting the content of the element using explicit wait?

答:
Can you give a try:</p>

```<code>Wait<WebDriver> wait = new FluentWait<WebDriver>((WebDriver) driver).withTimeout(20, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("XPath"))));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);
</code>```

Body:
I'm trying to get the content of an element. I've implemented an explicit wait of 20 seconds before the statement of getting content. But I can't get the content. I can get the content of the element if I use sleep() for 2 seconds. The code I tried is:

WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is :

The code with sleep():

WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : $0.00

I'm not getting the value if I use implicit wait also. It is recommended not to use sleep(). Using explicit wait is always the best practice. Why am I not getting the content of the element using explicit wait?

Body:
Can you give a try:

Wait<WebDriver> wait = new FluentWait<WebDriver>((WebDriver) driver).withTimeout(20, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("XPath"))));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);


问:
how to display the contents of a tab in the workspace of Jtabbedpane?
i'v put a jpanel on the tab of Jtabbedpane which is at the left side ,nw when the tab is clicked i want to display labels and textfields in the workspace of the tabbedpane,plz hlp. </p>

答:
I think you should do exactly as @7SpecialGems says (+1 for that).
Here is an example showing how exactly it can look like in code.

```<code>import java.awt.Color;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JTabbedPaneSample
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run()
            {
                createGUI();
            }
        });
    }

    private static void createGUI() throws HeadlessException
    {
        JPanel oi1 = new JPanel();
        oi1.setBackground(Color.RED);
        oi1.add(new JLabel("Label 1"));
        JPanel oi2 = new JPanel();
        oi2.setBackground(Color.PINK);
        oi2.add(new JLabel("Label 2"));
        oi2.add(new JTextField("TextField 1"));
        JTabbedPane tp = new JTabbedPane();
        tp.addTab("Oi1", oi1);
        tp.addTab("Oi2", oi2);
        JPanel contentPane = new JPanel();
        contentPane.add(tp);
        JFrame f = new JFrame();
        f.setContentPane(contentPane);
        f.setSize(800, 600);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}
</code>```

Good luck, Boro.

Body:
I think you should do exactly as @7SpecialGems says (+1 for that).
Here is an example showing how exactly it can look like in code.

import java.awt.Color;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JTabbedPaneSample
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run()
            {
                createGUI();
            }
        });
    }

    private static void createGUI() throws HeadlessException
    {
        JPanel oi1 = new JPanel();
        oi1.setBackground(Color.RED);
        oi1.add(new JLabel("Label 1"));
        JPanel oi2 = new JPanel();
        oi2.setBackground(Color.PINK);
        oi2.add(new JLabel("Label 2"));
        oi2.add(new JTextField("TextField 1"));
        JTabbedPane tp = new JTabbedPane();
        tp.addTab("Oi1", oi1);
        tp.addTab("Oi2", oi2);
        JPanel contentPane = new JPanel();
        contentPane.add(tp);
        JFrame f = new JFrame();
        f.setContentPane(contentPane);
        f.setSize(800, 600);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

Good luck, Boro.


问:
session item does not change when using lov in primary key
I am implementing a Interactive grid to perform DML operations on a table.

it has combined primary key of two columns
One primary key column is display only and refer to master table and another primary key column I want to have a LOV to select value. LOV is dynamic lov having a display and return value picked from another table.

Inserts are fine but session state item value is set for one row and all the operations are performed on that same row irrespective of which row is selected.

you can see a sample here
https://apex.oracle.com/pls/apex/f?p=128616:2:1964277347439::NO:::

master table name: sample
detail table name: sample_child

primary key in sample child : ID and Name
pop lov is implemented in NAME
LOV values are picked from table: Sample_uncle
LOV display : ID || '-' || NAME
LOV return  : ID

you can try to update blabla column of sample_child table to see the issue.

I am not sure how I can give you access to look at the implementation.

I have already tried all the options I can think of

答:
This is to do with your primary keys, the detail table does not appear to have proper ones, thats why it always tried to update the first entry, and I think this is also why every row is marked when you load the table.

Primary keys also do the annoying thing of refusing to be empty, as you can see if you insert a new row, the middle column(which is a PK) is filled with 't1001'.

Since you are dealing with simple tables(and not a whole bunch of joined tables) I always consider it best to use ROWID as PK. So set ROWID as PK for the master table, and ROWID for the detail table. And have the detail table have a Master table be your master table, and then click on the first column in the detail table and set the master column for it. And I also personaly always hide the column that is linked.

I would advise you use ROWID whenever possible as its just so much easier to work with, it does mean you might need to set up a validation to prevent someone adding duplicated values for your actual PK, but since the PK is in the underlying table, they cant enter it anyways(but if you have a validation, the error will be much prettier), whilst if the column is a PK, APEX will prevent duplicates by default.

I hope this helps


问:
How to get the current time as datetime
Just started with the playground. I'm trying to create a simple app.

I've created a date object like this:

```<code>var date = NSDate()
</code>```

How can I get the current hour? In other languages I can do something like this:

```<code>var hour = date.hour
</code>```

But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?

答:
SWIFT 4:</p>

```<code>extension Date
{
    func hour() -> Int
    {
    //Get Hour
    let calendar = Calendar.current
    let components = calendar.component(.hour, from: self)
    let hour = components

    //Return Hour
    return hour
    }

    func minute() -> Int
    {
    //Get Minute
    let calendar = Calendar.current
    let components = calendar.component(.minute, from: self)
    let minute = components

    //Return Minute
    return minute
        }
}
</code>```

Title: How to get the current time as datetime

Body:
Just started with the playground. I'm trying to create a simple app.

I've created a date object like this:

var date = NSDate()

How can I get the current hour? In other languages I can do something like this:

var hour = date.hour

But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?

Body:
SWIFT 4:

extension Date
{
    func hour() -> Int
    {
    //Get Hour
    let calendar = Calendar.current
    let components = calendar.component(.hour, from: self)
    let hour = components

    //Return Hour
    return hour
    }

    func minute() -> Int
    {
    //Get Minute
    let calendar = Calendar.current
    let components = calendar.component(.minute, from: self)
    let minute = components

    //Return Minute
    return minute
        }
}


问:
Power BI Measure to calculate percentage which changes with filters
I want to create a visualisation from a dataset which shows percentages that change accordingly when filters are used.

I have a dataset like the below but with over 1 million rows of data covering 18 months. All the fields are text except Month which is a date and SUMofAPPTS which is numerical.

```<code>SUPP    GEOG1   MODE    STATUS  TYPE    TIME    Month   Day    SUMofAPPTS
AA  00D Face    Att     1       1       Day     2018-06 Sun    12
AA  00D Face    Att     1       1       Day     2018-06 Mon    119
AA  00D Face    Att     1       4       Unk     2018-06 Tues   98
BB  00D Tel     DNA     2       1       Day     2018-06 Weds   98
BB  00D Online  DNA     3       1       Day     2018-06 Thurs  126
CC  00D Face    DNA     1       2       Day     2018-07 Sun    8
</code>```

I would like a measure which calculates the percentage of SUMofAPPTS by Day and MODE (and the same but for STATUS, TYPE and TIME) which changes when filters are placed on the other fields.

So I think I need to make this simple calculation (which would work in a column if I just wanted to know the percentage per row of the whole dataset) more dynamic so that it works when I filter the data:

```<code>PERCENT = 'dataset'[SUMofAPPTS]/SUM('dataset'[SUMofAPPTS])
</code>```

The end result will be a stacked bar chart with the following attributes:

Day as the Axis

PERCENT as the Value

MODE, STATUS, TYPE or TIME as the Legend

Ability to filter by one, many or all of the fields except Day and SUMofAPPTS

答:
First, create a measure for aggregating SUMofAPPTS:

```<code>Total APPTS = SUM(Data[SUMofAPPTS])
</code>```

Second, create a measure for the percentage:

```<code>APPTS % of Selected
= DIVIDE(
   [Total APPTS],
   CALCULATE([Total APPTS], ALLSELECTED()))
</code>```

This measure recalculates [Total APPTS] ignoring all filters except those selected by a user (on slicers etc).

Result:

after selections:

Edit

If you need to breakdown by Day (or any other field), you can re-introduce filters like this:

```<code>APPTS % of Selected
= DIVIDE(
   [Total APPTS],
   CALCULATE([Total APPTS], ALLSELECTED(), VALUES(Data[Day])))
</code>```

Body:
I want to create a visualisation from a dataset which shows percentages that change accordingly when filters are used.

I have a dataset like the below but with over 1 million rows of data covering 18 months. All the fields are text except Month which is a date and SUMofAPPTS which is numerical.

SUPP    GEOG1   MODE    STATUS  TYPE    TIME    Month   Day    SUMofAPPTS
AA  00D Face    Att     1       1       Day     2018-06 Sun    12
AA  00D Face    Att     1       1       Day     2018-06 Mon    119
AA  00D Face    Att     1       4       Unk     2018-06 Tues   98
BB  00D Tel     DNA     2       1       Day     2018-06 Weds   98
BB  00D Online  DNA     3       1       Day     2018-06 Thurs  126
CC  00D Face    DNA     1       2       Day     2018-07 Sun    8

I would like a measure which calculates the percentage of SUMofAPPTS by Day and MODE (and the same but for STATUS, TYPE and TIME) which changes when filters are placed on the other fields.

So I think I need to make this simple calculation (which would work in a column if I just wanted to know the percentage per row of the whole dataset) more dynamic so that it works when I filter the data:

PERCENT = 'dataset'[SUMofAPPTS]/SUM('dataset'[SUMofAPPTS])

The end result will be a stacked bar chart with the following attributes:

Day as the Axis

PERCENT as the Value

MODE, STATUS, TYPE or TIME as the Legend

Ability to filter by one, many or all of the fields except Day and SUMofAPPTS

Body:
First, create a measure for aggregating SUMofAPPTS:

Total APPTS = SUM(Data[SUMofAPPTS])

Second, create a measure for the percentage:

APPTS % of Selected
= DIVIDE(
   [Total APPTS],
   CALCULATE([Total APPTS], ALLSELECTED()))

This measure recalculates [Total APPTS] ignoring all filters except those selected by a user (on slicers etc).

Result:

after selections:

Edit

If you need to breakdown by Day (or any other field), you can re-introduce filters like this:

APPTS % of Selected
= DIVIDE(
   [Total APPTS],
   CALCULATE([Total APPTS], ALLSELECTED(), VALUES(Data[Day])))


问:
PHP: compare substrings
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

```<code><?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>
</code>```

答:
You can use various approaches here. For example:

```<code>$cal = explode('.', $cal);
if(last($cal) === "cfg")) {
    echo "Hello";
}
</code>```

Or using regular expressions (which are probably way slower than using strpos for example):

```<code>if(preg_match("/\.cfg$", $cal)) {
   echo "Hello";
}
</code>```

I honestly don't know how the explode() version compares to substr() with a negative value (lonesomeday's answer) or strpos() (which has its flaws, Frosty Z's answer). Probably the substr() version is the fastet, while regular expressions are the slowest possible way to do this).

Title: PHP: compare substrings

Body:
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

<?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>

Body:
You can use various approaches here. For example:

$cal = explode('.', $cal);
if(last($cal) === "cfg")) {
    echo "Hello";
}

Or using regular expressions (which are probably way slower than using strpos for example):

if(preg_match("/\.cfg$", $cal)) {
   echo "Hello";
}

I honestly don't know how the explode() version compares to substr() with a negative value (lonesomeday's answer) or strpos() (which has its flaws, Frosty Z's answer). Probably the substr() version is the fastet, while regular expressions are the slowest possible way to do this).


问:
I accidentally uploaded .env file with google key in it to github but edited the file and removed the key. Can the change be seen somewhere?
So I created an .env file and had the impression that .env files do not get commited, however, it did. Since it contains a Google API key, I edited the .env file straight away and removed the key from it, however, I wonder if there's a way for people to see what changes have been done to that .env file ( like removing text which in my case is the API key )</p>

答:
revoke the current key and create a new one (for safety reasons)

you can remove it by filtering the branch you are working on by using
git filter-branch

you can find about it in details here

https://help.github.com/en/articles/removing-sensitive-data-from-a-repository