问:
Intellij - How do I treat warnings as errors that will prevent compilation?
How do I treat warnings as errors that will prevent compilation in Intellij?  I figured out how to change the inspection severity to error, and that will underline the problem in red, but compilation still succeeds.  And also it doesn't show any red underlines in the project view like a normal error does.</p>

答:
IntelliJ can't change the rules that govern the compiler; the red-yellow-green is intended to influence your behavior.

Only proceed if IntelliJ shows green; ask your teammates to do so as well.


来源: stackexchange

问:
error when connecting oracle in python using cx_Oracle
I was trying to connect oracle database using python like below.

```<code>import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')
</code>```

I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.

I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,

'admin/admin@10.10.10.10:1010/orcl'.

Why coudn't it connect?

Ahh, btw I'm running all the code in azure notebooks.

答:
That error indicates that you are missing a 64-bit Oracle client installation or it hasn't been configured correctly. Take a look at the link mentioned in the error message. It will give instructions on how to perform the Oracle client installation and configuration.

[Update on behalf of Anthony: his latest cx_Oracle release doesn't need Oracle Client libraries so you won't see the DPI-1047 error if you upgrade.  The driver got renamed to python-oracledb but the API still supports the Python DB API 2.0 specification. See the homepage.]

ContentLicense: CC BY-SA 3.0

Body:
I was trying to connect oracle database using python like below.

import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')

I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.

I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,

'admin/admin@10.10.10.10:1010/orcl'.

Why coudn't it connect?

Ahh, btw I'm running all the code in azure notebooks.

ContentLicense: CC BY-SA 4.0


问:
Select only one term_id from taxonomy

I have a custom post type and a taxonomy, where I can put more the one value to the taxonomy, in this case the taxonomy is the city. I want to make a query that the result is the posts that only have ONE value set. Example: I want all posts that the taxnomy is only "term_id = 3" that is "sao-paulo-sp".

But I have some posts that has more than one value set to it, like "sao-paulo-sp, city 2, city 3 city 4, etc" and this kinda of post keep showing up in my results.

```<code>SELECT wp.ID, wp.post_title, wt.term_id  FROM wp_posts wp
INNER JOIN wp_term_relationships wtr ON (wp.`ID` = wtr.`object_id`)
INNER JOIN wp_term_taxonomy wtt ON (wtr.`term_taxonomy_id` =
wtt.`term_taxonomy_id`)
INNER JOIN wp_terms wt ON (wt.`term_id` = wtt.`term_id`)
WHERE wtt.taxonomy = 'cities'
AND wt.slug = 'sao-paulo-sp'
ORDER BY wp.ID
</code>```

I would like that the result was the posts that only have "sao-paulo-sp" or "term_id = 3' as his value to the taxonomy cities

答:
If I understand correctly, you want something like this:

```<code>SELECT wp.ID, wp.post_title, wt.term_id
FROM wp_posts wp INNER JOIN
     wp_term_relationships wtr
     ON wp.`ID` = wtr.`object_id` INNER JOIN
     wp_term_taxonomy wtt
     ON wtr.`term_taxonomy_id` = wtt.`term_taxonomy_id` INNER JOIN
     wp_terms wt
     ON wt.`term_id` = wtt.`term_id`
WHERE wtt.taxonomy = 'cities'
GROUP BY wp.ID
HAVING COUNT(*) = 1 AND MAX(wt.slug) = 'sao-paulo-sp'
ORDER BY wp.ID;
</code>```

I am not sure what wt.term_id is doing in the SELECT list.

Title: Select only one term_id from taxonomy

Body:
I have a custom post type and a taxonomy, where I can put more the one value to the taxonomy, in this case the taxonomy is the city. I want to make a query that the result is the posts that only have ONE value set. Example: I want all posts that the taxnomy is only "term_id = 3" that is "sao-paulo-sp".

But I have some posts that has more than one value set to it, like "sao-paulo-sp, city 2, city 3 city 4, etc" and this kinda of post keep showing up in my results.

SELECT wp.ID, wp.post_title, wt.term_id  FROM wp_posts wp
INNER JOIN wp_term_relationships wtr ON (wp.`ID` = wtr.`object_id`)
INNER JOIN wp_term_taxonomy wtt ON (wtr.`term_taxonomy_id` =
wtt.`term_taxonomy_id`)
INNER JOIN wp_terms wt ON (wt.`term_id` = wtt.`term_id`)
WHERE wtt.taxonomy = 'cities'
AND wt.slug = 'sao-paulo-sp'
ORDER BY wp.ID

I would like that the result was the posts that only have "sao-paulo-sp" or "term_id = 3' as his value to the taxonomy cities

Body:
If I understand correctly, you want something like this:

SELECT wp.ID, wp.post_title, wt.term_id
FROM wp_posts wp INNER JOIN
     wp_term_relationships wtr
     ON wp.`ID` = wtr.`object_id` INNER JOIN
     wp_term_taxonomy wtt
     ON wtr.`term_taxonomy_id` = wtt.`term_taxonomy_id` INNER JOIN
     wp_terms wt
     ON wt.`term_id` = wtt.`term_id`
WHERE wtt.taxonomy = 'cities'
GROUP BY wp.ID
HAVING COUNT(*) = 1 AND MAX(wt.slug) = 'sao-paulo-sp'
ORDER BY wp.ID;

I am not sure what wt.term_id is doing in the SELECT list.


问:
Why are the values for both dictionaries being updated, when I only want one updated? (Python OOP)
Here is the relevant portion of my code:

```<code>class Document:
    def __init__(self):
        self.term_frequency_per_document = {}
        self.document_frequency = {}
        self.term_freq_inv_doc_freq = {}
        self.file = None
        self.student_list = []
        self.index = 0

    def calculate_TFIDF(self):

        for key in self.term_frequency_per_document:
            for value in self.term_frequency_per_document[key]:
                self.term_freq_inv_doc_freq[key] = self.term_frequency_per_document.get(key)
            for value in self.term_freq_inv_doc_freq[key]:
                self.term_freq_inv_doc_freq[key][value] = \
                    (self.term_freq_inv_doc_freq[key][value]) * \
                    (math.log(26 / float(self.document_frequency.get(value))))

        print (self.term_freq_inv_doc_freq)
        print (self.document_frequency)
        print (self.term_frequency_per_document)
</code>```

When I execute the calculate_TFDIF method, the values of both the self.term_frequency_per_document and self.term_freq_inv_per_doc dictionaries are being updated, when I only want the latter dictionary's values updated. I know that the erroneous update is occurring in the calculate_TFDIF method, but I cannot figure out why.

The term_frequency_per_document dictionary should read:

```<code>{'student_1': {'love': 1, 'play': 2, 'watch': 1}, 'student_2': {'favorite': 2, 'hobby': 1}
</code>```

After executing the calculate_TFDIF method, the term_freq_inv_doc_freq dictionary should read:

```<code>{'student_1': {'love': 1.6486586255873816, 'play': 2.121743921370525, 'watch': 1.8718021769015913} 'student_2': {'favorite': 1.9110228900548727, 'hobby': 1.1786549963416462}
</code>```

Unfortunately, both dictionaries look like the latter.

答:
I suspect you assign the same dictionary to two variables and then both variables use the same data in memory. You will have to use copy.deepcopy() to create two separated dictionares.

BTW: You may run code on pythontutor.com to see how Python use "references" to objects im memory (see "arrows" when you run code on pythontutor)

Body:
Here is the relevant portion of my code:

class Document:
    def __init__(self):
        self.term_frequency_per_document = {}
        self.document_frequency = {}
        self.term_freq_inv_doc_freq = {}
        self.file = None
        self.student_list = []
        self.index = 0

    def calculate_TFIDF(self):

        for key in self.term_frequency_per_document:
            for value in self.term_frequency_per_document[key]:
                self.term_freq_inv_doc_freq[key] = self.term_frequency_per_document.get(key)
            for value in self.term_freq_inv_doc_freq[key]:
                self.term_freq_inv_doc_freq[key][value] = \
                    (self.term_freq_inv_doc_freq[key][value]) * \
                    (math.log(26 / float(self.document_frequency.get(value))))

        print (self.term_freq_inv_doc_freq)
        print (self.document_frequency)
        print (self.term_frequency_per_document)

When I execute the calculate_TFDIF method, the values of both the self.term_frequency_per_document and self.term_freq_inv_per_doc dictionaries are being updated, when I only want the latter dictionary's values updated. I know that the erroneous update is occurring in the calculate_TFDIF method, but I cannot figure out why.

The term_frequency_per_document dictionary should read:

{'student_1': {'love': 1, 'play': 2, 'watch': 1}, 'student_2': {'favorite': 2, 'hobby': 1}

After executing the calculate_TFDIF method, the term_freq_inv_doc_freq dictionary should read:

{'student_1': {'love': 1.6486586255873816, 'play': 2.121743921370525, 'watch': 1.8718021769015913} 'student_2': {'favorite': 1.9110228900548727, 'hobby': 1.1786549963416462}

Unfortunately, both dictionaries look like the latter.


问:
Excel Vba bold some text on a string
i need some help with excel.

I have a cell that get value by macro with code:

```<code>Range("A1").Value = "This Year we are having our guest " &Guest_name &" who is currently " &Guest_age &"years old, spending holidays with us"
</code>```

So i'm just wondering how can I get the Guest_name and Guest_age to be bold.

Thanks

答: Use InStr to locate each within the range's .value2 property and apply .font.bold = true to the substring's .Characters property.</p>

Title: Excel Vba bold some text on a string

Body:
i need some help with excel.

I have a cell that get value by macro with code:

Range("A1").Value = "This Year we are having our guest " &Guest_name &" who is currently " &Guest_age &"years old, spending holidays with us"

So i'm just wondering how can I get the Guest_name and Guest_age to be bold.

Thanks


问:
Recursive types in OCaml?
Hi this is my first time posting on Stack Overflow and I've run into a problem while trying to construct a type in OCaml

I'm trying to construct a type tree that has nodes/leafs/etc. This is what I have so far.

```<code>type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a * tree) | ....
</code>```

My node is supposed to be a type that contains the its name and another tree as a tuple.  But when I tried to compile this it said tree required two arguments. So I tried:

```<code>type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a * tree ('a*'b))
</code>```

and I was still getting an error.  Anything that you notice I was doing wrong? Thanks!

答:
```<code>type ('a, 'b) tree = Empty | Leaf of 'b | Node of 'a * ('a, 'b) tree
</code>```

You probably want your Nodes two have more than one child, though

```<code>type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a, 'b) tree * 'a * ('a, 'b) tree
</code>```

PS : Beware than in a type declaration, Foo of bar * baz and Foo of (bar * baz) are not the same : the first is a constructor Foo with two fields, the second has only one field, which is of type (bar * baz).

ContentLicense: CC BY-SA 2.5

Title: Recursive types in OCaml?

Body:
Hi this is my first time posting on Stack Overflow and I've run into a problem while trying to construct a type in OCaml

I'm trying to construct a type tree that has nodes/leafs/etc. This is what I have so far.

type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a * tree) | ....

My node is supposed to be a type that contains the its name and another tree as a tuple.  But when I tried to compile this it said tree required two arguments. So I tried:

type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a * tree ('a*'b))

and I was still getting an error.  Anything that you notice I was doing wrong? Thanks!

Body:
type ('a, 'b) tree = Empty | Leaf of 'b | Node of 'a * ('a, 'b) tree

You probably want your Nodes two have more than one child, though

type ('a, 'b) tree = Empty | Leaf of 'b | Node of ('a, 'b) tree * 'a * ('a, 'b) tree

PS : Beware than in a type declaration, Foo of bar * baz and Foo of (bar * baz) are not the same : the first is a constructor Foo with two fields, the second has only one field, which is of type (bar * baz).


问:
could not find compatible versions for gem "rubyzip"
I am using

gem 'axlsx_rails'

gem 'acts_as_xlsx'

for downloading file into excel.
Now I am trying to add the following gem

gem 'caracal'

for downloading file into docx.
Whenever, I am trying to run

bundle install, I got the following error

Bundler could not find compatible versions for gem "rubyzip":   In
  snapshot (Gemfile.lock):
      rubyzip (= 1.0.0)

In Gemfile:
      acts_as_xlsx was resolved to 1.0.6, which depends on
        axlsx (>= 1.0.13) was resolved to 2.0.1, which depends on
          rubyzip (~> 1.0.0)

```<code>caracal was resolved to 0.1.0, which depends on
  rubyzip (~> 1.1)
</code>```

Running bundle update will rebuild your snapshot from scratch, using
  only the gems in your Gemfile, which may resolve the conflict.

My gem file looks like following

source 'https://rubygems.org'

gem 'rails', '4.1.9'

gem 'mysql2', '~> 0.3.19'

gem 'sass-rails', '~> 4.0.3'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.0.0'

gem 'jquery-rails'

gem 'jbuilder', '~> 2.0'

gem 'sdoc', '~> 0.4.0',          group: :doc

gem 'spring',        group: :development

gem 'devise'

group :development do

gem 'better_errors'

gem 'binding_of_caller'

gem 'capistrano', '~> 3.4.1'

gem 'capistrano-rails'

gem 'capistrano-bundler'

gem 'capistrano-rvm'

end

gem 'therubyracer'

gem 'less-rails'

gem 'twitter-bootstrap-rails', '3.2.0'

gem 'cancan'

gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'

gem 'rmagick'

gem 'caracal'

gem 'activerecord-session_store', github:
  'rails/activerecord-session_store'

gem 'carmen-rails', '~> 1.0.0'

gem 'wicked'

gem 'figaro'

gem 'bootstrap-datepicker-rails'

gem 'axlsx_rails'

gem 'acts_as_xlsx'

答:
I have solved the problem by adding

gem 'axlsx', '~> 2.1.0.pre'

in the gem file. This gives an error first then I had to update rubyzip. After that I run

bundle install

Body:
I am using

gem 'axlsx_rails'

gem 'acts_as_xlsx'

for downloading file into excel.
Now I am trying to add the following gem

gem 'caracal'

for downloading file into docx.
Whenever, I am trying to run

bundle install, I got the following error

Bundler could not find compatible versions for gem "rubyzip":   In
  snapshot (Gemfile.lock):
      rubyzip (= 1.0.0)

In Gemfile:
      acts_as_xlsx was resolved to 1.0.6, which depends on
        axlsx (>= 1.0.13) was resolved to 2.0.1, which depends on
          rubyzip (~> 1.0.0)

caracal was resolved to 0.1.0, which depends on
  rubyzip (~> 1.1)

Running bundle update will rebuild your snapshot from scratch, using
  only the gems in your Gemfile, which may resolve the conflict.

My gem file looks like following

source 'https://rubygems.org'

gem 'rails', '4.1.9'

gem 'mysql2', '~> 0.3.19'

gem 'sass-rails', '~> 4.0.3'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.0.0'

gem 'jquery-rails'

gem 'jbuilder', '~> 2.0'

gem 'sdoc', '~> 0.4.0',          group: :doc

gem 'spring',        group: :development

gem 'devise'

group :development do

gem 'better_errors'

gem 'binding_of_caller'

gem 'capistrano', '~> 3.4.1'

gem 'capistrano-rails'

gem 'capistrano-bundler'

gem 'capistrano-rvm'

end

gem 'therubyracer'

gem 'less-rails'

gem 'twitter-bootstrap-rails', '3.2.0'

gem 'cancan'

gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'

gem 'rmagick'

gem 'caracal'

gem 'activerecord-session_store', github:
  'rails/activerecord-session_store'

gem 'carmen-rails', '~> 1.0.0'

gem 'wicked'

gem 'figaro'

gem 'bootstrap-datepicker-rails'

gem 'axlsx_rails'

gem 'acts_as_xlsx'


问:
Which browsers support multiple keyword values for the CSS display property?
CSS3 allows specifying display-outside and display-inside values within a single display rule.

For example:

```<code>display: block flow;
display: inline table;
display: flex run-in;
</code>```

The CSS MDN page doesn't say which browsers support this multi-keyword syntax.

Which browsers currently support CSS3's multiple keyword values for display, and what quirks are present (if any) among those that do support it?

EDIT (response to close votes):

I'm not asking for a recommendation or for someone to find an outside tool/resource.

The question's intent is to help me (and others) decide whether or not to use this CSS feature in code I write, based on how well-supported it is in current target platforms (browser engines), NOT to help me choose a browser (I already have all of them -- IE, Edge, Chrome, FF, Safari, and I develop and test against the most recent versions of all of them).

Basically, I'm asking the same question this answers for flexbox, but for a different CSS feature. I.e. What would the impact on my user base be if I were to use this CSS feature? (which depends on my app’s user base, but which anyone can answer for themselves given data on browser support for hr feature in question)

There are many examples of this type of question already on SO (I can provide in comments/discussion if interested).

答:
There are no implementations of the multi-value version of display as currently defined in css-display-3.

The only features new to css-display-3 that are implemented (not including features defined in their own CSS modules, such as flex layout, grid layout and ruby layout) are display: contents and display: flow-root, but these are implemented as single keyword values, which means implementations do not currently recognize display: block flow-root despite recognizing display: flow-root.

Considering that css-display-3 is still undergoing major clarifications and even rewrites as of 2017, I wouldn't hold my breath on implementations anytime soon, especially since the current definition of display requires reimplementing the property altogether (namely, moving from single-value to multi-value while ensuring that existing values and legacy values continue to work as intended and don't break for existing sites), not to mention perhaps an overhaul of the CSS layout system depending on how it's currently being implemented, warts and all.

Body:
CSS3 allows specifying display-outside and display-inside values within a single display rule.

For example:

display: block flow;
display: inline table;
display: flex run-in;

The CSS MDN page doesn't say which browsers support this multi-keyword syntax.

Which browsers currently support CSS3's multiple keyword values for display, and what quirks are present (if any) among those that do support it?

EDIT (response to close votes):

I'm not asking for a recommendation or for someone to find an outside tool/resource.

The question's intent is to help me (and others) decide whether or not to use this CSS feature in code I write, based on how well-supported it is in current target platforms (browser engines), NOT to help me choose a browser (I already have all of them -- IE, Edge, Chrome, FF, Safari, and I develop and test against the most recent versions of all of them).

Basically, I'm asking the same question this answers for flexbox, but for a different CSS feature. I.e. What would the impact on my user base be if I were to use this CSS feature? (which depends on my app’s user base, but which anyone can answer for themselves given data on browser support for hr feature in question)

There are many examples of this type of question already on SO (I can provide in comments/discussion if interested).


问:
Getting successful result with $.ajax request but Error-500 with $http request

I am working on a small web application which simplifies the process of creating and populating USPTO IDS forms by accessing data from another server. For accessing data I am using this API - http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js.

I am doing this with angular and hence I used $http but it is throwing error 500 (Internal Server Error). while doing it with ajax-request, its working fine. In fact any other method like $.get() instead of ajax throwing the same error, even I used ng-resource get method but no help. I am not getting what I am doing wrong.

Here are my codes -

```<code>$.get( "http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js",
function( data ) {
    vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
    console.log(vm.inventors);
});

var req = {
    method: 'GET',
    url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
   };
$http(req).then(function(response){
   console.log(response);
}, function(response){
    console.log(response);
});
</code>```

Both of these codes are throwing error 500. Here is the image

while this code is working fine. But here I am getting an issue of page load, the page is loaded before data is bound to $scope and hence not showing on the page.

```<code>  $.ajax({
     url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/' + 'US9623902' + '/biblio.js',
     type: 'GET',
     dataType: "jsonP",
     success: function(data) {
         vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
         console.log(vm.inventors);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown) {
        vm.errorContent = [{
            heading: "Error",
            description: "Could not load json data "
        }];
        return false;
    }
});
</code>```

Image of successful result

Any help would be appreciated. Thank you.

答:
if you are using x-www-form-urlencoded as header, you might need to transform your request.

```<code>var req = {
  method: 'GET',
  url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },

  transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
};
</code>```

Body:
I am working on a small web application which simplifies the process of creating and populating USPTO IDS forms by accessing data from another server. For accessing data I am using this API - http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js.

I am doing this with angular and hence I used $http but it is throwing error 500 (Internal Server Error). while doing it with ajax-request, its working fine. In fact any other method like $.get() instead of ajax throwing the same error, even I used ng-resource get method but no help. I am not getting what I am doing wrong.

Here are my codes -

$.get( "http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/biblio.js",
function( data ) {
    vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
    console.log(vm.inventors);
});

var req = {
    method: 'GET',
    url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
   };
$http(req).then(function(response){
   console.log(response);
}, function(response){
    console.log(response);
});

Both of these codes are throwing error 500. Here is the image

while this code is working fine. But here I am getting an issue of page load, the page is loaded before data is bound to $scope and hence not showing on the page.

  $.ajax({
     url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/' + 'US9623902' + '/biblio.js',
     type: 'GET',
     dataType: "jsonP",
     success: function(data) {
         vm.inventors = data['ops:world-patent-data']['exchange-documents']['exchange-document']['bibliographic-data']['parties']['inventors']['inventor'];
         console.log(vm.inventors);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown) {
        vm.errorContent = [{
            heading: "Error",
            description: "Could not load json data "
        }];
        return false;
    }
});

Image of successful result

Any help would be appreciated. Thank you.

Body:
if you are using x-www-form-urlencoded as header, you might need to transform your request.

var req = {
  method: 'GET',
  url: 'http://ops.epo.org/3.1/rest-services/published-data/publication/epodoc/US9623902/full-cycle.js',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },

  transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
};


问:
Javascript: Convert Array of Arrays Into Array of Objects
I am attempting to change an array of arrays containing two value arrays into an array of two objects.

I'm fairly new to JS and I'm not sure where my code is wrong. The array being logged to the console contains the same two objects.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function transformEmployeeData(array) {
  let arrayOfObjects = [];
  let newObj = {};
  // iterates through employees
  for (let i = 0; i < array.length; i++) {
    // resets obj to empty
    newObj = {};
    // iterates through employees properties
    for (let j = 0; j < array[i].length; j++) {
      newObj[array[j][j][0]] = array[j][j][1];
    }
    // pushes object into array
    arrayOfObjects.push(newObj);
  }
  return arrayOfObjects;
}

console.log(transformEmployeeData(myArray));```

答:
when faced with an nexted array problem, it is not recommended to use arr[i][j][k]...

you can do this:

```<code>        function transformEmployeeData (array) {
            if (!Array.isArray(array) || array.length === 0) {
                return []
            }

            return array.map(item => {
                const obj = {}
                if (Array.isArray(item)) {
                    item.reduce((a, b) => {
                        if (a) {
                            obj[a[0]] = a[1]
                        }
                        obj[b[0]] = b[1]
                    })
                }
                return obj
            })
        }
</code>```

Body:
when faced with an nexted array problem, it is not recommended to use arr[i][j][k]...

you can do this:

        function transformEmployeeData (array) {
            if (!Array.isArray(array) || array.length === 0) {
                return []
            }

            return array.map(item => {
                const obj = {}
                if (Array.isArray(item)) {
                    item.reduce((a, b) => {
                        if (a) {
                            obj[a[0]] = a[1]
                        }
                        obj[b[0]] = b[1]
                    })
                }
                return obj
            })
        }


问:
Python count dictionary inside list with same value
I have dicts like this :

```<code>list_dicts = [
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A2', 'name': 'Black',
    },
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A3', 'name': 'Red',
    }
]
</code>```

And how to get dicts look like this from above dicts ?

```<code>list_dicts = [
    {
        'code': 'A1', 'name': 'White', 'qty': 2
    },
    {
        'code': 'A2', 'name': 'Black', 'qty': 1
    },
    {
        'code': 'A3', 'name': 'Red', 'qty': 1
    }
]
</code>```

..........................

答:
Assuming that you actually have a list of dicts:

```<code>list_dict = [
    {'code': 'A1', 'name': 'White'},
    {'code': 'A2', 'name': 'Black'},
    {'code': 'A1', 'name': 'White'},
    {'code': 'A3', 'name': 'Red'}
]
</code>```

Then you can use collections.Counter to count the values:

```<code>In []:
from collections import Counter
Counter((x['code'], x['name']) for x in list_dict)

Out[]:
Counter({('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1})
</code>```

It's a fairly easy exercise to turn this back into the list of dictionaries you are looking for.

Body:
I have dicts like this :

list_dicts = [
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A2', 'name': 'Black',
    },
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A3', 'name': 'Red',
    }
]

And how to get dicts look like this from above dicts ?

list_dicts = [
    {
        'code': 'A1', 'name': 'White', 'qty': 2
    },
    {
        'code': 'A2', 'name': 'Black', 'qty': 1
    },
    {
        'code': 'A3', 'name': 'Red', 'qty': 1
    }
]

..........................

Body:
Assuming that you actually have a list of dicts:

list_dict = [
    {'code': 'A1', 'name': 'White'},
    {'code': 'A2', 'name': 'Black'},
    {'code': 'A1', 'name': 'White'},
    {'code': 'A3', 'name': 'Red'}
]

Then you can use collections.Counter to count the values:

In []:
from collections import Counter
Counter((x['code'], x['name']) for x in list_dict)

Out[]:
Counter({('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1})

It's a fairly easy exercise to turn this back into the list of dictionaries you are looking for.


问:
Update progressbar from worker thread
I'm building a java program that downloads N elements from a server. I'd like to have a working progress bar, that shows "already downloaded elements"/N percentage. Right now, I update progressbar value by passing to the thread a reference to the GUI object, but it makes the code "ugly" ( GUI class creates the thread, that contains a reference to the GUI itself, creating a sort of loop).
Is there a better way to do it?</p>

答: Read the JProgressBar API and follow the link to the Swing tutorial on How to Use Progress Bars for a working example.</p>

Title: Update progressbar from worker thread


问:
eslint error Expected indentation of 1 tab character but found 0
I'm working on a project that has a eslintrc file and when I run npm run test in my Intellij project. I get an error

```<code>Expected indentation of 1 tab character but found 0
</code>```

I tried checking the box for enable ESlint search for .eslintrc
file > other settings > default settings > Languages & Frameworks > javascript > Code Quality Tools > ESLint

```<code>{
  "parser": "babel-eslint",
  "extends": [
    "airbnb",
    "plugin:import/errors",
    "plugin:import/warnings"
  ],
  "plugins": [
    "react",
    "flow-vars"
  ],
  "settings": {
    "import/ignore": [
      "node_modules",
      "\\.(html|json|properties)$",
      "DevTools"
    ],
    "import/resolver": {
      "webpack": {
        "config": "./src/js/webpack/webpack.base.config.js"
      }
    }
  },
  "rules": {
    "eqeqeq": [2, "allow-null"],
    "flow-vars/define-flow-type": 1,
    "flow-vars/use-flow-type": 1,
    "func-names": 0,
    "import/no-named-as-default": 0,
    "indent": [2, "tab", {"SwitchCase": 1}],
    "new-cap": 0,
    "no-multi-spaces": [2, {"exceptions": {"VariableDeclarator": true}}],
    "no-param-reassign": [2, {"props": false}],
    "no-script-url": 0,
    "no-unused-vars": [2, {"args": "after-used", "argsIgnorePattern": "^_"}],
    "no-use-before-define": [2, "nofunc"],
    "quote-props": [2, "consistent-as-needed"],
    "react/jsx-indent-props": [2, "tab"],
    "react/jsx-no-bind": [2, {
      "ignoreRefs": false,
      "allowArrowFunctions": false,
      "allowBind": false
    }],
    "space-before-function-paren": 0,
    "spaced-comment": 0
  },
  "globals": {
    "__ENV__": false,
    "__DEV__": false,
    "__TEST__": false
  }
}
</code>```

I even tried just changing the tab number to 2 from 4 in settings but get the error. Any help appreciated.

答:
Usually the linting error should indicate the file & line number of where it originated from.

In this case, you can try running the following command: eslint --fix & allow eslint to fix that indentation error for you.

Body:
I'm working on a project that has a eslintrc file and when I run npm run test in my Intellij project. I get an error

Expected indentation of 1 tab character but found 0

I tried checking the box for enable ESlint search for .eslintrc
file > other settings > default settings > Languages & Frameworks > javascript > Code Quality Tools > ESLint

{
  "parser": "babel-eslint",
  "extends": [
    "airbnb",
    "plugin:import/errors",
    "plugin:import/warnings"
  ],
  "plugins": [
    "react",
    "flow-vars"
  ],
  "settings": {
    "import/ignore": [
      "node_modules",
      "\\.(html|json|properties)$",
      "DevTools"
    ],
    "import/resolver": {
      "webpack": {
        "config": "./src/js/webpack/webpack.base.config.js"
      }
    }
  },
  "rules": {
    "eqeqeq": [2, "allow-null"],
    "flow-vars/define-flow-type": 1,
    "flow-vars/use-flow-type": 1,
    "func-names": 0,
    "import/no-named-as-default": 0,
    "indent": [2, "tab", {"SwitchCase": 1}],
    "new-cap": 0,
    "no-multi-spaces": [2, {"exceptions": {"VariableDeclarator": true}}],
    "no-param-reassign": [2, {"props": false}],
    "no-script-url": 0,
    "no-unused-vars": [2, {"args": "after-used", "argsIgnorePattern": "^_"}],
    "no-use-before-define": [2, "nofunc"],
    "quote-props": [2, "consistent-as-needed"],
    "react/jsx-indent-props": [2, "tab"],
    "react/jsx-no-bind": [2, {
      "ignoreRefs": false,
      "allowArrowFunctions": false,
      "allowBind": false
    }],
    "space-before-function-paren": 0,
    "spaced-comment": 0
  },
  "globals": {
    "__ENV__": false,
    "__DEV__": false,
    "__TEST__": false
  }
}

I even tried just changing the tab number to 2 from 4 in settings but get the error. Any help appreciated.


问:
Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources
I'm trying to set up my Nexus 7 (2013) for debugging, but I am getting stuck at the step where you install the USB driver.  Here's what I've tried so far:

Steps taken:

Turned on debugging mode on Nexus 7 (2013)

Connected device to PC

Downloaded Google USB Driver at http://developer.android.com/sdk/win-usb.html (and unpacked it)

Opened Computer Management and tried to update drivers on Nexus 7 device

Directed the driver update wizard to the unpacked usb_driver folder with Include Subfolders checked (not the zip file nor the amd64 and i386 folders inside), but I get the message: "Windows could not find driver software for your device."

Installed Google USB Driver with Android SDK Manager

Used update driver wizard with path to usb_driver folder from SDK manager, same result.

Tried using "Let me pick from a list of device drivers" option on update driver wizard.

Picked "Android USB Devices", then clicked "Have Disk" button

Pointed to android_winusb.inf inside usb_driver folder, got message: "The folder you specified doesn't contain a compatible software driver for your device. If the folder contains a driver, make sure it is designed to work with Windows for x64-based systems."

I'm pretty much at my wit's end (I usually try to find answers myself or from other posts online, but this one's got me stumped pretty hard.)  Can anyone help?

答:
Depending on the device, sometimes you are getting "The folder you specified doesn't contain a compatible software" error because the first interface isn't actually the ADB interface.

Try installing it as a generic "USB composite device" instead (from the 'pick from a list' driver install option); once the standard composite driver installs it will allow Windows to communicate with the device and detect the associated ADB driver interface and install it properly.


问:
ORA-00904: "T": invalid identifier Apex Error
I try this query in SQLDeveloper and works regular

```<code>   select (CASE when :Y1 = '1' then ah.kategorija_sifra when :Y1 = '2' then ah.robnagrupa_sifra when :Y1 = '3' then ah.model
when :Y1 = '6' then ah.grana when :Y1 = '7' then ah.priroda_proizvoda_sifra when :Y1 = '8' then ah.grana_proizvoda_sifra
when :Y1 = '9' then aa.nadgrupa_a when :Y1 = '10' then aa.rgrupa_a when :Y1 = '11' then aa.model_a when :Y1 = '12' then aa.osnovna_sifra end) as grupisanje
, (case when :AY1 = '1' then s.boja_osnovna  when :AY1 = '2' then s.materijal_osnovni when :AY1 = '3' then s.boja_metala  when :AY1 = '4' then s.sezona when :AY1 = '5' then s.kolekcija when :AY1 = '6' then s.nijansa_osn_boje when :AY1 = '7' then s.specificnosti_osn_materjala   when :AY1 = '8' then s.specificnosti_osn_materjala_t when :AY1 = '9' then s.godina_proizvodnje  when :AY1 = '10' then s.nijansa_boje4  end  ) as atribu1
, (case when :AY2 = '1' then s.boja_osnovna  when :AY2 = '2' then s.materijal_osnovni when :AY2 = '3' then s.boja_metala  when :AY2 = '4' then s.sezona when :AY2 = '5' then s.kolekcija when :AY2 = '6' then s.nijansa_osn_boje when :AY2 = '7' then s.specificnosti_osn_materjala   when :AY2 = '8' then s.specificnosti_osn_materjala_t when :AY2 = '9' then s.godina_proizvodnje  when :AY2 = '10' then s.nijansa_boje4  end  ) as atribu2
, (case when :AY3 = '1' then s.boja_osnovna  when :AY3 = '2' then s.materijal_osnovni when :AY3 = '3' then s.boja_metala  when :AY3 = '4' then s.sezona when :AY3 = '5' then s.kolekcija when :AY3 = '6' then s.nijansa_osn_boje when :AY3 = '7' then s.specificnosti_osn_materjala   when :AY3 = '8' then s.specificnosti_osn_materjala_t when :AY3 = '9' then s.godina_proizvodnje  when :AY3 = '10' then s.nijansa_boje4  end  ) as atribu3
, nvl(sum(p.ks_vlp),0) as ks_vlp, nvl(sum(p.ks_mlp),0) as ks_mlp
, nvl(sum(p3s.proiz),0), nvl(sum(p3s.prod_vp),0), nvl(sum(p3s.ost_vp),0), nvl(sum(p3s.kol_vp),0), nvl(sum(p3s.ps_v),0), nvl(sum(p3s.proiz_v),0), nvl(sum(p3s.prod_vp_v),0), nvl(sum(p3s.ost_vp_v),0), nvl(sum(p3s.popust_vp),0), nvl(sum(p3s.poslato),0)
, nvl(sum(p3s.primljeno),0), nvl(sum(p3s.prod_mp),0), nvl(sum(p3s.ost_mp),0), nvl(sum(p3s.kol_mp),0)
from

(select sifra, velicina,nvl(sum(vlp),0)+nvl(sum(put_vlp),0) as ks_vlp , nvl(sum(mlp),0)+nvl(sum(put_mlp),0) as ks_mlp
from mona_internal.zal_3b_savke
where datum between to_date('01'||substr(:P405,4,8),'dd.mm.yyyy') and :P405
group by sifra, velicina) p

------------------------------------------------------------ Krajnja stanja -------------------------------------------

left join mona_internal.artikli_hijerarhija ah
on p.sifra=ah.artikal_sifra

---------------------------------------------------------- Artikli hijerarhija -----------------------------------------

left join dwh.bck_svojstva s
on s.artikal_sifra= ah.artikal_sifra

---------------------------------------------------------- Svojstva  -----------------------------------------

left join mona_internal.artikli_analiza aa
on aa.sifra=ah.artikal_sifra

---------------------------------------------------------- Artikli analiza -----------------------------------------

left join (
select datum, sifra, velicina
, nvl(sum(proiz),0) proiz, nvl(sum(prod_vp),0) prod_vp, nvl(sum(ost_vp),0) ost_vp, nvl(sum(kol_vp),0) kol_vp, nvl(sum(ps_v),0) ps_v
, nvl(sum(proiz_v),0) proiz_v, nvl(sum(prod_vp_v),0) prod_vp_v, nvl(sum(ost_vp_v),0) ost_vp_v, nvl(sum(popust_vp),0) popust_vp, nvl(sum(poslato),0) as poslato         /* --vlp iz 3bsira*/
, nvl(sum(primljeno),0) primljeno, nvl(sum(prod_mp),0) prod_mp, nvl(sum(ost_mp),0) ost_mp, nvl(sum(kol_mp),0) as kol_mp                                          /* --mlp  iz 3bsira*/
from mona_internal.PROMET_3B_SIRA
where datum between :P305 and :P405
group by datum, sifra, velicina) p3s
on p3s.sifra=ah.artikal_sifra

left join (
select sifra, velicina, sum(vlp)+sum(put_vlp) as vlp, sum(mlp)+sum(put_mlp) as mlp from mona_internal.zal_3b_savke
where (datum between to_date('01'||substr(:P305,4,8),'dd.mm.yyyy')
and case when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') = :P305 then  to_date(:P305, 'dd.mm.yyyy')  when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') != :P305 then to_date(:P305, 'dd.mm.yyyy') - 1 end )
and  jeps like (case when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') = :P305 then  'D' else  '%'  end)
group by sifra, velicina) ps
on ps.sifra=ah.artikal_sifra

---------------------------------------------------------- Pocetna stanja   -----------------------------------------

group by
 (CASE when :Y1 = '1' then ah.kategorija_sifra when :Y1 = '2' then ah.robnagrupa_sifra when :Y1 = '3' then ah.model
when :Y1 = '6' then ah.grana when :Y1 = '7' then ah.priroda_proizvoda_sifra when :Y1 = '8' then ah.grana_proizvoda_sifra
when :Y1 = '9' then aa.nadgrupa_a when :Y1 = '10' then aa.rgrupa_a when :Y1 = '11' then aa.model_a when :Y1 = '12' then aa.osnovna_sifra end)
, (case when :AY1 = '1' then s.boja_osnovna  when :AY1 = '2' then s.materijal_osnovni when :AY1 = '3' then s.boja_metala  when :AY1 = '4' then s.sezona when :AY1 = '5' then s.kolekcija when :AY1 = '6' then s.nijansa_osn_boje when :AY1 = '7' then s.specificnosti_osn_materjala   when :AY1 = '8' then s.specificnosti_osn_materjala_t when :AY1 = '9' then s.godina_proizvodnje  when :AY1 = '10' then s.nijansa_boje4  end  )
, (case when :AY2 = '1' then s.boja_osnovna  when :AY2 = '2' then s.materijal_osnovni when :AY2 = '3' then s.boja_metala  when :AY2 = '4' then s.sezona when :AY2 = '5' then s.kolekcija when :AY2 = '6' then s.nijansa_osn_boje when :AY2 = '7' then s.specificnosti_osn_materjala   when :AY2 = '8' then s.specificnosti_osn_materjala_t when :AY2 = '9' then s.godina_proizvodnje  when :AY2 = '10' then s.nijansa_boje4  end  )
, (case when :AY3 = '1' then s.boja_osnovna  when :AY3 = '2' then s.materijal_osnovni when :AY3 = '3' then s.boja_metala  when :AY3 = '4' then s.sezona when :AY3 = '5' then s.kolekcija when :AY3 = '6' then s.nijansa_osn_boje when :AY3 = '7' then s.specificnosti_osn_materjala   when :AY3 = '8' then s.specificnosti_osn_materjala_t when :AY3 = '9' then s.godina_proizvodnje  when :AY3 = '10' then s.nijansa_boje4  end  ) ;
</code>```

But when the same query input in APEX, it return to me:
 ORA-00904: "T": invalid identifier

I found many cases on google, but none with this problem. Strange is, that works in Developer, but not works in APEX.

Any idea?

P.S.

1.) Parameters P305 and P405 are in APEX items-date picker

2.) Parameter Y1 is LOV and has values
 (STATIC:Nadgrupa;1,RGrupa;2,Model;3,Grana;6,prir_proiz_sif;7,grana_proiz_sif;8,
  nadgrupa_a;9,rgrupa_a;10,model_a;11,osn_sifra_a;12)

3.) Parameters AY1, AY2, AY3 are also LOV and have same values
 (STATIC:boja_osnovna;1,materijal_osnovni;2,boja_metala;3,sezona;4,kolekcija;5,n
 ijansa_osn_boje;6,specificnosti_osn_materjala;7,T_specificnosti_osn_materijala;
 8,godina_proizvodnje;9,godina_sezone;10)

答: Try reduce the 'T_specificnosti_osn_materijala' by one or two chars.. </p>

Body:
I try this query in SQLDeveloper and works regular

   select (CASE when :Y1 = '1' then ah.kategorija_sifra when :Y1 = '2' then ah.robnagrupa_sifra when :Y1 = '3' then ah.model
when :Y1 = '6' then ah.grana when :Y1 = '7' then ah.priroda_proizvoda_sifra when :Y1 = '8' then ah.grana_proizvoda_sifra
when :Y1 = '9' then aa.nadgrupa_a when :Y1 = '10' then aa.rgrupa_a when :Y1 = '11' then aa.model_a when :Y1 = '12' then aa.osnovna_sifra end) as grupisanje
, (case when :AY1 = '1' then s.boja_osnovna  when :AY1 = '2' then s.materijal_osnovni when :AY1 = '3' then s.boja_metala  when :AY1 = '4' then s.sezona when :AY1 = '5' then s.kolekcija when :AY1 = '6' then s.nijansa_osn_boje when :AY1 = '7' then s.specificnosti_osn_materjala   when :AY1 = '8' then s.specificnosti_osn_materjala_t when :AY1 = '9' then s.godina_proizvodnje  when :AY1 = '10' then s.nijansa_boje4  end  ) as atribu1
, (case when :AY2 = '1' then s.boja_osnovna  when :AY2 = '2' then s.materijal_osnovni when :AY2 = '3' then s.boja_metala  when :AY2 = '4' then s.sezona when :AY2 = '5' then s.kolekcija when :AY2 = '6' then s.nijansa_osn_boje when :AY2 = '7' then s.specificnosti_osn_materjala   when :AY2 = '8' then s.specificnosti_osn_materjala_t when :AY2 = '9' then s.godina_proizvodnje  when :AY2 = '10' then s.nijansa_boje4  end  ) as atribu2
, (case when :AY3 = '1' then s.boja_osnovna  when :AY3 = '2' then s.materijal_osnovni when :AY3 = '3' then s.boja_metala  when :AY3 = '4' then s.sezona when :AY3 = '5' then s.kolekcija when :AY3 = '6' then s.nijansa_osn_boje when :AY3 = '7' then s.specificnosti_osn_materjala   when :AY3 = '8' then s.specificnosti_osn_materjala_t when :AY3 = '9' then s.godina_proizvodnje  when :AY3 = '10' then s.nijansa_boje4  end  ) as atribu3
, nvl(sum(p.ks_vlp),0) as ks_vlp, nvl(sum(p.ks_mlp),0) as ks_mlp
, nvl(sum(p3s.proiz),0), nvl(sum(p3s.prod_vp),0), nvl(sum(p3s.ost_vp),0), nvl(sum(p3s.kol_vp),0), nvl(sum(p3s.ps_v),0), nvl(sum(p3s.proiz_v),0), nvl(sum(p3s.prod_vp_v),0), nvl(sum(p3s.ost_vp_v),0), nvl(sum(p3s.popust_vp),0), nvl(sum(p3s.poslato),0)
, nvl(sum(p3s.primljeno),0), nvl(sum(p3s.prod_mp),0), nvl(sum(p3s.ost_mp),0), nvl(sum(p3s.kol_mp),0)
from

(select sifra, velicina,nvl(sum(vlp),0)+nvl(sum(put_vlp),0) as ks_vlp , nvl(sum(mlp),0)+nvl(sum(put_mlp),0) as ks_mlp
from mona_internal.zal_3b_savke
where datum between to_date('01'||substr(:P405,4,8),'dd.mm.yyyy') and :P405
group by sifra, velicina) p

------------------------------------------------------------ Krajnja stanja -------------------------------------------

left join mona_internal.artikli_hijerarhija ah
on p.sifra=ah.artikal_sifra

---------------------------------------------------------- Artikli hijerarhija -----------------------------------------

left join dwh.bck_svojstva s
on s.artikal_sifra= ah.artikal_sifra

---------------------------------------------------------- Svojstva  -----------------------------------------

left join mona_internal.artikli_analiza aa
on aa.sifra=ah.artikal_sifra

---------------------------------------------------------- Artikli analiza -----------------------------------------

left join (
select datum, sifra, velicina
, nvl(sum(proiz),0) proiz, nvl(sum(prod_vp),0) prod_vp, nvl(sum(ost_vp),0) ost_vp, nvl(sum(kol_vp),0) kol_vp, nvl(sum(ps_v),0) ps_v
, nvl(sum(proiz_v),0) proiz_v, nvl(sum(prod_vp_v),0) prod_vp_v, nvl(sum(ost_vp_v),0) ost_vp_v, nvl(sum(popust_vp),0) popust_vp, nvl(sum(poslato),0) as poslato         /* --vlp iz 3bsira*/
, nvl(sum(primljeno),0) primljeno, nvl(sum(prod_mp),0) prod_mp, nvl(sum(ost_mp),0) ost_mp, nvl(sum(kol_mp),0) as kol_mp                                          /* --mlp  iz 3bsira*/
from mona_internal.PROMET_3B_SIRA
where datum between :P305 and :P405
group by datum, sifra, velicina) p3s
on p3s.sifra=ah.artikal_sifra

left join (
select sifra, velicina, sum(vlp)+sum(put_vlp) as vlp, sum(mlp)+sum(put_mlp) as mlp from mona_internal.zal_3b_savke
where (datum between to_date('01'||substr(:P305,4,8),'dd.mm.yyyy')
and case when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') = :P305 then  to_date(:P305, 'dd.mm.yyyy')  when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') != :P305 then to_date(:P305, 'dd.mm.yyyy') - 1 end )
and  jeps like (case when to_date('01'||substr(:P305,4,8),'dd.mm.yyyy') = :P305 then  'D' else  '%'  end)
group by sifra, velicina) ps
on ps.sifra=ah.artikal_sifra

---------------------------------------------------------- Pocetna stanja   -----------------------------------------

group by
 (CASE when :Y1 = '1' then ah.kategorija_sifra when :Y1 = '2' then ah.robnagrupa_sifra when :Y1 = '3' then ah.model
when :Y1 = '6' then ah.grana when :Y1 = '7' then ah.priroda_proizvoda_sifra when :Y1 = '8' then ah.grana_proizvoda_sifra
when :Y1 = '9' then aa.nadgrupa_a when :Y1 = '10' then aa.rgrupa_a when :Y1 = '11' then aa.model_a when :Y1 = '12' then aa.osnovna_sifra end)
, (case when :AY1 = '1' then s.boja_osnovna  when :AY1 = '2' then s.materijal_osnovni when :AY1 = '3' then s.boja_metala  when :AY1 = '4' then s.sezona when :AY1 = '5' then s.kolekcija when :AY1 = '6' then s.nijansa_osn_boje when :AY1 = '7' then s.specificnosti_osn_materjala   when :AY1 = '8' then s.specificnosti_osn_materjala_t when :AY1 = '9' then s.godina_proizvodnje  when :AY1 = '10' then s.nijansa_boje4  end  )
, (case when :AY2 = '1' then s.boja_osnovna  when :AY2 = '2' then s.materijal_osnovni when :AY2 = '3' then s.boja_metala  when :AY2 = '4' then s.sezona when :AY2 = '5' then s.kolekcija when :AY2 = '6' then s.nijansa_osn_boje when :AY2 = '7' then s.specificnosti_osn_materjala   when :AY2 = '8' then s.specificnosti_osn_materjala_t when :AY2 = '9' then s.godina_proizvodnje  when :AY2 = '10' then s.nijansa_boje4  end  )
, (case when :AY3 = '1' then s.boja_osnovna  when :AY3 = '2' then s.materijal_osnovni when :AY3 = '3' then s.boja_metala  when :AY3 = '4' then s.sezona when :AY3 = '5' then s.kolekcija when :AY3 = '6' then s.nijansa_osn_boje when :AY3 = '7' then s.specificnosti_osn_materjala   when :AY3 = '8' then s.specificnosti_osn_materjala_t when :AY3 = '9' then s.godina_proizvodnje  when :AY3 = '10' then s.nijansa_boje4  end  ) ;

But when the same query input in APEX, it return to me:
 ORA-00904: "T": invalid identifier

I found many cases on google, but none with this problem. Strange is, that works in Developer, but not works in APEX.

Any idea?

P.S.

1.) Parameters P305 and P405 are in APEX items-date picker

2.) Parameter Y1 is LOV and has values
 (STATIC:Nadgrupa;1,RGrupa;2,Model;3,Grana;6,prir_proiz_sif;7,grana_proiz_sif;8,
  nadgrupa_a;9,rgrupa_a;10,model_a;11,osn_sifra_a;12)

3.) Parameters AY1, AY2, AY3 are also LOV and have same values
 (STATIC:boja_osnovna;1,materijal_osnovni;2,boja_metala;3,sezona;4,kolekcija;5,n
 ijansa_osn_boje;6,specificnosti_osn_materjala;7,T_specificnosti_osn_materijala;
 8,godina_proizvodnje;9,godina_sezone;10)


问:
Where does PostgreSQL store the database?
Where are the files for a PostgreSQL database stored?</p>

答:
Everyone already answered but just for the latest updates. If you want to know where all the configuration files reside then run this command in the shell</p>

```<code>SELECT name, setting FROM pg_settings WHERE category = 'File Locations';
</code>```

Body:
Everyone already answered but just for the latest updates. If you want to know where all the configuration files reside then run this command in the shell

SELECT name, setting FROM pg_settings WHERE category = 'File Locations';


问:
Python not allowing variables in input
In Python 3.6 when entering the code

```<code>var = 1
var1 = input("Hey var = ",(var),"Bye : ")
</code>```

for some reason it comes out with an error message

```<code>    var1 = input("Hey var = ",(var),"Bye : ")
TypeError: input expected at most 1 arguments got 1/2/3/4/5/6+
</code>```

Does anyone know how to fix this so it runs like:

```<code>Hey var = 1 Bye : (where you enter text)
</code>```

答:
Sorry, I might not answer your question fully but you can't have more than one argument in input().

```<code>var = 1
var1 = input("Enter something:")
print(f"Hey {var} Bye : {var1}")
</code>```

Title: Python not allowing variables in input

Body:
In Python 3.6 when entering the code

var = 1
var1 = input("Hey var = ",(var),"Bye : ")

for some reason it comes out with an error message

    var1 = input("Hey var = ",(var),"Bye : ")
TypeError: input expected at most 1 arguments got 1/2/3/4/5/6+

Does anyone know how to fix this so it runs like:

Hey var = 1 Bye : (where you enter text)

Body:
Sorry, I might not answer your question fully but you can't have more than one argument in input().

var = 1
var1 = input("Enter something:")
print(f"Hey {var} Bye : {var1}")


问:
Differences in Differentiation Implementations in MATLAB
I'm trying to find the (numerical) curvature at specific points. I have data stored in an array, and I essentially want to find the local curvature at every separate point. I've searched around, and found three different implementations for this in MATLAB: diff, gradient, and del2.

If my array's name is arr I have tried the following implementations:

```<code>curvature = diff(diff(arr));
curvature = diff(arr,2);
curvature = gradient(gradient(arr));
curvature = del2(arr);
</code>```

The first two seem to output the same values. This makes sense, because they're essentially the same implementation. However, the gradient and del2 implementations give different values from each other and from diff.

I can't figure out from the documentation precisely how the implementations work. My guess is that some of them are some type of two-sided derivative, and some of them are not two-sided derivatives. Another thing that confuses me is that my current implementations use only the data from arr. arr is my y-axis data, the x-axis essentially being time. Do these functions default to a stepsize of 1 or something like that?

If it helps, I want an implementation that takes the curvature at the current point using only previous array elements. For context, my data is such that a curvature calculation based on data in the future of the current point wouldn't be useful for my purposes.

tl;dr I need a rigorous curvature at a point implementation that uses only data to the left of the point.

Edit: I kind of better understand what's going on based on this, thanks to the answers below. This is what I'm referring to:

gradient calculates the central difference for interior data points.
  For example, consider a matrix with unit-spaced data, A, that has
  horizontal gradient G = gradient(A). The interior gradient values,
  G(:,j), are

G(:,j) = 0.5*(A(:,j+1) - A(:,j-1)); The subscript j varies between 2
  and N-1, with N = size(A,2).

Even so, I still want to know how to do a "lefthand" computation.

答:
diff is simply the difference between two adjacent elements in arr, which is exactly why you lose 1 element for using diff once. For example, 10 elements in an array only have 9 differences.

gradient and del2 are for derivatives. Of course, you can use diff to approximate derivative by dividing the difference by the steps. Usually the step is equally-spaced, but it does not have to be. This answers your question why x is not used in the calculation. I mean, it's okay that your x is not uniform-spaced.

So, why gradient gives us an array with the same length of the original array? It is clearly explained in the manual how the boundary is handled,

The gradient values along the edges of the matrix are calculated with single->sided differences, so that

G(:,1) = A(:,2) - A(:,1);

G(:,N) = A(:,N) - A(:,N-1);

Double-gradient and del2 are not necessarily the same, although they are highly correlated. It's all because how you calculate/approximate the 2nd-oder derivatives. The difference is, the former approximates the 2nd derivative by doing 1st derivative twice and the latter directly approximates the 2nd derivative. Please refer to the help manual, the formula are documented.

Okay, do you really want curvature or the 2nd derivative for each point on arr? They are very different. https://en.wikipedia.org/wiki/Curvature#Precise_definition

You can use diff to get the 2nd derivative from the left. Since diff takes the difference from right to left, e.g. x(2)-x(1), you can first flip x from left to right, then use diff. Some codes like,

```<code>x=fliplr(x)
first=x./h
second=diff(first)./h
</code>```

where h is the space between x. Notice I use ./, which idicates that h can be an array (i.e. non-uniform spaced).

Body:
I'm trying to find the (numerical) curvature at specific points. I have data stored in an array, and I essentially want to find the local curvature at every separate point. I've searched around, and found three different implementations for this in MATLAB: diff, gradient, and del2.

If my array's name is arr I have tried the following implementations:

curvature = diff(diff(arr));
curvature = diff(arr,2);
curvature = gradient(gradient(arr));
curvature = del2(arr);

The first two seem to output the same values. This makes sense, because they're essentially the same implementation. However, the gradient and del2 implementations give different values from each other and from diff.

I can't figure out from the documentation precisely how the implementations work. My guess is that some of them are some type of two-sided derivative, and some of them are not two-sided derivatives. Another thing that confuses me is that my current implementations use only the data from arr. arr is my y-axis data, the x-axis essentially being time. Do these functions default to a stepsize of 1 or something like that?

If it helps, I want an implementation that takes the curvature at the current point using only previous array elements. For context, my data is such that a curvature calculation based on data in the future of the current point wouldn't be useful for my purposes.

tl;dr I need a rigorous curvature at a point implementation that uses only data to the left of the point.

Edit: I kind of better understand what's going on based on this, thanks to the answers below. This is what I'm referring to:

gradient calculates the central difference for interior data points.
  For example, consider a matrix with unit-spaced data, A, that has
  horizontal gradient G = gradient(A). The interior gradient values,
  G(:,j), are

G(:,j) = 0.5*(A(:,j+1) - A(:,j-1)); The subscript j varies between 2
  and N-1, with N = size(A,2).

Even so, I still want to know how to do a "lefthand" computation.

Body:
diff is simply the difference between two adjacent elements in arr, which is exactly why you lose 1 element for using diff once. For example, 10 elements in an array only have 9 differences.

gradient and del2 are for derivatives. Of course, you can use diff to approximate derivative by dividing the difference by the steps. Usually the step is equally-spaced, but it does not have to be. This answers your question why x is not used in the calculation. I mean, it's okay that your x is not uniform-spaced.

So, why gradient gives us an array with the same length of the original array? It is clearly explained in the manual how the boundary is handled,

The gradient values along the edges of the matrix are calculated with single->sided differences, so that

G(:,1) = A(:,2) - A(:,1);

G(:,N) = A(:,N) - A(:,N-1);

Double-gradient and del2 are not necessarily the same, although they are highly correlated. It's all because how you calculate/approximate the 2nd-oder derivatives. The difference is, the former approximates the 2nd derivative by doing 1st derivative twice and the latter directly approximates the 2nd derivative. Please refer to the help manual, the formula are documented.

Okay, do you really want curvature or the 2nd derivative for each point on arr? They are very different. https://en.wikipedia.org/wiki/Curvature#Precise_definition

You can use diff to get the 2nd derivative from the left. Since diff takes the difference from right to left, e.g. x(2)-x(1), you can first flip x from left to right, then use diff. Some codes like,

x=fliplr(x)
first=x./h
second=diff(first)./h

where h is the space between x. Notice I use ./, which idicates that h can be an array (i.e. non-uniform spaced).


问:
Searching array for multiple value
I've got an array containing

```<code>"1", "2", "3", "4"
</code>```

And I use array_rand to select one of those numbers randomly five times. Then I want to count how many of the result of array_rand that have been chosen multiple times like the number 2 got chosen 2 times and number 3 got chosen 2 times.

I have tested doing this

```<code>$array = array($kort1[$rand_kort1[0]], $kort1[$rand_kort2[0]], $kort1[$rand_kort3[0]], $kort1[$rand_kort4[0]], $kort1[$rand_kort5[0]]);
$bank = array_count_values($array);
if (in_array("2", $bank)) {
    echo "You got one pair";
} elseif(in_array("2", $bank) && (???)) {
    echo "You got two pair";
}
</code>```

it will tell me "You got one pair" if one of those numbers were randomly chosen 2 times but my problem is I don't know how to make it say "You got two pairs" if 2 of those numbers were chosen 2 times.
the result of $bank could be

```<code> [4] => 1 [3] => 2 [1] => 2
</code>```

答:
You can use array_filter to appy a function to each element of your array

```<code>$bank=array(4 => 1, 3 => 2, 1 => 2); // Your array
function pairs($var) {
    return($var === 2); // returns value if the input integer equals 2
}
$pairs=count(array_filter($bank, "pairs")); // Apply the function to all elements of the array and get the number of times 2 was found
if ($pairs === 1)
{
echo "you got one pair";
}
if ($pairs === 2) {
echo "you got two pairs";
}
</code>```

EDIT

Thought of this one liner later:

```<code>$pairs=count(array_diff($bank, array(1,3,4)));
</code>```

Title: Searching array for multiple value

Body:
I've got an array containing

"1", "2", "3", "4"

And I use array_rand to select one of those numbers randomly five times. Then I want to count how many of the result of array_rand that have been chosen multiple times like the number 2 got chosen 2 times and number 3 got chosen 2 times.

I have tested doing this

$array = array($kort1[$rand_kort1[0]], $kort1[$rand_kort2[0]], $kort1[$rand_kort3[0]], $kort1[$rand_kort4[0]], $kort1[$rand_kort5[0]]);
$bank = array_count_values($array);
if (in_array("2", $bank)) {
    echo "You got one pair";
} elseif(in_array("2", $bank) && (???)) {
    echo "You got two pair";
}

it will tell me "You got one pair" if one of those numbers were randomly chosen 2 times but my problem is I don't know how to make it say "You got two pairs" if 2 of those numbers were chosen 2 times.
the result of $bank could be

 [4] => 1 [3] => 2 [1] => 2

Body:
You can use array_filter to appy a function to each element of your array

$bank=array(4 => 1, 3 => 2, 1 => 2); // Your array
function pairs($var) {
    return($var === 2); // returns value if the input integer equals 2
}
$pairs=count(array_filter($bank, "pairs")); // Apply the function to all elements of the array and get the number of times 2 was found
if ($pairs === 1)
{
echo "you got one pair";
}
if ($pairs === 2) {
echo "you got two pairs";
}

EDIT

Thought of this one liner later:

$pairs=count(array_diff($bank, array(1,3,4)));


问:
Search and get all child nodes of XML node base on attribute id
I have a sample XML like this:

```<code><doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>
</code>```

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

```<code> XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;
</code>```

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

答:
you can use below code to get information in first tag.

```<code>var first = doc.Root.Elements("customer").Elements("first").Elements();
</code>```

Body:
I have a sample XML like this:

<doc>
    <customer id="1">
      <first>
        <fullname>John Doe 1</fullname>
        <contact>011-1111111</contact>
        <title>Lorem</title>
      </first>
      <second>
        <fullname>John Doe 2</fullname>
        <contact>012-2222222</contact>
        <title>Lorem</title>
      </second>
    </customer>
</doc>

My question is how can I get all the child node inside first and second based on the customer id. So far this is what i have tried but i have no idea how to continue it.

 XDocument doc = XDocument.Load("sampleXML.xml");
 var controls = from str in doc.Elements("customer")
                           where str.Attribute("id").Value == 1
                           select str;

If I am able to get the data, how can i display the result? By using foreach loop? Sorry if this is a stupid question, but I am quite new to c# and linq.

Body:
you can use below code to get information in first tag.

var first = doc.Root.Elements("customer").Elements("first").Elements();


问:
Scipy kd-tree with auxiliary identifier assigned to each point
I am attempting to build a kd-tree with 3D coordinates that have arbitrary integers assigned to them. For example a tuple ([34534.65424, 10957.00023, -79.154323], 32).

However, I cant find out how to use scipy.spatial.cKDTree() with anything but a numpy array.

The identifier could even be a fourth field in the numpy array but the tree would have to be build based on the first three coordinates only.
Can somebody shed some light on this?
The purpose is to reference the kd-tree nodes back to a segment it belongs to for later comparisons.

Thank you!

Body:
Since the tree structure and also answers to queries are given in terms of indices, not values, you can simply keep your labels in a separate array with the same order.

Demo:

a = np.random.rand(100, 3)
t = cKDTree(a)
t.tree.indices
# array([13, 12, 18, 19, 20, 47, 54, 55, 83, 88, 82, 40, 31, 10, 45, 22, 15,
#        95, 76, 46, 94, 62,  5, 84, 74, 63, 80, 81, 59,  9, 34, 29, 71, 61,
#        73,  4, 85,  0, 16, 39, 35, 26, 53, 69, 77,  6, 36, 97, 57, 78, 90,
#        32, 38, 68, 65, 96,  3, 24, 66, 11, 86, 89, 91, 30, 67, 42, 28, 33,
#         7, 44,  8, 17, 60, 56, 41, 43, 92, 51, 58,  2, 93, 21, 14, 64, 70,
#        87, 72, 50, 25, 49, 98, 37, 99, 52,  1, 48, 75, 79, 23, 27])

t.query_pairs(0.1)
# {(20, 55), (48, 98), (6, 35), (38, 89), (98, 99), (26, 39), (45, 84), (26, 53), (37, 48), (48, 99), (15, 46), (36, 97), (14, 87), (42, 56), (37, 99), (5, 94), (71, 73), (0, 85), (70, 72), (22, 74), (37, 98)}


问:
C++ Pointers to arrays
```<code>#include <stdio.h>

char strA[80] = "A string to be used for demonstration purposes";
char strB[80];

char *my_strcpy(char *destination, char *source)
{
   char *p = destination;
   while (*source != '\0')
   {
       *p++ = *source++;
   }
   *p = '\0';
   return destination;
}
int main(void)
{
    my_strcpy(strB, strA);
    puts(strB);
 }
</code>```

so my question here is that when i take out the portion:
    //*p= '\0';

it prints the exact same answer, so why is this necessary? from my understanding, \0 is a nul portion of memory after a string but since the array strA already contains the nul portion since its in "" is it really necessary?

答:
Your loop stops when it sees the \0 and so it is not copied to the destination and the destination is not NUL terminated. Is that a problem?

Not if your destination buffer is initialized to all 0s

Not if your code is willing to deal with fixed length strings (so the my_strcpy signature would need to change to return the length)

In general YES - the 0 terminated C string is such a common thing that not following the convention is asking for trouble,

Whether you 0 terminate or not the rest of the values will be the same as they were when you started. The 0 termination just makes your character array a "standard C string".

For arguments sake: Assuming you knew every string had space for 80 chars you could just do

```<code>for(int i = 0; i < 80; i++)
{
    dest[i] = src[i];
}
</code>```

The effect is the same and assuming the source is 0 terminated the destination will be too.

Title: C++ Pointers to arrays

Body:
#include <stdio.h>

char strA[80] = "A string to be used for demonstration purposes";
char strB[80];

char *my_strcpy(char *destination, char *source)
{
   char *p = destination;
   while (*source != '\0')
   {
       *p++ = *source++;
   }
   *p = '\0';
   return destination;
}
int main(void)
{
    my_strcpy(strB, strA);
    puts(strB);
 }

so my question here is that when i take out the portion:
    //*p= '\0';

it prints the exact same answer, so why is this necessary? from my understanding, \0 is a nul portion of memory after a string but since the array strA already contains the nul portion since its in "" is it really necessary?

Body:
Your loop stops when it sees the \0 and so it is not copied to the destination and the destination is not NUL terminated. Is that a problem?

Not if your destination buffer is initialized to all 0s

Not if your code is willing to deal with fixed length strings (so the my_strcpy signature would need to change to return the length)

In general YES - the 0 terminated C string is such a common thing that not following the convention is asking for trouble,

Whether you 0 terminate or not the rest of the values will be the same as they were when you started. The 0 termination just makes your character array a "standard C string".

For arguments sake: Assuming you knew every string had space for 80 chars you could just do

for(int i = 0; i < 80; i++)
{
    dest[i] = src[i];
}

The effect is the same and assuming the source is 0 terminated the destination will be too.


问:
Implementing this with CSS and HTMl
This is my css -

```<code>#nav {
    position: relative;
    background-color: #292929;
    float: left;
    width:960px;
    margin-left:auto;
    margin-right:auto;

}
#nav li {
    float: left;
    list-style: none;

    width:auto;

}
#nav li a {
    color: #e3e3e3;
    position: relative;
    z-index: 2;
    float: left;

}
ul, li {
  margin:0;
    padding: 0;

}

#blob {

    position: absolute;
    top: 0;
    z-index : 1;
    background: #0b2b61;

    background-repeat:repeat;

}
</code>```

I want to place this object in the center. How do i do that. I also want the background to fit the page. I tried a lot, but it isn't working.

```<code><ul id="nav">
        <li><a href="home.php">Home</a></li>
</ul>
</code>```

答:
You want place
 int the center, right?

The easiest way according to your current markup is to apply fixed width and add margin: 0 auto; to your li.

Semantics of that solution is really bad, but i guess you don't really care.

Title: Implementing this with CSS and HTMl

Body:
This is my css -

#nav {
    position: relative;
    background-color: #292929;
    float: left;
    width:960px;
    margin-left:auto;
    margin-right:auto;

}
#nav li {
    float: left;
    list-style: none;

    width:auto;

}
#nav li a {
    color: #e3e3e3;
    position: relative;
    z-index: 2;
    float: left;

}
ul, li {
  margin:0;
    padding: 0;

}

#blob {

    position: absolute;
    top: 0;
    z-index : 1;
    background: #0b2b61;

    background-repeat:repeat;

}

I want to place this object in the center. How do i do that. I also want the background to fit the page. I tried a lot, but it isn't working.

Home

Body:
You want place <li> int the center, right?

The easiest way according to your current markup is to apply fixed width and add margin: 0 auto; to your li.

Semantics of that solution is really bad, but i guess you don't really care.


答:
Try this: (This will work even if your array has more than 4 values)

```<code>$count = 0;
foreach ($bank as $key=>$value) {
    if ($value === 2) {
        $count++;
    }
}

if ($count) {
    $s = $count > 1 ? 's' : '';
    echo "You got $count pair$s";
}
</code>```

It will show an output like You got 1 pair. If you want to use words (like you mentioned in your question), you can use NumberFormatter class

Title: Searching array for multiple value

Body:
Try this: (This will work even if your array has more than 4 values)

$count = 0;
foreach ($bank as $key=>$value) {
    if ($value === 2) {
        $count++;
    }
}

if ($count) {
    $s = $count > 1 ? 's' : '';
    echo "You got $count pair$s";
}

It will show an output like You got 1 pair. If you want to use words (like you mentioned in your question), you can use NumberFormatter class


问:
no operator ">>" matches these operands operand types are: std::istream >> double*

I'm trying to dynamically allocate an array from a structure. I've look on a couple of other pages on stackoverflow and tried some some code, but none seems to work for my case. The closest I've found to what I'm doing is here:

C++ dynamic memory allocation with arrays in a structure

For some reason when I use this line of code:

```<code>cin >> testsPtr[i].students;
</code>```

I get the error in the title. I've also tried using:

```<code>cin >> testsPtr[i]->students;
</code>```

How can I have the user enter the data for my program?

Here are the specifications for the programming challenge:

Modify the program of Programming Challenge 1 to allow the user to enter name-score pairs. For each student taking a test, the user types a string representing the name of the student, followed by an integer representing the students score. Modify both the sorting and average-calculating functions so they take arrays of structures, with each structure containing the name and score of a single student. In traversing the arrays, use pointers rather than array indices.

```<code>#include <iostream>
#include <iomanip>

using namespace std;

int main() {

void averageScore(double*, int);
void sort(double*, int);

int numScores;

struct studentScores {
    double *scores;
    string *students;
};

cout << "How many test scores will you be entering?" << endl;
cin >> numScores;

studentScores *testsPtr = new studentScores[numScores];

for (int i = 0; i < numScores; i++) {

    cout << "What is the #" << i + 1 << " students name?" << endl;
    cin >> testsPtr[i].students;
    for (int j = 0; j < numScores; j++) {

        cout << "Please enter test score #" << j + 1 << endl;

        do {
            cin >> testsPtr[j].scores;
            if (testsPtr[i].scores < 0) {
                cout << "A test score can't be less than 0. Re-enter test score #" << i + 1 << endl;
            }

        } while (testsPtr[i].scores < 0);
    }
}

cout << endl;

/*sort(testsPtr.scores, numScores);
cout << endl;

averageScore(testScores, numScores);
cout << endl;*/
for (int i = 0; i <= numScores; i++) {
    cout << testsPtr->students << " test scores are: " << endl;
    for (int j = 0; j <= numScores; j++) {
        cout << testsPtr->scores;
    }
}

delete[] testsPtr;
testsPtr = nullptr;

return 0;
}
</code>```

答:
The fix to your problem is to change your cin line to this cin >> *(testsPtr[i].students); this is because testsPtr[i].students is a pointer so you have to use the deference pointer. Make sure you correctly initialize the members.

Hope this helps.

Body:
I'm trying to dynamically allocate an array from a structure. I've look on a couple of other pages on stackoverflow and tried some some code, but none seems to work for my case. The closest I've found to what I'm doing is here:

C++ dynamic memory allocation with arrays in a structure

For some reason when I use this line of code:

cin >> testsPtr[i].students;

I get the error in the title. I've also tried using:

cin >> testsPtr[i]->students;

How can I have the user enter the data for my program?

Here are the specifications for the programming challenge:

Modify the program of Programming Challenge 1 to allow the user to enter name-score pairs. For each student taking a test, the user types a string representing the name of the student, followed by an integer representing the students score. Modify both the sorting and average-calculating functions so they take arrays of structures, with each structure containing the name and score of a single student. In traversing the arrays, use pointers rather than array indices.

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

void averageScore(double*, int);
void sort(double*, int);

int numScores;

struct studentScores {
    double *scores;
    string *students;
};

cout << "How many test scores will you be entering?" << endl;
cin >> numScores;

studentScores *testsPtr = new studentScores[numScores];

for (int i = 0; i < numScores; i++) {

    cout << "What is the #" << i + 1 << " students name?" << endl;
    cin >> testsPtr[i].students;
    for (int j = 0; j < numScores; j++) {

        cout << "Please enter test score #" << j + 1 << endl;

        do {
            cin >> testsPtr[j].scores;
            if (testsPtr[i].scores < 0) {
                cout << "A test score can't be less than 0. Re-enter test score #" << i + 1 << endl;
            }

        } while (testsPtr[i].scores < 0);
    }
}

cout << endl;

/*sort(testsPtr.scores, numScores);
cout << endl;

averageScore(testScores, numScores);
cout << endl;*/
for (int i = 0; i <= numScores; i++) {
    cout << testsPtr->students << " test scores are: " << endl;
    for (int j = 0; j <= numScores; j++) {
        cout << testsPtr->scores;
    }
}

delete[] testsPtr;
testsPtr = nullptr;

return 0;
}


答:
Just use a defaultdict to store the counts of each (code, name):

```<code>from collections import defaultdict

list_dict = [{'code': 'A1', 'name': 'White'},
             {'code': 'A2', 'name': 'Black'},
             {'code': 'A1', 'name': 'White'},
             {'code': 'A3', 'name': 'Red'},
            ]

d = defaultdict(int)
for dic in list_dict:
    key = dic['code'], dic['name']
    d[key] += 1

>>> print(dict(d))
{('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1}
</code>```

Then just create a new list, and insert the new data from the dictionary above:

```<code>new_dict_list = [{'code':code, 'name':name, 'qty':qty} for (name, code), qty in d.items()]

>>> print(new_dict_list)
[{'code': 'A1', 'name': 'White', 'qty': 2}, {'code': 'A2', 'name': 'Black', 'qty': 1}, {'code': 'A3', 'name': 'Red', 'qty': 1}]
</code>```

Title: Python count dictionary inside list with same value

Body:
I have dicts like this :

list_dicts = [
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A2', 'name': 'Black',
    },
    {
        'code': 'A1', 'name': 'White',
    },
    {
        'code': 'A3', 'name': 'Red',
    }
]

And how to get dicts look like this from above dicts ?

list_dicts = [
    {
        'code': 'A1', 'name': 'White', 'qty': 2
    },
    {
        'code': 'A2', 'name': 'Black', 'qty': 1
    },
    {
        'code': 'A3', 'name': 'Red', 'qty': 1
    }
]

..........................

Body:
Just use a defaultdict to store the counts of each (code, name):

from collections import defaultdict

list_dict = [{'code': 'A1', 'name': 'White'},
             {'code': 'A2', 'name': 'Black'},
             {'code': 'A1', 'name': 'White'},
             {'code': 'A3', 'name': 'Red'},
            ]

d = defaultdict(int)
for dic in list_dict:
    key = dic['code'], dic['name']
    d[key] += 1

>>> print(dict(d))
{('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1}

Then just create a new list, and insert the new data from the dictionary above:

new_dict_list = [{'code':code, 'name':name, 'qty':qty} for (name, code), qty in d.items()]

>>> print(new_dict_list)
[{'code': 'A1', 'name': 'White', 'qty': 2}, {'code': 'A2', 'name': 'Black', 'qty': 1}, {'code': 'A3', 'name': 'Red', 'qty': 1}]


答:
It seems you already know the importance of the null terminator, but the point is, you defined char strB[80]; in external namespace (with static life span), which causes initialization of the array strB, which sets all bytes of it to zero. That's why you can't observe the difference （because even if you don't append a null character, the rest of strB already is).

Moving the definition of  strB makes this visible. strA doesn't need moving because it doesn't matter.

In actuality, this code

```<code>while (*source != '\0')
{
    *p++ = *source++;
}
// *p = '\0';
</code>```

When *source reaches a null character, it's not copied to *p, so you need to manualky add a terminator for that.

Title: C++ Pointers to arrays

Body:
It seems you already know the importance of the null terminator, but the point is, you defined char strB[80]; in external namespace (with static life span), which causes initialization of the array strB, which sets all bytes of it to zero. That's why you can't observe the difference （because even if you don't append a null character, the rest of strB already is).

Moving the definition of  strB makes this visible. strA doesn't need moving because it doesn't matter.

In actuality, this code

while (*source != '\0')
{
    *p++ = *source++;
}
// *p = '\0';

When *source reaches a null character, it's not copied to *p, so you need to manualky add a terminator for that.


问:
How to access JSON values using foreach - Laravel
I am in php/laravel im using foreach to access the values like:

CODE:

```<code>@foreach($users as $user)
{{$user}}
@endforeach
</code>```

Result:

```<code>{
    "id": 97,
    "user_id": 68,
    "reporting": "25",
    "created_at": "2017-11-28 09:18:57",
    "updated_at": "2017-11-28 09:18:57",
    "reporting_users": [
        {
            "id": 2,
            "attendanceId": 1,
            "name": 68,
            "attendanceDate": "2017-12-04 00:00:00",
            "clockIn": "2017-12-04 05:10:00",
            "clockOut": "2017-12-04 05:10:00",
            "workTime": "2017-12-04 05:10:00",
            "reason": "test",
            "status": 1,
            "created_at": null,
            "updated_at": null
        }
    ],
    "find_user": {
        "id": 68,
        "attendances_id": 1,
        "name": "Ahsan Khyraj",
        "email": "ahsan22@gmail.com",
        "verificationToken": "nhpyzVQr8YjFJbHvokrzjwee2",
        "status": 1,
        "userType": 1,
        "department": 1,
        "created_at": "2017-11-28 09:18:57",
        "updated_at": "2017-11-28 09:18:57"
    }
}
</code>```

Now how can I access the value attendanceId and email ?

I am able to access the value of reporting

```<code>{{$user->reporting}}
</code>```

but how can I access the other values which is inside reporting_users and find_user

答:
Let's break it down.

reporting_users is an array (Note the [] square bracket). So you got to loop it.

find_user is an object (Note the {}), so you just access it via the ->.

```<code>@foreach($users as $user)
  {{ $user->find_user->name }}
  @foreach($user->reporting_users as $reporting_user)
     {{ $reporting_user->name }}

  @endforeach
@endforeach
</code>```

Body:
I am in php/laravel im using foreach to access the values like:

CODE:

@foreach($users as $user)
{{$user}}
@endforeach

Result:

{
    "id": 97,
    "user_id": 68,
    "reporting": "25",
    "created_at": "2017-11-28 09:18:57",
    "updated_at": "2017-11-28 09:18:57",
    "reporting_users": [
        {
            "id": 2,
            "attendanceId": 1,
            "name": 68,
            "attendanceDate": "2017-12-04 00:00:00",
            "clockIn": "2017-12-04 05:10:00",
            "clockOut": "2017-12-04 05:10:00",
            "workTime": "2017-12-04 05:10:00",
            "reason": "test",
            "status": 1,
            "created_at": null,
            "updated_at": null
        }
    ],
    "find_user": {
        "id": 68,
        "attendances_id": 1,
        "name": "Ahsan Khyraj",
        "email": "ahsan22@gmail.com",
        "verificationToken": "nhpyzVQr8YjFJbHvokrzjwee2",
        "status": 1,
        "userType": 1,
        "department": 1,
        "created_at": "2017-11-28 09:18:57",
        "updated_at": "2017-11-28 09:18:57"
    }
}

Now how can I access the value attendanceId and email ?

I am able to access the value of reporting

{{$user->reporting}}

but how can I access the other values which is inside reporting_users and find_user

Body:
Let's break it down.

reporting_users is an array (Note the [] square bracket). So you got to loop it.

find_user is an object (Note the {}), so you just access it via the ->.

@foreach($users as $user)
  {{ $user->find_user->name }}
  @foreach($user->reporting_users as $reporting_user)
     {{ $reporting_user->name }}

  @endforeach
@endforeach


问:
Pyvmomi - Assign VM to specific folder with non-unique name
I'm trying to figure out how to assign a VM to a folder that does not contain a unique name. I'm currently testing with the clone_vm.py template. With the sample, I have the ability to set the folder, but it does not work correctly if there's nested folders with the same name (example below). I would like to make sure the folder assigned is the "Linux/Dev" folder, but I can only pass "Dev" and hope that it picks the right one. The line of code below is how the folder is being set.

```<code>destfolder = get_obj(content, [vim.Folder], vm_folder)
</code>```

Linux

```<code>    |------Dev

    |------Prod
</code>```

Windows

```<code>    |------Dev

    |------Prod
</code>```

Thanks!

答: The best way to do that is to use a search_index.FindByInventoryPath and get the folder by the path. It can be a little confusing because of hidden folders but the MOB can help you. I answered a question where I covered how to use that search method see this answer.

Body:
I'm trying to figure out how to assign a VM to a folder that does not contain a unique name. I'm currently testing with the clone_vm.py template. With the sample, I have the ability to set the folder, but it does not work correctly if there's nested folders with the same name (example below). I would like to make sure the folder assigned is the "Linux/Dev" folder, but I can only pass "Dev" and hope that it picks the right one. The line of code below is how the folder is being set.

destfolder = get_obj(content, [vim.Folder], vm_folder)

Linux

    |------Dev

    |------Prod

Windows

    |------Dev

    |------Prod

Thanks!


问:
PHP Notice: Use of undefined constant php - assumed 'php'
Was just editing a site I'm working on to include the subscription form in the footer.php rather than just the homepage. I made the changes on the local server then moved it to my live environment (dev sub-folder). I didn't see any errors on my localhost, but on the dev site it is showing the following error:

PHP Notice:  Use of undefined constant php - assumed 'php' in /home/website-name/public_html/uk-en/dev/wp-content/themes/theme-name/footer.php on line 1

The only thing on line 1 is the opening php tag, see code below from the footer.php file

```<code><?php?>
</div><!-- #main -->
<footer id="colophon" class="site-footer" role="contentinfo">
    <div class="subscribe-form">
        <p>SIGN UP TO OUR EMAIL NEWSLETTER FOR NEWS, OFFERS & EXCITING COMPETITIONS.<p>
    <div class="contact-7-subscribe">           <?php echo do_shortcode( '[contact-form-7 id="4563" title="Newsletter"]' ); ?>      </div>
    </div>
    <div class="site-info">

        <div class="socialmedia">
            <a href="https://www.facebook.com/pg/page-name/" target="_blank" class="facebook"></a>
            <a href="https://twitter.com/page-name?lang=en" target="_blank" class="twitter"></a>
            <a href="https://www.instagram.com/page-name/" target="_blank" class="youtube"></a>
        </div>
        <div class="payment_cards">
            <img src="<?=site_url();?>/wp-content/uploads/2017/05/payment_cards.png" alt="payments cards"/>
        </div>
        <?php /* Widgetized sidebar */ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footerwidget') ) : ?><?php endif; ?>
    </div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
<?php /* if(get_the_ID() == 5) { ?>
<script type="text/javascript"
src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-
forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false">
</script><script type="text/javascript">require(["mojo/signup-
forms/Loader"], function(L) { L.start({"baseUrl":"mc.us10.list-
manage.com","uuid":"37710aefba71598269bda7def","lid":"4385b1c355"}) })
</script>
<?php } */ ?>
<!--Start of Zopim Live Chat Script-->
<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
$.src="//v2.zopim.com/?34qd49wmFaK3NsxoUst4PCSk4gaXUQVe";z.t=+new Date;$.
type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
</script>
<!--End of Zopim Live Chat Script-->
<?php /*?><script type="text/javascript"
src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-
forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false">
</script><script type="text/javascript">require(["mojo/signup-
forms/Loader"], function(L) { L.start({"baseUrl":"mc.us10.list-
manage.com","uuid":"37710aefba71598269bda7def","lid":"4385b1c355"}) })
</script><?php */?>
</body>
</html>
</code>```

I could turn off notice display however I would like to get the right solution rather than a cover up

答:
Basic syntax of php opening tag is <?php[whitespace] not just <?php, see here http://php.net/manual/en/language.basic-syntax.phptags.php#118827.
So the right syntax would be adding a white space in between php opening and closing tag <?php ?>

Body:
Was just editing a site I'm working on to include the subscription form in the footer.php rather than just the homepage. I made the changes on the local server then moved it to my live environment (dev sub-folder). I didn't see any errors on my localhost, but on the dev site it is showing the following error:

PHP Notice:  Use of undefined constant php - assumed 'php' in /home/website-name/public_html/uk-en/dev/wp-content/themes/theme-name/footer.php on line 1

The only thing on line 1 is the opening php tag, see code below from the footer.php file

<?php?>

SIGN UP TO OUR EMAIL NEWSLETTER FOR NEWS, OFFERS & EXCITING COMPETITIONS.

           <?php echo do_shortcode( '[contact-form-7 id="4563" title="Newsletter"]' ); ?>

            <img src="<?=site_url();?>/wp-content/uploads/2017/05/payment_cards.png" alt="payments cards"/>

        <?php /* Widgetized sidebar */ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footerwidget') ) : ?><?php endif; ?>

<?php wp_footer(); ?>
<?php /* if(get_the_ID() == 5) { ?>

<?php } */ ?>

<?php /*?><?php */?>

I could turn off notice display however I would like to get the right solution rather than a cover up


问:
Get Non Pre-Windows 2000 Group Name from SID
I have a SID which represents a group on a different domain.

I am trying to get the group name using:

```<code>$objSid = New-Object 'System.Security.Principal.SecurityIdentifier'($Sid)
$objUser = $objSid.Translate([System.Security.Principal.NTAccount])
$groupName = $objUser.Value
</code>```

However this returns the pre-Windows 2000 name which is different to the actual group name (it has A_ at the front).

How can I get the real group name instead of the pre-Windows 2000 group name?

EDIT:
iRon mentioned I can use (Get-ADGroup $GroupName).Name, however I now need to write this in C#. The first part is easy to translate, however how can I get the C# code for the Get-ADGroup commandlet?

答:
Turns out the pre-Windows 2000 name is just the samAccountName.
So to get the group name, you just need to search for the group with samAccountName = pre-Windows 2000 name.
This can easily be done in C# using DirectorySearcher.</p>

Body:
I have a SID which represents a group on a different domain.

I am trying to get the group name using:

$objSid = New-Object 'System.Security.Principal.SecurityIdentifier'($Sid)
$objUser = $objSid.Translate([System.Security.Principal.NTAccount])
$groupName = $objUser.Value

However this returns the pre-Windows 2000 name which is different to the actual group name (it has A_ at the front).

How can I get the real group name instead of the pre-Windows 2000 group name?

EDIT:
iRon mentioned I can use (Get-ADGroup $GroupName).Name, however I now need to write this in C#. The first part is easy to translate, however how can I get the C# code for the Get-ADGroup commandlet?


问:
Bootstrap popover positioning
Is there a way to align bootstrap popover on "Right Bottom" of the clicked button instead of the "Right Middle"? It should be dynamic.

You can check the standard code here http://jsfiddle.net/VUZhL/2915/

```<code><a href="#" id="example" rel="popover" data-placement="right" data-content="Header" data-original-title="Text">pop</a>
</code>```

Thanks in advance.

答:
You need to override bootstrap popover css to achieve what you want:

```<code>.popover {
    margin-top: -20px;
}

.popover.right .arrow {
    margin-top: 8px;
}
</code>```

Check the following fiddle:

http://jsfiddle.net/VUZhL/2916/

Title: Bootstrap popover positioning

Body:
Is there a way to align bootstrap popover on "Right Bottom" of the clicked button instead of the "Right Middle"? It should be dynamic.

You can check the standard code here http://jsfiddle.net/VUZhL/2915/

pop

Thanks in advance.

Body:
You need to override bootstrap popover css to achieve what you want:

.popover {
    margin-top: -20px;
}

.popover.right .arrow {
    margin-top: 8px;
}

Check the following fiddle:

http://jsfiddle.net/VUZhL/2916/


问:
while installing node.js getting permission denied error
I downloaded the file for version 8.9.2 of node js and I am using lubuntu. I extracted the tar.xz file of nodejs I downloaded into a folder I made, and then in my command line entered

```<code>cd /usr/src
wget http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
</code>```

But then this shows up.

```<code>--2017-12-07 22:08:56--  http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
Resolving nodejs.org (nodejs.org)... 2400:cb00:2048:1::6814:172e, 2400:cb00:2048:1::6814:162e, 104.20.22.46, ...
Connecting to nodejs.org (nodejs.org)|2400:cb00:2048:1::6814:172e|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31109143 (30M) [application/gzip]
node-v8.9.2.tar.gz: Permission denied

Cannot write to ‘node-v8.9.2.tar.gz’ (Permission denied).
</code>```

So how do I install it properly?

答: You will have to be root or have use sudo before command provided you are added to sudoers group.

Body:
I downloaded the file for version 8.9.2 of node js and I am using lubuntu. I extracted the tar.xz file of nodejs I downloaded into a folder I made, and then in my command line entered

cd /usr/src
wget http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz

But then this shows up.

--2017-12-07 22:08:56--  http://nodejs.org/dist/v8.9.2/node-v8.9.2.tar.gz
Resolving nodejs.org (nodejs.org)... 2400:cb00:2048:1::6814:172e, 2400:cb00:2048:1::6814:162e, 104.20.22.46, ...
Connecting to nodejs.org (nodejs.org)|2400:cb00:2048:1::6814:172e|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31109143 (30M) [application/gzip]
node-v8.9.2.tar.gz: Permission denied

Cannot write to ‘node-v8.9.2.tar.gz’ (Permission denied).

So how do I install it properly?