问:
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.continuum.io/pk gs/r/win-64/repodata.json.bz2>
I need to install Tensorflow and was trying to add up environment first. But I get HTTP Connection Failed error. I'm behind a corporate proxy and already defined them well in .condarc file. Here is the error I'm getting:

```<code>C:\Users\Rahul\Downloads>conda create -n tensorflow python=3.6 anaconda
Solving environment: failed
CondaHTTPError: HTTP 000 CONNECTION FAILED for url
<https://repo.continuum.io/pk
gs/r/win-64/repodata.json.bz2>
Elapsed: -
An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your
way.
ConnectionError(MaxRetryError("HTTPSConnectionPool(host='repo.continuum.io, por
t=443): Max retries exceeded with url: /pkgs/r/win-64/repodata.json.bz2 (Caused
by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0
000001A00393C88>: Failed to establish a new connection: [Errno 11002] getaddrinf
o failed',))",),)
</code>```

I posted this issue in their issue tracker here in detail:
https://github.com/conda/conda/issues/7283

As mentioned in issue tracker, I already tried resetting ssl, adding condarc file etc. But no luck so far. My proxy is working as expected and my entries in condarc file are correct. Also continuum repository is accessible via browser without issues.

None of the commands like conda update or conda install works and gives the same error stack while executing.

What might be going wrong here?

答:
I strongly recommend to copy libcrypto-1_1-x64.*
libssl-1_1-x64.* from .\Library in Anaconda folder to .\DLL in Anaconda folder. I'm 100% sure that your problem will be solved. Please don't crack your heads looking for solution on all the platforms.

Body:
I need to install Tensorflow and was trying to add up environment first. But I get HTTP Connection Failed error. I'm behind a corporate proxy and already defined them well in .condarc file. Here is the error I'm getting:

C:\Users\Rahul\Downloads>conda create -n tensorflow python=3.6 anaconda
Solving environment: failed
CondaHTTPError: HTTP 000 CONNECTION FAILED for url
<https://repo.continuum.io/pk
gs/r/win-64/repodata.json.bz2>
Elapsed: -
An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your
way.
ConnectionError(MaxRetryError("HTTPSConnectionPool(host='repo.continuum.io, por
t=443): Max retries exceeded with url: /pkgs/r/win-64/repodata.json.bz2 (Caused
by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0
000001A00393C88>: Failed to establish a new connection: [Errno 11002] getaddrinf
o failed',))",),)

I posted this issue in their issue tracker here in detail:
https://github.com/conda/conda/issues/7283

As mentioned in issue tracker, I already tried resetting ssl, adding condarc file etc. But no luck so far. My proxy is working as expected and my entries in condarc file are correct. Also continuum repository is accessible via browser without issues.

None of the commands like conda update or conda install works and gives the same error stack while executing.

What might be going wrong here?


来源: stackexchange

问:
Taking the last five digits of a number from user input in REACT.jsx
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

```<code>{this.props.x ? (
              <p>
                Card number: <br />
                {"***** *****" + this.props.x}
              </p>
            ) : (
              ""
            )
</code>```

I want the end result to look like
***** ***** 54321

答:
Use simple JS:

let str = "12345 12345 54321",
    len = str.length - 1,
    newstr = "",
    i = 0;

while (i != 5) {
    newstr = str[len] + newstr;
    len--; i++;
}

console.log(newstr)```

ContentLicense: CC BY-SA 4.0

Body:
Basically, I am currently using this.props.x (which is the user input) to get information from another page. So this.props.x is a number, for example "12345 12345 54321" in three groups of 5 digits. I want to replace the first 10 digits with asterisks and keep the last 5 digits. How do I manipulate this.props.x in such a way that I can make this possible?

Thanks.

This is what I've tried.

{this.props.x ? (

                Card number:

                {"***** *****" + this.props.x}

            ) : (
              ""
            )

I want the end result to look like
***** ***** 54321


问:
Dynamic define_method throwing error in RSpec
I am pretty sure I am missing a basic mistake here, so I am hoping another set of eyes might help. I am using Rails 3, Ruby 1.9.2 and Rspec 2.

I would like to define dynamic class methods on a model so that I can return base roles for an assignable object (such as account) as they are added to the system. For example:

```<code>BaseRole.creator_for_account
</code>```

Everything works fine via the console:

```<code>ruby-1.9.2-p180 :003 > BaseRole.respond_to?(:creator_for_account)
 => true
</code>```

but when I run my specs for any of class methods, I get a NoMethodError wherever I call the method in the spec. I am assuming that something about how I am dynamically declaring the methods is not jiving with RSpec but I cannot seem to figure out why.

The lib dir is autoloaded path and the methods return true for respond_to?.

```<code># /lib/assignable_base_role.rb
module AssignableBaseRole
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    BaseRole.all.each do |base_role|
      role_type = RoleType.find(base_role.role_type_id)
      assignable_name = base_role.assignable_type.downcase
      method = "#{role_type.name}_for_#{assignable_name}"

      define_method(method) do
        self.where(:role_type_id => role_type.id,
                :assignable_type => assignable_name).first
      end
    end
  end
end
</code>```

Then include the Module in BaseRole

```<code># /models/base_role.rb
class BaseRole < ActiveRecord::Base
  include AssignableBaseRole

  belongs_to :role
  belongs_to :role_type

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

end
</code>```

Then in my spec:

```<code>  it "adds correct authority for creator role" do
    create_assignment
    base_role = BaseRole.creator_for_account # <== NoMethodError here
    user1 = Factory.create(:user)
    account.users << user1
    user1.roles_for_assignable(account).should include(base_role.role)
  end
</code>```

答:
It appears you are defining these methods based on values in the database:

```<code>BaseRole.all.each do |base_role|
.....
</code>```

Could it be that "creator" doesn't exist in the test database as a role type, or "account" doesn't exist as assignable_type?

Presumably you are testing this in the console for development, not test, so the data could be mismatched. Might need to set up the data in a before hook.

ContentLicense: CC BY-SA 3.0

Body:
I am pretty sure I am missing a basic mistake here, so I am hoping another set of eyes might help. I am using Rails 3, Ruby 1.9.2 and Rspec 2.

I would like to define dynamic class methods on a model so that I can return base roles for an assignable object (such as account) as they are added to the system. For example:

BaseRole.creator_for_account

Everything works fine via the console:

ruby-1.9.2-p180 :003 > BaseRole.respond_to?(:creator_for_account)
 => true

but when I run my specs for any of class methods, I get a NoMethodError wherever I call the method in the spec. I am assuming that something about how I am dynamically declaring the methods is not jiving with RSpec but I cannot seem to figure out why.

The lib dir is autoloaded path and the methods return true for respond_to?.

# /lib/assignable_base_role.rb
module AssignableBaseRole
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    BaseRole.all.each do |base_role|
      role_type = RoleType.find(base_role.role_type_id)
      assignable_name = base_role.assignable_type.downcase
      method = "#{role_type.name}_for_#{assignable_name}"

      define_method(method) do
        self.where(:role_type_id => role_type.id,
                :assignable_type => assignable_name).first
      end
    end
  end
end

Then include the Module in BaseRole

# /models/base_role.rb
class BaseRole < ActiveRecord::Base
  include AssignableBaseRole

  belongs_to :role
  belongs_to :role_type

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

end

Then in my spec:

  it "adds correct authority for creator role" do
    create_assignment
    base_role = BaseRole.creator_for_account # <== NoMethodError here
    user1 = Factory.create(:user)
    account.users << user1
    user1.roles_for_assignable(account).should include(base_role.role)
  end

Body:
It appears you are defining these methods based on values in the database:

BaseRole.all.each do |base_role|
.....

Could it be that "creator" doesn't exist in the test database as a role type, or "account" doesn't exist as assignable_type?

Presumably you are testing this in the console for development, not test, so the data could be mismatched. Might need to set up the data in a before hook.


问:
How to remove N+1 queries
I have a rails API that currently has quite a few N+1 queries that I'd like to reduce.

As you can see it's going through quite a few loops before returning the data.

The relationships are as follows:

Company Model

```<code>class Company < ApplicationRecord
  has_many :jobs, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :listings
end
</code>```

Job Model

```<code>class Job < ApplicationRecord
  belongs_to :company
  has_many :listings
  has_and_belongs_to_many :technologies
  has_and_belongs_to_many :tools

  scope :category, -> ( category ) { where category: category }
end
</code>```

Listing Modal

```<code>class Listing < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :company, dependent: :destroy

  scope :is_active, -> ( active ) { where is_active: active }
end
</code>```

Job Serializer

```<code>class SimpleJobSerializer < ActiveModel::Serializer
  attributes  :id,
              :title,
              :company_name,

  attribute :technology_list, if: :technologies_exist
  attribute :tool_list, if: :tools_exist

  def technology_list
    custom_technologies = []

    object.technologies.each do |technology|
      custom_technology = { label: technology.label, icon: technology.icon }
      custom_technologies.push(custom_technology)
    end

    return custom_technologies
  end

  def tool_list
    custom_tools = []

    object.tools.each do |tool|
      custom_tool = { label: tool.label, icon: tool.icon }
      custom_tools.push(custom_tool)
    end

    return custom_tools
  end

  def tools_exist
    return object.tools.any?
  end

  def technologies_exist
    return object.technologies.any?
  end

  def company_name
    object.company.name
  end
end
</code>```

Current query in controller

```<code>Job.eager_load(:listings).order("listings.live_date DESC").where(category: "developer", listings: { is_active: true }).first(90)
</code>```

I've tried to use eager_load to join the listings to the Jobs to make the request more efficient but i'm unsure how to handle this when some of the n+1 queries are coming from inside the serializer as it tries to look at tools and technologies.

Any help would be much appreciated!

答:
Try nested preload:

Job.preload(:technologies, :tools, company: :listings).order(...).where(...)
```

Title: How to remove N+1 queries

Body:
I have a rails API that currently has quite a few N+1 queries that I'd like to reduce.

As you can see it's going through quite a few loops before returning the data.

The relationships are as follows:

Company Model

class Company < ApplicationRecord
  has_many :jobs, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :listings
end

Job Model

class Job < ApplicationRecord
  belongs_to :company
  has_many :listings
  has_and_belongs_to_many :technologies
  has_and_belongs_to_many :tools

  scope :category, -> ( category ) { where category: category }
end

Listing Modal

class Listing < ApplicationRecord
  belongs_to :job, dependent: :destroy
  belongs_to :company, dependent: :destroy

  scope :is_active, -> ( active ) { where is_active: active }
end

Job Serializer

class SimpleJobSerializer < ActiveModel::Serializer
  attributes  :id,
              :title,
              :company_name,

  attribute :technology_list, if: :technologies_exist
  attribute :tool_list, if: :tools_exist

  def technology_list
    custom_technologies = []

    object.technologies.each do |technology|
      custom_technology = { label: technology.label, icon: technology.icon }
      custom_technologies.push(custom_technology)
    end

    return custom_technologies
  end

  def tool_list
    custom_tools = []

    object.tools.each do |tool|
      custom_tool = { label: tool.label, icon: tool.icon }
      custom_tools.push(custom_tool)
    end

    return custom_tools
  end

  def tools_exist
    return object.tools.any?
  end

  def technologies_exist
    return object.technologies.any?
  end

  def company_name
    object.company.name
  end
end

Current query in controller

Job.eager_load(:listings).order("listings.live_date DESC").where(category: "developer", listings: { is_active: true }).first(90)

I've tried to use eager_load to join the listings to the Jobs to make the request more efficient but i'm unsure how to handle this when some of the n+1 queries are coming from inside the serializer as it tries to look at tools and technologies.

Any help would be much appreciated!


问:
R adding element to Dataframe at specific position
I want to add a row to a dataframe in R at a specific position. I am aware that there are solutions for this on this site, yet they don't seem to work. I know rbind is rather slow, but given that I only need to do it for a single element it doesn't matter:

Example:

```<code>vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,], data.frame("value"=5000),
                            vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),])
</code>```

The desired result is obviously 1,2,3,4,5,5000,6,7,8,9, yet I get 1,5000,6. Where is my mistake?

答:
We can use add_row to add a specific row at a location

```<code>library(tibble)
add_row(vector_labour_brexit.m , .before = 6, value = 5000)
#   value
#1      1
#2      2
#3      3
#4      4
#5      5
#6   5000
#7      6
#8      7
#9      8
#10     9
</code>```

The issue in the OP's code was due to drop = TRUE by default when there is a single column or row, it drops the dimensions

```<code>vector_labour_brexit.m[1:5,]
</code>```

If we add drop = FALSE while subsetting, it would work

Body:
I want to add a row to a dataframe in R at a specific position. I am aware that there are solutions for this on this site, yet they don't seem to work. I know rbind is rather slow, but given that I only need to do it for a single element it doesn't matter:

Example:

vector_labour_brexit.m <- data.frame("value" = c(1,2,3,4,5,6,7,8,9))

temp <- rbind(vector_labour_brexit.m[1:5,], data.frame("value"=5000),
                            vector_labour_brexit.m[6:nrow(vector_labour_brexit.m),])

The desired result is obviously 1,2,3,4,5,5000,6,7,8,9, yet I get 1,5000,6. Where is my mistake?

Body:
We can use add_row to add a specific row at a location

library(tibble)
add_row(vector_labour_brexit.m , .before = 6, value = 5000)
#   value
#1      1
#2      2
#3      3
#4      4
#5      5
#6   5000
#7      6
#8      7
#9      8
#10     9

The issue in the OP's code was due to drop = TRUE by default when there is a single column or row, it drops the dimensions

vector_labour_brexit.m[1:5,]

If we add drop = FALSE while subsetting, it would work


问:
How do I create a parallel spliterator from multiple iterators?
I have a list of cursor-backed iterators that are returned by a method that executes multiple database queries.

Since each cursor-backed iterator is partitioned as such on the database, I'd like to leverage parallel-stream operations on the resultant stream as well. For this, I'd like to create a spliterator.

```<code>List<Iterator<Article>> articleIterators = executeQuery();
</code>```

How would I go about creating a spliterator? Assume that the items in each iterator are ordered. It is possible that my thinking is fundamentally flawed.

A bit more background: I run multiple Cassandra queries so each query hits a different partition. Each query returns its own lazy paging iterator.

答:
You may could have a try with Stream provided in abacus-common

```<code>List<Stream<Integer>> iters = IntStream.range(1, 32).mapToObj(it -> Stream.repeat(1, it).peek(Fn.sleep(3))).toList();

long startTime = System.currentTimeMillis();
Stream.concat(iters).sumInt(Integer::intValue);
System.out.println("Took: " + (System.currentTimeMillis() - startTime)); // print out: Took: 1535

iters = IntStream.range(1, 32).mapToObj(it -> Stream.repeat(1, it).peek(Fn.sleep(3))).toList();

startTime = System.currentTimeMillis();
Stream.parallelConcat(iters).sumInt(Integer::intValue);
System.out.println("Took: " + (System.currentTimeMillis() - startTime)); // print out: Took: 251
</code>```

Disclaimer：I'm the developer of abacus-common.

Body:
I have a list of cursor-backed iterators that are returned by a method that executes multiple database queries.

Since each cursor-backed iterator is partitioned as such on the database, I'd like to leverage parallel-stream operations on the resultant stream as well. For this, I'd like to create a spliterator.

List<Iterator
> articleIterators = executeQuery();

How would I go about creating a spliterator? Assume that the items in each iterator are ordered. It is possible that my thinking is fundamentally flawed.

A bit more background: I run multiple Cassandra queries so each query hits a different partition. Each query returns its own lazy paging iterator.

Body:
You may could have a try with Stream provided in abacus-common

List<Stream<Integer>> iters = IntStream.range(1, 32).mapToObj(it -> Stream.repeat(1, it).peek(Fn.sleep(3))).toList();

long startTime = System.currentTimeMillis();
Stream.concat(iters).sumInt(Integer::intValue);
System.out.println("Took: " + (System.currentTimeMillis() - startTime)); // print out: Took: 1535

iters = IntStream.range(1, 32).mapToObj(it -> Stream.repeat(1, it).peek(Fn.sleep(3))).toList();

startTime = System.currentTimeMillis();
Stream.parallelConcat(iters).sumInt(Integer::intValue);
System.out.println("Took: " + (System.currentTimeMillis() - startTime)); // print out: Took: 251

Disclaimer：I'm the developer of abacus-common.


问:
How to show only one div with same class then others
I'm creating a garage system and when my user clicks on a selected item, I wish to show the car picture for it. However the divs that contain the images all have the same class name, so all cars are showing up.

I'm trying to show only the class="imagem" from the selected item (active) not all.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');
  $('.imagem').fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $('.imagem').fadeIn(500);
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imagem {
  display: none;
}</code>```

GARAGE

  MODEL:
  DOCUMENTS:
  PRICE:

Bugatti

Indeed

$ 320.100

      Motor: 100%

      Chassis: 100%

      Fuel: 10%

Another Car

Indeed

$ 20.000

      Motor: 100%

      Chassis: 100%

      Fuel: 100%

```

答:
$('.imagem')` will always return you all the available elements on the page.

You have to find the .imagem class from its parent with find.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');
  $el.find('.imagem').fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $el.find('.imagem').fadeIn(500);
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imagem {
  display: none;
}</code>```

GARAGE

  MODEL:
  DOCUMENTS:
  PRICE:

Bugatti

Indeed

$ 320.100

      Motor: 100%

      Chassis: 100%

      Fuel: 10%

Another Car

Indeed

$ 20.000

      Motor: 100%

      Chassis: 100%

      Fuel: 100%

```

Body:
I'm creating a garage system and when my user clicks on a selected item, I wish to show the car picture for it. However the divs that contain the images all have the same class name, so all cars are showing up.

I'm trying to show only the class="imagem" from the selected item (active) not all.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');
  $('.imagem').fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $('.imagem').fadeIn(500);
  }

});

.imagem {
  display: none;
}

GARAGE

  MODEL:
  DOCUMENTS:
  PRICE:

Bugatti

Indeed

$ 320.100

      Motor: 100%

      Chassis: 100%

      Fuel: 10%

Another Car

Indeed

$ 20.000

      Motor: 100%

      Chassis: 100%

      Fuel: 100%

Body:
$('.imagem')` will always return you all the available elements on the page.

You have to find the .imagem class from its parent with find.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');
  $el.find('.imagem').fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $el.find('.imagem').fadeIn(500);
  }

});

.imagem {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="title">
  <h1>GARAGE</h1>
</div>
<div id="subtitle">
  <span class="sub1">MODEL: </span>
  <span class="sub2">DOCUMENTS:</span>
  <span class="sub3">PRICE:</span>
  </br>
</div>
<div class="item" data-item-name="bugatti">
  <div id="itemname">Bugatti</div>
  <div id="itemqtd">Indeed</div>
  <div id="itempeso">$ 320.100</div>
  <div class="imagem">
    <img style="max-width: 100%; max-height: 132px;" src="http://177.54.152.85/imgallstar/bugatti.png" />
    <div class="status">
      <span class="stat1">Motor: </span><span class="stat2">100%</span></br>
      <span class="stat1">Chassis: </span><span class="stat2">100%</span></br>
      <span class="stat1">Fuel: </span><span class="stat2">10%</span></br>
    </div>
  </div>
</div>
<div class="item" data-item-name="another">
  <div id="itemname">Another Car</div>
  <div id="itemqtd">Indeed</div>
  <div id="itempeso">$ 20.000</div>
  <div class="imagem">
    <img style="max-width: 100%; max-height: 132px;" src="http://177.54.152.85/imgallstar/another.png" />
    <div class="status">
      <span class="stat1">Motor: </span><span class="stat2">100%</span></br>
      <span class="stat1">Chassis: </span><span class="stat2">100%</span></br>
      <span class="stat1">Fuel: </span><span class="stat2">100%</span></br>
    </div>
  </div>
</div>


问:
True case statements are executed even if condition is false - MySQL
I need to select a column only if that column exists.

I've tried this check in this way:

```<code>set @esisteIlCampo =
    (
        SELECT COUNT(*)
        FROM
        (
            SELECT *
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = 'ventodelnord'
            AND TABLE_NAME = 'impiegati'
            AND COLUMN_NAME = 'Email'
        ) AS t
    ) > 0
</code>```

If gives 1 if the column Email exists and 0 if not.

Then I have this query to make use of it:

```<code>SELECT
    `i`.`IDImpiegato` AS `ID`,
    `i`.`TelDomicilio` AS `Numero Di Telefono`,
    CONCAT(`i`.`Nome`, ' ', `i`.`Cognome`) AS `Nome Completo`,
    (
        CASE WHEN
        @esisteIlCampo = 1
        THEN
        (
            SELECT impiegati.Email from impiegati limit 1
        )
        ELSE
        (
           SELECT "Campo Mancante"
        )
        END
    ) as "Email",
    'Impiegati' AS `Tabella di provenienza`
FROM
    `impiegati` `i`;
</code>```

But even if the @esisteIlCampo is 0, so the @esisteIlCampo = 1 evaluates to false, the SELECT impiegati.Email from impiegati limit 1 query is executed.

How is this possible?

答:
Start by using SELECT INTO

```<code>SELECT COUNT(*) INTO @esisteIlCampo
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'ventodelnord'
    AND TABLE_NAME = 'impiegati'
    AND COLUMN_NAME = 'Email';
</code>```

Then you can use

```<code>SELECT @esisteIlCampo;
</code>```

to see the result.

Then you can use it in your second Query.
Of course make sure hat you get an result.

Body:
I need to select a column only if that column exists.

I've tried this check in this way:

set @esisteIlCampo =
    (
        SELECT COUNT(*)
        FROM
        (
            SELECT *
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = 'ventodelnord'
            AND TABLE_NAME = 'impiegati'
            AND COLUMN_NAME = 'Email'
        ) AS t
    ) > 0

If gives 1 if the column Email exists and 0 if not.

Then I have this query to make use of it:

SELECT
    `i`.`IDImpiegato` AS `ID`,
    `i`.`TelDomicilio` AS `Numero Di Telefono`,
    CONCAT(`i`.`Nome`, ' ', `i`.`Cognome`) AS `Nome Completo`,
    (
        CASE WHEN
        @esisteIlCampo = 1
        THEN
        (
            SELECT impiegati.Email from impiegati limit 1
        )
        ELSE
        (
           SELECT "Campo Mancante"
        )
        END
    ) as "Email",
    'Impiegati' AS `Tabella di provenienza`
FROM
    `impiegati` `i`;

But even if the @esisteIlCampo is 0, so the @esisteIlCampo = 1 evaluates to false, the SELECT impiegati.Email from impiegati limit 1 query is executed.

How is this possible?

Body:
Start by using SELECT INTO

SELECT COUNT(*) INTO @esisteIlCampo
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'ventodelnord'
    AND TABLE_NAME = 'impiegati'
    AND COLUMN_NAME = 'Email';

Then you can use

SELECT @esisteIlCampo;

to see the result.

Then you can use it in your second Query.
Of course make sure hat you get an result.


问:
How to use sqlalchemy expression in read_sql_table using Dask?
I am using df = dd.read_sql_table('mytable_name', 'connection_string',npartitions=10, index_col='id') to create a Dask dataframe and it is working perfectly. But it is taking all rows of the table. I want to limit the number of rows or apply some conditions. For that, according to the official documentation read_sql_table we can use sqlalchemy expression. I am trying to write sqlalchemy expression but none of the way worked for me.

I tried like this:

```<code>engine = create_engine(connection_string)

metadata = MetaData()

t = Table('mytable_name', metadata,
Column('id'),
schema='my_schema')
s = select([t]).limit(500)
dd.read_sql_table(s, connection_string, index_col='id')
</code>```

but this is also not working. This is the sqlalchemy expression I found in the Official documentation of sqlalchemy.

Help me with the way of passing sqlalchemy expression in read_sql_table using Dask.

Thanks in Advance.

答:
The term "expression" is somewhat overloaded here. You are using the ORM representation, but Dask requires the lower-level SQL function expression syntax. In your case, I believe it would look like

```<code>from sqlalchemy import sql
expr = sql.select([sql.column("id")]).select_from(
        sql.table("mytable_name")
    ).limit(500)
</code>```

I do not know how to get the schema into there.

Body:
I am using df = dd.read_sql_table('mytable_name', 'connection_string',npartitions=10, index_col='id') to create a Dask dataframe and it is working perfectly. But it is taking all rows of the table. I want to limit the number of rows or apply some conditions. For that, according to the official documentation read_sql_table we can use sqlalchemy expression. I am trying to write sqlalchemy expression but none of the way worked for me.

I tried like this:

engine = create_engine(connection_string)

metadata = MetaData()

t = Table('mytable_name', metadata,
Column('id'),
schema='my_schema')
s = select([t]).limit(500)
dd.read_sql_table(s, connection_string, index_col='id')

but this is also not working. This is the sqlalchemy expression I found in the Official documentation of sqlalchemy.

Help me with the way of passing sqlalchemy expression in read_sql_table using Dask.

Thanks in Advance.

Body:
The term "expression" is somewhat overloaded here. You are using the ORM representation, but Dask requires the lower-level SQL function expression syntax. In your case, I believe it would look like

from sqlalchemy import sql
expr = sql.select([sql.column("id")]).select_from(
        sql.table("mytable_name")
    ).limit(500)

I do not know how to get the schema into there.


问:
ReactJs: Is it possible to retrieve the edited value inside this tag  {this.state.value} 	 tag
I have searched in many different stackOverflow questions and native html documentation and apparantly there's no way to retrieve the value inside a  :

```<code><td contentEditable='true'> {this.state.value}  </td>
</code>```

Apparently there's no native way to retrieve the edited value by the user?

In my app:

After the user clicks on the green button, I set the contentEditable attribute to true and hence he is able to edit the right column. However, I've found myself stuck when I wanted to retrieve the new value that the user has typed to send it to the backend!

But this doesn't make any sense, because what's the use of the attribute contentEditable if I cannot retrieve the edited value?

I have only found the onClick listener which I can use to learn when the user has clicked on a particular cell.

PS: I remember in Angular I used to do this easily with two-way data binding..

答:
```<code><td onClick={() => this.setState({ isEditing: true })}>
  {this.state.isEditing ? <input {...yourPropsToHandleInput} /> : {this.state.value}
</td>
</code>```

Title: ReactJs: Is it possible to retrieve the edited value inside this tag <td contentEditable='true'> {this.state.value} </td> tag

Body:
I have searched in many different stackOverflow questions and native html documentation and apparantly there's no way to retrieve the value inside a  :

 {this.state.value}

Apparently there's no native way to retrieve the edited value by the user?

In my app:

After the user clicks on the green button, I set the contentEditable attribute to true and hence he is able to edit the right column. However, I've found myself stuck when I wanted to retrieve the new value that the user has typed to send it to the backend!

But this doesn't make any sense, because what's the use of the attribute contentEditable if I cannot retrieve the edited value?

I have only found the onClick listener which I can use to learn when the user has clicked on a particular cell.

PS: I remember in Angular I used to do this easily with two-way data binding..


问:
How to manage time in seconds in text format?
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

```<code>Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub
</code>```

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

答:
Try something like this.</p>

```<code>Sub FixTime()
    Dim t As Double
    Dim s As String
    For Each cell In Range("A1:A10")
        If Left(cell, 3) = "- :" Then
            s = Replace(cell, "- :", "")
            t = Val(s) / 24
            t = t / 3600
            cell.Value = Format(t, "hh:mm:ss")
        Else
            cell.Value = "00" & cell.Value
        End If

    Next
End Sub
</code>```

Body:
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

Body:
Try something like this.

Sub FixTime()
    Dim t As Double
    Dim s As String
    For Each cell In Range("A1:A10")
        If Left(cell, 3) = "- :" Then
            s = Replace(cell, "- :", "")
            t = Val(s) / 24
            t = t / 3600
            cell.Value = Format(t, "hh:mm:ss")
        Else
            cell.Value = "00" & cell.Value
        End If

    Next
End Sub


问:
How to find all files with specific file extensions in a directory in Python
Let's say I have a folder with several files in it with different file types:
.jpg, .jpeg, .png, .tif, .gif, .docx, .pptx, .xlsx, .mp4, .avi, .mpeg, etc.

How should I set up a function that searches for a specific set of file types in a specified directory?

Let's say I only want the image files (i.e. jpg, jpeg, png, tif, and gif).
Or I only want the video files (.mp4, .avi, .mpeg).

Would I have to write a separate function for each of these file types?
Or can I have a single function that searches for image files, video files, etc.?

```<code>import os

def enterFilePath():
    global filepath
    filepath = input("Please enter your file path. ")

enterFilePath()

def enterFileName():
    global name
    name = input("Name the file. "))

enterFileName()

def data_list():
    for elem in os.listdir(filepath):
        if elem.endswith('.jpg'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.jpeg'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.png'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.tif'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.gif'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        else:
            continue
data_list()
</code>```

答:
Collect all your extensions in a dict and then you can just pull them out quickly and easily.  I am using os.cwd() but you can just replace that with your directory.

```<code>import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

# Example on how to search for your extensions and then do something
extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)
</code>```

Body:
Let's say I have a folder with several files in it with different file types:
.jpg, .jpeg, .png, .tif, .gif, .docx, .pptx, .xlsx, .mp4, .avi, .mpeg, etc.

How should I set up a function that searches for a specific set of file types in a specified directory?

Let's say I only want the image files (i.e. jpg, jpeg, png, tif, and gif).
Or I only want the video files (.mp4, .avi, .mpeg).

Would I have to write a separate function for each of these file types?
Or can I have a single function that searches for image files, video files, etc.?

import os

def enterFilePath():
    global filepath
    filepath = input("Please enter your file path. ")

enterFilePath()

def enterFileName():
    global name
    name = input("Name the file. "))

enterFileName()

def data_list():
    for elem in os.listdir(filepath):
        if elem.endswith('.jpg'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.jpeg'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.png'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.tif'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        if elem.endswith('.gif'):
            listItem = elem + '\n'
            listName = filepath + (r"\{}List.txt".format(name))
            writeFile = open(listName, 'a')
            writeFile.write(listItem)
            writeFile.close()
        else:
            continue
data_list()

Body:
Collect all your extensions in a dict and then you can just pull them out quickly and easily.  I am using os.cwd() but you can just replace that with your directory.

import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

# Example on how to search for your extensions and then do something
extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)


问:
binding to width property in code behind
I have a situation where I need to create View box with one button. The xaml for this is as below: Please observe Width property of viewbox. The Width should be increased/decreased according to a slider bar(moving to right increases it, to left decreases it). As listed below I know how to do it in xaml and it works fine. But my requirement is to be able to create viewbox in code behind and assign it the properties.

```<code> <WrapPanel x:Name="_wrpImageButtons" Grid.IsSharedSizeScope="True"
           ScrollViewer.CanContentScroll="True" d:LayoutOverrides="Height"
           Margin="5">
    <Viewbox x:Name="_ScaleButton"
             Width="{Binding Value, ElementName=ZoomSlider}" Stretch="Fill">
         <CustomButton:_uscVCARSImagesButton x:Name="_btnImage1"/>
    </Viewbox>
 </WrapPanel>
</code>```

Thanks.

答:
This should do what you want:</p>

```<code>Viewbox x = new Viewbox();
Binding bnd = new Binding("Value") { ElementName = "ZoomSlider"};
BindingOperations.SetBinding(x, Viewbox.WidthProperty, bnd);
// ... Code to insert the Viewbox into the WrapPanel etc.
</code>```

Body:
I have a situation where I need to create View box with one button. The xaml for this is as below: Please observe Width property of viewbox. The Width should be increased/decreased according to a slider bar(moving to right increases it, to left decreases it). As listed below I know how to do it in xaml and it works fine. But my requirement is to be able to create viewbox in code behind and assign it the properties.

 <WrapPanel x:Name="_wrpImageButtons" Grid.IsSharedSizeScope="True"
           ScrollViewer.CanContentScroll="True" d:LayoutOverrides="Height"
           Margin="5">
    <Viewbox x:Name="_ScaleButton"
             Width="{Binding Value, ElementName=ZoomSlider}" Stretch="Fill">
         <CustomButton:_uscVCARSImagesButton x:Name="_btnImage1"/>
    </Viewbox>
 </WrapPanel>

Thanks.

Body:
This should do what you want:

Viewbox x = new Viewbox();
Binding bnd = new Binding("Value") { ElementName = "ZoomSlider"};
BindingOperations.SetBinding(x, Viewbox.WidthProperty, bnd);
// ... Code to insert the Viewbox into the WrapPanel etc.


问:
Why can't selenium find this seemingly simple element from my xpath?
I'm fairly new to Selenium, but this bug is just knocking my knickers!
I'm trying to code a bot to click the like button on the first 10 photos in my Instagram feed.  I just copied and pasted the XPath of the like button from Chrome, but this XPath won't work for some reason.

Here's the code:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep, strftime
from random import randint

sleep(3)
for x in range(1,10):
    button_like = webdriver.find_element_by_xpath('//*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[{}]/div[2]/section[1]/span[1]/button/span'.format(x))
    button_like.click()
    sleep(randint(2,3))
</code>```

And here's the HTML of the section with the buttons I'm trying to click.

```<code><section class="ltpMr Slqrh">
    <span class="FY9nT fr66n">
        <button class="dCJp8 afkep _0mzm-">
            <span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
        </button>
    </span>
    <span class="_15y0l">
        <button class="dCJp8 afkep _0mzm-">
            <span class="glyphsSpriteComment__outline__24__grey_9 u-__7" aria-label="Comment"></span>
        </button></span>
    <span class="_5e4p">
        <button class="dCJp8 afkep _0mzm-">
            <span class="glyphsSpriteShare__outline__24__grey_9 u-__7" aria-label="Share Post"></span>
        </button>
    </span>
    <span class="wmtNn">
        <button class="dCJp8 afkep _0mzm-">
            <span class="glyphsSpriteSave__outline__24__grey_9 u-__7" aria-label="Save"></span>
        </button>
    </span>
</section>
</code>```

And here's the error message I get:

Traceback (most recent call last):
    File "/Users/JoshSong/Desktop/Liking Your Friend's Photos.py", line 33, in
      button_like = webdriver.find_element_by_xpath('//[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[{}]/div[2]/section[1]/span[1]/button/span'.format(x))
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
      return self.find_element(by=By.XPATH, value=xpath)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
      'value': value})['value']
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
      self.error_handler.check_response(response)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[1]/div[2]/section[1]/span[1]/button/span"}
    (Session info: chrome=76.0.3809.100)

答:
We need more of the HTML to be able to answer the question adequately. For example, with what you provided, one solution would be:

```<code>like_button = driver.find_element_by_xpath("//span[@class='FY9nT fr66n']/button")
like_button.click()
</code>```

Based on the provided HTML, this would click the first button (which is actually an Unlike button from what you provided, but I'm assuming the Like button WAS there). If the span elements surrounding each of the Like buttons you want has the same class, this would only require minor modification:

```<code>like_buttons = driver.find_elements_by_xpath("//span[@class='FY9nT fr66n']/button")
#create maxIndex of the lesser of the length, or the max index you want to press
maxIndex = MIN(9, len(like_buttons))
for i in range (0, maxIndex):
    like_buttons[i].click()
</code>```

This solution should work, assuming the span elements surrounding each Like button are the same AND that that class is not reused on other span elements on the page that are not wrapping Like buttons. If you update the HTML and these assumptions are violated, I would be happy to review a new solution

Body:
I'm fairly new to Selenium, but this bug is just knocking my knickers!
I'm trying to code a bot to click the like button on the first 10 photos in my Instagram feed.  I just copied and pasted the XPath of the like button from Chrome, but this XPath won't work for some reason.

Here's the code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep, strftime
from random import randint

sleep(3)
for x in range(1,10):
    button_like = webdriver.find_element_by_xpath('//*[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[{}]/div[2]/section[1]/span[1]/button/span'.format(x))
    button_like.click()
    sleep(randint(2,3))

And here's the HTML of the section with the buttons I'm trying to click.

        <button class="dCJp8 afkep _0mzm-">

        </button>

        <button class="dCJp8 afkep _0mzm-">

        </button>

        <button class="dCJp8 afkep _0mzm-">

        </button>

        <button class="dCJp8 afkep _0mzm-">

        </button>

And here's the error message I get:

Traceback (most recent call last):
    File "/Users/JoshSong/Desktop/Liking Your Friend's Photos.py", line 33, in
      button_like = webdriver.find_element_by_xpath('//[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[{}]/div[2]/section[1]/span[1]/button/span'.format(x))
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
      return self.find_element(by=By.XPATH, value=xpath)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
      'value': value})['value']
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
      self.error_handler.check_response(response)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//[@id="react-root"]/section/main/section/div[2]/div[1]/div/article[1]/div[2]/section[1]/span[1]/button/span"}
    (Session info: chrome=76.0.3809.100)

Body:
We need more of the HTML to be able to answer the question adequately. For example, with what you provided, one solution would be:

like_button = driver.find_element_by_xpath("//span[@class='FY9nT fr66n']/button")
like_button.click()

Based on the provided HTML, this would click the first button (which is actually an Unlike button from what you provided, but I'm assuming the Like button WAS there). If the span elements surrounding each of the Like buttons you want has the same class, this would only require minor modification:

like_buttons = driver.find_elements_by_xpath("//span[@class='FY9nT fr66n']/button")
#create maxIndex of the lesser of the length, or the max index you want to press
maxIndex = MIN(9, len(like_buttons))
for i in range (0, maxIndex):
    like_buttons[i].click()

This solution should work, assuming the span elements surrounding each Like button are the same AND that that class is not reused on other span elements on the page that are not wrapping Like buttons. If you update the HTML and these assumptions are violated, I would be happy to review a new solution


问:
Best way to deploy nodejs code on docker, how to automatically install node_modules?
Suppose the following simple nodejs docker starter:

```<code>version: '3'
services:
  node:
    container_name: venko_node
    image: node
    restart: always
    volumes:
      - '../src:/usr/src/app/'
    ports:
      - '80:80'
    links:
      - mongo
    working_dir: /usr/src/app
    command: node index.js
</code>```

How can I make sure that node_module packages are installed in the first run?

I thougth of adding the command npm install before node index.js but it will try to install everytime I run. Is it a problem? What if I restart the server and it decides to update a bunch of packages?

Is there a better solution? If not, how can I put npm install before node index.js?

答:
In order to run npm install during image build (and not at the container start) you may want to create your own Dockerfile, it may looks like as follows:

```<code>FROM node

ADD . /usr/src/app
WORKDIR /usr/src/app

RUN npm install

CMD node index.js
</code>```

Then in the docker-compose configuration you need to define build context that is the directory where the Dockerfile is located. For example if the docker-compose config and the Dockerfile are in the same directory setting context to . should be work out:

```<code>version: '3'
services:
  node:
    build:
      context: '.'
    container_name: venko_node
    restart: always
    ports:
      - '80:80'
</code>```

Body:
Suppose the following simple nodejs docker starter:

version: '3'
services:
  node:
    container_name: venko_node
    image: node
    restart: always
    volumes:
      - '../src:/usr/src/app/'
    ports:
      - '80:80'
    links:
      - mongo
    working_dir: /usr/src/app
    command: node index.js

How can I make sure that node_module packages are installed in the first run?

I thougth of adding the command npm install before node index.js but it will try to install everytime I run. Is it a problem? What if I restart the server and it decides to update a bunch of packages?

Is there a better solution? If not, how can I put npm install before node index.js?

Body:
In order to run npm install during image build (and not at the container start) you may want to create your own Dockerfile, it may looks like as follows:

FROM node

ADD . /usr/src/app
WORKDIR /usr/src/app

RUN npm install

CMD node index.js

Then in the docker-compose configuration you need to define build context that is the directory where the Dockerfile is located. For example if the docker-compose config and the Dockerfile are in the same directory setting context to . should be work out:

version: '3'
services:
  node:
    build:
      context: '.'
    container_name: venko_node
    restart: always
    ports:
      - '80:80'


问:
How do I get kotlin-logging (MicroUtils) to print to subclass name instead of abstract class name?
I'm using kotlin-logging (https://github.com/MicroUtils/kotlin-logging), I want my logger to print to subclass name instead of abstract class name. Example I have these class

```<code>// in A.kt file:

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

abstract class A<T> {
    fun someMethod(item: T?) {
        logger.info("testing")
    }
}

fun main() {
    val b: A<String> = B()
    b.someMethod("123")
}

// in B.kt file

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

class B : A<String>() {
}
</code>```

It prints: [main] INFO A - testing

But I want it to print: [main] INFO B - testing  (where B is the subclass name)

答:
If the logger were inside of your abstract Class A, you could use the logger(name: String) method instead of the logger(func: () -> Unit) method like so:

```<code>// in A.kt file

import mu.KotlinLogging

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("testing")
    }
}

fun main() {
    val b: A<String> = B()
    b.someMethod("123")
}

// in B.kt file

class B : A<String>() {
}
</code>```

So that any class that extends A would be logged according to its own class name.

Result: INFO B - testing

Why?
KotlinLogging has two methods, one using the logger(name: String) and one using logger(func: () -> Unit) found here:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/KotlinLogging.kt#L14-L16

The logger(func: () -> Unit) calls the logger(name: String) internally using the class name of the function:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerFactory.kt#L29-L30

In your case, the function call in A.kt is private val logger = KotlinLogging.logger {} is from inside A.kt, never outside that file, so it will always be from A.
so it finds A in this name resolver:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerNameResolver.kt#L15-L23

If we use this code here:

```<code>import mu.KotlinLogging

private val funcJavaClass: String = {}.javaClass.name

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}
</code>```

the result is AKt$funcJavaClass$1 so when we slice the name here:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerNameResolver.kt#L18
the result is simply A

It's also worth noting that the original example uses A because the file name is A, not because of the class.

```<code>// in R.kt

import mu.KotlinLogging

private val funcJavaClass: String = {}.javaClass.name

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}
</code>```

result: RKt$funcJavaClass$1

whereas if the function is called from inside the class

```<code>// in R.kt

import mu.KotlinLogging

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")
    private val funcJavaClass: String = {}.javaClass.name

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}
</code>```

result: A$funcJavaClass$1

Body:
I'm using kotlin-logging (https://github.com/MicroUtils/kotlin-logging), I want my logger to print to subclass name instead of abstract class name. Example I have these class

// in A.kt file:

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

abstract class A<T> {
    fun someMethod(item: T?) {
        logger.info("testing")
    }
}

fun main() {
    val b: A<String> = B()
    b.someMethod("123")
}

// in B.kt file

import mu.KotlinLogging

private val logger = KotlinLogging.logger {}

class B : A<String>() {
}

It prints: [main] INFO A - testing

But I want it to print: [main] INFO B - testing  (where B is the subclass name)

Body:
If the logger were inside of your abstract Class A, you could use the logger(name: String) method instead of the logger(func: () -> Unit) method like so:

// in A.kt file

import mu.KotlinLogging

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("testing")
    }
}

fun main() {
    val b: A<String> = B()
    b.someMethod("123")
}

// in B.kt file

class B : A<String>() {
}

So that any class that extends A would be logged according to its own class name.

Result: INFO B - testing

Why?
KotlinLogging has two methods, one using the logger(name: String) and one using logger(func: () -> Unit) found here:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/KotlinLogging.kt#L14-L16

The logger(func: () -> Unit) calls the logger(name: String) internally using the class name of the function:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerFactory.kt#L29-L30

In your case, the function call in A.kt is private val logger = KotlinLogging.logger {} is from inside A.kt, never outside that file, so it will always be from A.
so it finds A in this name resolver:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerNameResolver.kt#L15-L23

If we use this code here:

import mu.KotlinLogging

private val funcJavaClass: String = {}.javaClass.name

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}

the result is AKt$funcJavaClass$1 so when we slice the name here:
https://github.com/MicroUtils/kotlin-logging/blob/master/src/jvmMain/kotlin/mu/internal/KLoggerNameResolver.kt#L18
the result is simply A

It's also worth noting that the original example uses A because the file name is A, not because of the class.

// in R.kt

import mu.KotlinLogging

private val funcJavaClass: String = {}.javaClass.name

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}

result: RKt$funcJavaClass$1

whereas if the function is called from inside the class

// in R.kt

import mu.KotlinLogging

abstract class A<T> {
    private val logger = KotlinLogging.logger("${this::class.java.name}")
    private val funcJavaClass: String = {}.javaClass.name

    fun someMethod(item: T?) {
        logger.info("$funcJavaClass")
        logger.info("testing")
    }
}

result: A$funcJavaClass$1


问:
Should I use prototypes decorator or there is another way?
I have some code for example. I need to add the logging function to the "fn" function of "Test" class. At the same time it should work as the original function without changes (accept and return the same values), but additionally display "call" in the console. I cannot change the original "Test" class function or the created object. The code can only be written in the designated area. As a result, when I call console.log after "End of code" I should see both the result and the specified "call". Is it possible to do? Can you help or give advice how i can do it?</p>

```<code>class Test {
  constructor(num) {
    this.num = num;
  }

  fn(...numbers) {
    const sum = (a, b) => a + b;
    return this.num + numbers.reduce(sum);
  }
}

// Сode here

// End of code

const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);
</code>```

答:
You can wrap the function on Test.prototype:

```<code>const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
    console.log("Log the call here");
    return original.apply(this, args);
};
</code>```

Live Example:

class Test {
  constructor(num) {
    this.num = num;
  }

  fn(...numbers) {
    const sum = (a, b) => a + b;
    return this.num + numbers.reduce(sum);
  }
}

// Сode here
const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
    console.log("Log the call here");
    return original.apply(this, args);
};
// End of code

const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);```

Note the way I call the original, using apply in order to set this to the correct value.

Body:
I have some code for example. I need to add the logging function to the "fn" function of "Test" class. At the same time it should work as the original function without changes (accept and return the same values), but additionally display "call" in the console. I cannot change the original "Test" class function or the created object. The code can only be written in the designated area. As a result, when I call console.log after "End of code" I should see both the result and the specified "call". Is it possible to do? Can you help or give advice how i can do it?

class Test {
  constructor(num) {
    this.num = num;
  }

  fn(...numbers) {
    const sum = (a, b) => a + b;
    return this.num + numbers.reduce(sum);
  }
}

// Сode here

// End of code

const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);

Body:
You can wrap the function on Test.prototype:

const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
    console.log("Log the call here");
    return original.apply(this, args);
};

Live Example:

class Test {
  constructor(num) {
    this.num = num;
  }

  fn(...numbers) {
    const sum = (a, b) => a + b;
    return this.num + numbers.reduce(sum);
  }
}

// Сode here
const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
    console.log("Log the call here");
    return original.apply(this, args);
};
// End of code

const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);

Note the way I call the original, using apply in order to set this to the correct value.


问:
Problem with window.open in FireFox
I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything.  I understand that solution is very simple, but I think today is not my lucky day :)

Simple example. I try to call a web method from JavaScript and download a file.

Client code:

```<code> <script language="javascript" type="text/javascript">
         function Test() {
             PageMethods.Test(onCompleted);
         }

         function onCompleted(result) {
             window.open(result);
         }
    </script>

........

 <asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

    <div>
     <input type=button value="Download" onclick="Test()"/>

    </div>
</code>```

Server side:

```<code>[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}
</code>```

Folder 'Files' lies in root folder of Web application.

For IE and Chrome, this code is working fine, and I can download the file.  But in Firefox, I get an error:

Server Error in '/' Application.

HTTP Error 400 - Bad Request.

and in url I can see for example:
http://localhost:1406/\Files\test.zip

How can I return the correct path to zip file?

答:
Change the server side code to:

```<code>[System.Web.Services.WebMethod]
public static string Test()
{
    return "/Files/test.zip";
}
</code>```

Web URLs should use forward-slashes instead of backslashes.

Title: Problem with window.open in FireFox

Body:
I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything.  I understand that solution is very simple, but I think today is not my lucky day :)

Simple example. I try to call a web method from JavaScript and download a file.

Client code:

........

 <asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

     <input type=button value="Download" onclick="Test()"/>

Server side:

[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}

Folder 'Files' lies in root folder of Web application.

For IE and Chrome, this code is working fine, and I can download the file.  But in Firefox, I get an error:

Server Error in '/' Application.

HTTP Error 400 - Bad Request.

and in url I can see for example:
http://localhost:1406/\Files\test.zip

How can I return the correct path to zip file?

Body:
Change the server side code to:

[System.Web.Services.WebMethod]
public static string Test()
{
    return "/Files/test.zip";
}

Web URLs should use forward-slashes instead of backslashes.


问:
Radix sort on 38 bits in a uint64?
Question: Is there a "Dial_A_Bit" Radix Sort which can be used to sort on a subset of the bits in a data type?

```<code>uint64 *Radix_Sort_Dial_A_Bit(uint64_t *a, int num_a, int sort_bits);
</code>```

In particular, would a 38 bit sort on 64 bit data be possible and have speed somewhere between the 32/64 and 48/64 varieties shown below?

```<code>uint64 *Radix_Sort_ui64_38MSB(uint64_t *a, int num_a);
</code>```

Note how research into 48 and 32 bit sorts has verified both increased speed and correctness compared to sorting on all 64 bits in a uint64_t[].

It seems as though a Radix_Sort() which sorts on a subset of the data package size would be generally useful and efficient, sorting only what is needed.

There are cases in which results are calculated for each Pixel and need to be sorted. A uint64_t[] is used to hold both the calculation result and the XY location.

26 total bits (13 for X and 13 for Y, 8192 max resolution) are needed to hold the pixel XY coordinates which leaves 38 bits for the data to be sorted.

The entire 64 bit package can be sorted with the Radix_Sort_Uint64().

A faster method is to use a Radix_Sort_Uint48() (see below) so the last 16 bits are not considered in the sort. This sorts all of the data correctly and also sorts 10 of the 13 X coordinate bits which is not needed.

Since performance is almost linearly proportional to bits sorted, optimally, only the 38 most significant bits would be considered in the sort.

Even a 40 bit Radix Sort would be better than using 48 bits. I tried to generalize the working 48 bit Radix Sort to operate on 40 bits but it does not sort correctly.

QSort_uint64_38_msb():

```<code>static inline int comp_uint64_38_msb(const void *a, const void *b)  {
register int64_t ca, cb;
    ca = (*((uint64_t *)a)) >> 26;  // Send 26 LSBs to oblivion
    cb = (*((uint64_t *)b)) >> 26;  // Send 26 LSBs to oblivion
    return((ca > cb) - (ca < cb));  // Calcs to [+1, 0 -1]
}
</code>```

As you can see, the 48 bit sort is significantly faster than the full 64 bits.
The 32 bit sort is almost twice as fast as the full 64 bit. And the qsort is lagging far behind:

```<code>  Time=  2.136 sec =  3.390%, RADIX_SORT_FFFF0000  , hits=4, 0.534 sec each
  Time=  2.944 sec =  4.672%, RADIX_SORT_FFFFFF00  , hits=4, 0.736 sec each
  Time=  4.691 sec =  7.444%, RADIX_SORT_64        , hits=5, 0.938 sec each
  Time= 25.209 sec = 40.010%, QSORT_UINT64_ARRAY   , hits=4, 6.302 sec each
  Time= 26.191 sec = 41.569%, QSORT_UINT64_38_ARRAY, hits=4, 6.548 sec each
</code>```

Linearizing from the 64, 48 and 32 bit results to 38 bits:

```<code>lsf 64  0.938   48  0.736    32  0.534   38   ->  0.6500
</code>```

The 38 bit Radix_Sort could be 35% faster than 64 bit sorting and 17% faster than the 48 bit sort.

Even 40 bits would be quicker, 5 bytes vs 6 processed per uint64.

=========

Fastest yet, 6 of 8 byte sort of uint64[], generalized from:
32 MSbits used to sort uint64

```<code>// #############################################################################
// From: http://ideone.com/JHI0d9
// RadixSort---  for 48 MSB of uint64
typedef union {
    struct {
        uint32_t c6[256];
        uint32_t c5[256];
        uint32_t c4[256];
        uint32_t c3[256];
        uint32_t c2[256];
        uint32_t c1[256];
    };
    uint32_t counts[256 * 6];
}  rscounts6_t;

// #############################################################################
// Patterned off of Radix_Sort_64 but looks only at the 48 MostSigBits
// 0XFFFF-FFFF-FFFF-0000  << Ignore the zeros, sort on 3 MostSigBytes
// Made for RGB48 stuffed into uint64 with 2 LeastSig bytes zero
// Get rid of the 7 and 8 level comps
uint64_t *radix_sort_48_msb(uint64_t *arrayA, uint32_t asize)
{
register uint64_t *array=arrayA;  // Slam arg into Register!
register int ii;  // Loop control

    rscounts6_t counts;
    memset(&counts, 0, 256 * 6 * sizeof(uint32_t));
    uint64_t *cpy = (uint64_t *)malloc(asize * sizeof(uint64_t));
    uint32_t o6=0, o5=0, o4=0, o3=0, o2=0, o1=0;
    uint32_t t6, t5, t4, t3, t2, t1;
    register uint32_t x;
    // calculate counts
    for(x = 0; x < asize; x++) {
        t6 = (array[x] >> 16) & 0xff;
        t5 = (array[x] >> 24) & 0xff;
        t4 = (array[x] >> 32) & 0xff;
        t3 = (array[x] >> 40) & 0xff;
        t2 = (array[x] >> 48) & 0xff;
        t1 = (array[x] >> 56) & 0xff;
        counts.c6[t6]++;
        counts.c5[t5]++;
        counts.c4[t4]++;
        counts.c3[t3]++;
        counts.c2[t2]++;
        counts.c1[t1]++;
    }
    // convert counts to offsets
    for(x = 0; x < 256; x++) {
        t6 = o6 + counts.c6[x];
        t5 = o5 + counts.c5[x];
        t4 = o4 + counts.c4[x];
        t3 = o3 + counts.c3[x];
        t2 = o2 + counts.c2[x];
        t1 = o1 + counts.c1[x];
        counts.c6[x] = o6;
        counts.c5[x] = o5;
        counts.c4[x] = o4;
        counts.c3[x] = o3;
        counts.c2[x] = o2;
        counts.c1[x] = o1;
        o6 = t6;
        o5 = t5;
        o4 = t4;
        o3 = t3;
        o2 = t2;
        o1 = t1;
    }
    // radix
    for(x = 0; x < asize; x++) {
        t6 = (array[x] >> 16) & 0xff;
        cpy[counts.c6[t6]] = array[x];
        counts.c6[t6]++;  }
    for(x = 0; x < asize; x++) {
        t5 = (cpy[x] >> 24) & 0xff;
        array[counts.c5[t5]] = cpy[x];
        counts.c5[t5]++;  }
    for(x = 0; x < asize; x++) {
        t4 = (array[x] >> 32) & 0xff;
        cpy[counts.c4[t4]] = array[x];
        counts.c4[t4]++;  }
    for(x = 0; x < asize; x++) {
        t3 = (cpy[x] >> 40) & 0xff;
        array[counts.c3[t3]] = cpy[x];
        counts.c3[t3]++;  }
    for(x = 0; x < asize; x++) {
        t2 = (array[x] >> 48) & 0xff;
        cpy[counts.c2[t2]] = array[x];
        counts.c2[t2]++;  }
    for(x = 0; x < asize; x++) {
        t1 = (cpy[x] >> 56) & 0xff;
        array[counts.c1[t1]] = cpy[x];
        counts.c1[t1]++;  }
    free(cpy);
    return array;
}  // End radix_sort_48_msb().
</code>```

==================================

Thanks again to Rcgldr for innovative programming suggestion!
Instead of 10, 10, 9, 9, I used the fast 32 bit pattern with [4][10]

It Works, but it is quite a bit slower than the 48 MSB sort, 737 msec for 40 MSBt, 588 msec for 48 MSB. :(

Maybe I coded it poorly.

```<code>    Time=  6.108 sec = 33.668%, QSORT_UINT64_ARRAY   , hits=1
    Time=  3.060 sec = 16.866%, RADIX_SORT_UINT64_REG, hits=4, 0.765 sec each
    Time=  2.947 sec = 16.241%, RADIX_SORT_UINT64_40R, hits=4, 0.737 sec each < SLOW
    Time=  2.354 sec = 12.973%, RADIX_SORT_UINT64_48R, hits=4, 0.588 sec each
    Time=  1.542 sec =  8.498%, RADIX_SORT_UINT64_32R, hits=4, 0.385 sec each
    Time=  0.769 sec =  4.236%, RADIX_SORT_64        , hits=1
</code>```

The test:

create a random, uint64_t[36M] master array

sort it with both qsort and a known good Radix Sort, radixSort() to create a standard array

Comparing Qsort and radixSort() results for identicality.

Sort a copy of the master with 32, 40, 48 and 64 MSB Radix Sorts

Compare each test sort to the Standard after masking off the ignored LSBs

Here is the code:

```<code>    //=============================================================================
// From code submitted by rcgldr, Feb 8 2020
// Optimized to use Registers and to sort on 40 MSBs, ignoring 24 LSBs
void radix_sort_r64_40(uint64_t *pData, uint64_t *pTemp, size_t count,
    EV_TIME_STR *tsa)
{
    size_t mIndex[4][1024] = { 0 };  /* index matrix */
    size_t * pmIndex;                /* ptr to row of matrix */
    size_t i, j, m, n;
    uint64_t u;
    if(tsa)  time_event(E_RADIX_SORT_UINT64_40R, tsa, E_TIME_EVENT, 1, 0);

    for (i = 0; i < count; i++) {       /* generate histograms */
        u = pData[i];
        mIndex[3][(u >> 24) & 0x3ff]++;
        mIndex[2][(u >> 34) & 0x3ff]++;
        mIndex[1][(u >> 44) & 0x3ff]++;
        mIndex[0][(u >> 54) & 0x3ff]++;
    }

    for (j = 0; j < 4; j++) {           /* convert to indices */
        pmIndex = mIndex[j];
        n = 0;
        for (i = 0; i < 1024; i++)  {
            m = pmIndex[i];
            pmIndex[i] = n;
            n += m;
        }
    }

    for (i = 0; i < count; i++)  {  /* radix sort */
        u = pData[i];
        pTemp[mIndex[3][(u >> 24) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pTemp[i];
        pData[mIndex[2][(u >> 34) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pData[i];
        pTemp[mIndex[1][(u >> 44) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pTemp[i];
        pData[mIndex[0][(u >> 54) & 0x3ff]++] = u;
    }
}  // End Radix_Sort_R64_40().
</code>```

Here is the unique dif between the FAST 32 MSB version and the cloned 40 MSB slow version.

```<code>Unique lines from "~/tmp/radix.sort.32.c":
  02) void radix_sort_r64_32(uint64_t *pData, uint64_t *pTemp, size_t count,
  05) size_t mIndex[4][256] = { 0 };      /* index matrix */
  09) if(tsa)  time_event(E_RADIX_SORT_UINT64_32R, tsa, E_TIME_EVENT, 1, 0);
  13) mIndex[3][(u >> 32) & 0xff]++;  // B4
  14) mIndex[2][(u >> 40) & 0xff]++;  // B5
  15) mIndex[1][(u >> 48) & 0xff]++;  // B6
  16) mIndex[0][(u >> 56) & 0xff]++;  // B7
  22) for (i = 0; i < 256; i++) {
  31) pTemp[mIndex[3][(u >> 32) & 0xff]++] = u;
  35) pData[mIndex[2][(u >> 40) & 0xff]++] = u;
  39) pTemp[mIndex[1][(u >> 48) & 0xff]++] = u;
  43) pData[mIndex[0][(u >> 56) & 0xff]++] = u;

Unique lines from "~/tmp/radix.sort.40.c":
  01) void radix_sort_r64_40(uint64_t *pData, uint64_t *pTemp, size_t count,
  04) size_t mIndex[4][1024] = { 0 };  /* index matrix */
  08) if(tsa)  time_event(E_RADIX_SORT_UINT64_40R, tsa, E_TIME_EVENT, 1, 0);
  12) mIndex[3][(u >> 24) & 0x3ff]++;
  13) mIndex[2][(u >> 34) & 0x3ff]++;
  14) mIndex[1][(u >> 44) & 0x3ff]++;
  15) mIndex[0][(u >> 54) & 0x3ff]++;
  21) for (i = 0; i < 1024; i++)  {
  30) pTemp[mIndex[3][(u >> 24) & 0x3ff]++] = u;
  34) pData[mIndex[2][(u >> 34) & 0x3ff]++] = u;
  38) pTemp[mIndex[1][(u >> 44) & 0x3ff]++] = u;
  42) pData[mIndex[0][(u >> 54) & 0x3ff]++] = u;
</code>```

答:
2 more sorting algorithm test results:

```<code>  Time=  6.208 sec = 21.838%, QSORT_UINT64_ARRAY   , hits=1
  Time=  3.358 sec = 11.813%, RADIX_SORT_UINT64_REG, hits=4, 0.840 sec each
  Time=  2.525 sec =  8.884%, RADIX_SORT_UI64_AA99 , hits=4, 0.631 sec each <NEW
  Time=  2.509 sec =  8.825%, RADIX_SORT_UINT64_48R, hits=4, 0.627 sec each
  Time=  2.461 sec =  8.658%, RADIX_SORT_UI64_1024 , hits=4, 0.615 sec each <NEW
  Time=  2.223 sec =  7.822%, RADIX_SORT_UINT64_42R, hits=4, 0.556 sec each
  Time=  2.215 sec =  7.791%, RADIX_SORT_UI64_40_85, hits=4, 0.554 sec each
  Time=  1.930 sec =  6.788%, RADIX_SORT_UINT64_36R, hits=4, 0.482 sec each
  Time=  1.710 sec =  6.014%, RADIX_SORT_UINT64_32R, hits=4, 0.427 sec each
  Time=  0.915 sec =  3.220%, COMP_UINT64_ARRAYS   , hits=32, 0.029 sec each
</code>```

Another run without Firefox hogging the system:

```<code>  Time=  6.156 sec = 23.199%, QSORT_UINT64_ARRAY   , hits=1
  Time=  2.993 sec = 11.277%, RADIX_SORT_UINT64_REG, hits=4, 0.748 sec each
  Time=  2.409 sec =  9.077%, RADIX_SORT_UI64_AA99 , hits=4, 0.602 sec each < NEW
  Time=  2.330 sec =  8.778%, RADIX_SORT_UI64_1024 , hits=4, 0.582 sec each < NEW
  Time=  2.241 sec =  8.443%, RADIX_SORT_UINT64_48R, hits=4, 0.560 sec each
  Time=  2.124 sec =  8.002%, RADIX_SORT_UI64_40_85, hits=4, 0.531 sec each
  Time=  1.982 sec =  7.468%, RADIX_SORT_UINT64_42R, hits=4, 0.495 sec each
  Time=  1.725 sec =  6.499%, RADIX_SORT_UINT64_36R, hits=4, 0.431 sec each
  Time=  1.507 sec =  5.677%, RADIX_SORT_UINT64_32R, hits=4, 0.377 sec each
  Time=  0.889 sec =  3.348%, COMP_UINT64_ARRAYS   , hits=32, 0.028 sec each
</code>```

The RADIX_SORT_UI64_AA99 uses bin bits [10, 10, 9, 9] in 4 passes.

The RADIX_SORT_UI64_1024 sorts by most significant 10 bits first.

The RADIX_SORT_UINT64_42R uses 6 bins of 7 bits each

Note the dueling 40 MSB, 8 bin 5 bit RADIX_SORT_UI64_40_85 and the 42 MSB, 7 bin 6 bit RADIX_SORT_UINT64_42R relative performance.  The 42 MSB sort is often much faster though the 40 bit edges it out at times.

The compiler is GCC, optimized for speed:

```<code>gcc -Ofast -ffast-math -m64 -march=native -funroll-loops -fopenmp -flto -finline-functions -Wuninitialized  ~/bin/pb.c  -lm  -o  ~/bin/pb_a
</code>```

Are there better compiler options?

gcc version 7.4.1 20190905 [gcc-7-branch revision 275407] (SUSE Linux)

==========================

Full Code:

```<code>// =============================================================================
// Sort with bin bits 10, 10, 9,9
// From code by rcgldr StackOverflow Feb 8, 2020
void RadixSort_aa99(uint64_t *a, uint64_t *b, size_t count, EV_TIME_STR *tsa)
{
uint32_t mIndex[4][1024] = { 0 };  /* index matrix */
uint32_t * pmIndex;                /* ptr to row of matrix */
uint32_t i, j, m, n;
uint64_t u;

if(tsa)  time_event(E_RADIX_SORT_UI64_AA99, tsa, E_TIME_EVENT, 1, 0);
for (i = 0; i < count; i++) {       /* generate histograms */
    u = a[i];
    mIndex[3][(u >> 26) & 0x1ff]++;
    mIndex[2][(u >> 35) & 0x1ff]++;
    mIndex[1][(u >> 44) & 0x3ff]++;
    mIndex[0][(u >> 54) & 0x3ff]++;
}

for (j = 0; j < 2; j++) {           /* convert to indices */
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 1024; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}
for (j = 2; j < 4; j++) {
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 512; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}

pmIndex = mIndex[3];
for (i = 0; i < count; i++)  {      /* radix sort */
    u = a[i];
    b[pmIndex[(u >> 26) & 0x1ff]++] = u;
}
pmIndex = mIndex[2];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 35) & 0x1ff]++] = u;
}
pmIndex = mIndex[1];
for (i = 0; i < count; i++)  {
    u = a[i];
    b[pmIndex[(u >> 44) & 0x3ff]++] = u;
}
pmIndex = mIndex[0];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 54) & 0x3ff]++] = u;
}
}

// =============================================================================
/* split array into 1024 bins according to most significant 10 bits */
void RadixSort_1024(uint64_t *a, uint64_t *b, size_t count, EV_TIME_STR *tsa)
{
uint32_t aIndex[1025] = {0};            /* index array */
uint32_t i, m, n;
if(tsa)  time_event(E_RADIX_SORT_UI64_1024, tsa, E_TIME_EVENT, 1, 0);
for(i = 0; i < count; i++)          /* generate histogram */
    aIndex[(a[i] >> 54)]++;
n = 0;                              /* convert to indices */
for (i = 0; i < 1025; i++)  {
    m = aIndex[i];
    aIndex[i] = n;
    n += m;
}
for(i = 0; i < count; i++)          /* sort by ms 10 bits */
    b[aIndex[a[i]>>54]++] = a[i];
for(i = 1024; i; i--)               /* restore aIndex */
    aIndex[i] = aIndex[i-1];
aIndex[0] = 0;
for(i = 0; i < 1024; i++)           /* radix sort the 1024 bins */
    RadixSort3(&b[aIndex[i]], &a[aIndex[i]], aIndex[i+1]-aIndex[i]);
}

void RadixSort3(uint64_t *a, uint64_t *b, size_t count)
{
uint32_t mIndex[3][1024] = { 0 };   /* index matrix */
uint32_t * pmIndex;                 /* ptr to row of matrix */
uint32_t i, j, m, n;
uint64_t u;

for (i = 0; i < count; i++) {       /* generate histograms */
    u = a[i];
    mIndex[2][(u >> 26) & 0x1ff]++;
    mIndex[1][(u >> 35) & 0x1ff]++;
    mIndex[0][(u >> 44) & 0x3ff]++;
}

for (j = 0; j < 1; j++) {           /* convert to indices */
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 1024; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}
for (j = 1; j < 3; j++) {
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 512; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}

pmIndex = mIndex[2];
for (i = 0; i < count; i++)  {      /* radix sort */
    u = a[i];
    b[pmIndex[(u >> 26) & 0x1ff]++] = u;
}
pmIndex = mIndex[1];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 35) & 0x1ff]++] = u;
}
pmIndex = mIndex[0];
for (i = 0; i < count; i++)  {
    u = a[i];
    b[pmIndex[(u >> 44) & 0x3ff]++] = u;
}
}
</code>```

Title: Radix sort on 38 bits in a uint64?

Body:
Question: Is there a "Dial_A_Bit" Radix Sort which can be used to sort on a subset of the bits in a data type?

uint64 *Radix_Sort_Dial_A_Bit(uint64_t *a, int num_a, int sort_bits);

In particular, would a 38 bit sort on 64 bit data be possible and have speed somewhere between the 32/64 and 48/64 varieties shown below?

uint64 *Radix_Sort_ui64_38MSB(uint64_t *a, int num_a);

Note how research into 48 and 32 bit sorts has verified both increased speed and correctness compared to sorting on all 64 bits in a uint64_t[].

It seems as though a Radix_Sort() which sorts on a subset of the data package size would be generally useful and efficient, sorting only what is needed.

There are cases in which results are calculated for each Pixel and need to be sorted. A uint64_t[] is used to hold both the calculation result and the XY location.

26 total bits (13 for X and 13 for Y, 8192 max resolution) are needed to hold the pixel XY coordinates which leaves 38 bits for the data to be sorted.

The entire 64 bit package can be sorted with the Radix_Sort_Uint64().

A faster method is to use a Radix_Sort_Uint48() (see below) so the last 16 bits are not considered in the sort. This sorts all of the data correctly and also sorts 10 of the 13 X coordinate bits which is not needed.

Since performance is almost linearly proportional to bits sorted, optimally, only the 38 most significant bits would be considered in the sort.

Even a 40 bit Radix Sort would be better than using 48 bits. I tried to generalize the working 48 bit Radix Sort to operate on 40 bits but it does not sort correctly.

QSort_uint64_38_msb():

static inline int comp_uint64_38_msb(const void *a, const void *b)  {
register int64_t ca, cb;
    ca = (*((uint64_t *)a)) >> 26;  // Send 26 LSBs to oblivion
    cb = (*((uint64_t *)b)) >> 26;  // Send 26 LSBs to oblivion
    return((ca > cb) - (ca < cb));  // Calcs to [+1, 0 -1]
}

As you can see, the 48 bit sort is significantly faster than the full 64 bits.
The 32 bit sort is almost twice as fast as the full 64 bit. And the qsort is lagging far behind:

  Time=  2.136 sec =  3.390%, RADIX_SORT_FFFF0000  , hits=4, 0.534 sec each
  Time=  2.944 sec =  4.672%, RADIX_SORT_FFFFFF00  , hits=4, 0.736 sec each
  Time=  4.691 sec =  7.444%, RADIX_SORT_64        , hits=5, 0.938 sec each
  Time= 25.209 sec = 40.010%, QSORT_UINT64_ARRAY   , hits=4, 6.302 sec each
  Time= 26.191 sec = 41.569%, QSORT_UINT64_38_ARRAY, hits=4, 6.548 sec each

Linearizing from the 64, 48 and 32 bit results to 38 bits:

lsf 64  0.938   48  0.736    32  0.534   38   ->  0.6500

The 38 bit Radix_Sort could be 35% faster than 64 bit sorting and 17% faster than the 48 bit sort.

Even 40 bits would be quicker, 5 bytes vs 6 processed per uint64.

=========

Fastest yet, 6 of 8 byte sort of uint64[], generalized from:
32 MSbits used to sort uint64

// #############################################################################
// From: http://ideone.com/JHI0d9
// RadixSort---  for 48 MSB of uint64
typedef union {
    struct {
        uint32_t c6[256];
        uint32_t c5[256];
        uint32_t c4[256];
        uint32_t c3[256];
        uint32_t c2[256];
        uint32_t c1[256];
    };
    uint32_t counts[256 * 6];
}  rscounts6_t;

// #############################################################################
// Patterned off of Radix_Sort_64 but looks only at the 48 MostSigBits
// 0XFFFF-FFFF-FFFF-0000  << Ignore the zeros, sort on 3 MostSigBytes
// Made for RGB48 stuffed into uint64 with 2 LeastSig bytes zero
// Get rid of the 7 and 8 level comps
uint64_t *radix_sort_48_msb(uint64_t *arrayA, uint32_t asize)
{
register uint64_t *array=arrayA;  // Slam arg into Register!
register int ii;  // Loop control

    rscounts6_t counts;
    memset(&counts, 0, 256 * 6 * sizeof(uint32_t));
    uint64_t *cpy = (uint64_t *)malloc(asize * sizeof(uint64_t));
    uint32_t o6=0, o5=0, o4=0, o3=0, o2=0, o1=0;
    uint32_t t6, t5, t4, t3, t2, t1;
    register uint32_t x;
    // calculate counts
    for(x = 0; x < asize; x++) {
        t6 = (array[x] >> 16) & 0xff;
        t5 = (array[x] >> 24) & 0xff;
        t4 = (array[x] >> 32) & 0xff;
        t3 = (array[x] >> 40) & 0xff;
        t2 = (array[x] >> 48) & 0xff;
        t1 = (array[x] >> 56) & 0xff;
        counts.c6[t6]++;
        counts.c5[t5]++;
        counts.c4[t4]++;
        counts.c3[t3]++;
        counts.c2[t2]++;
        counts.c1[t1]++;
    }
    // convert counts to offsets
    for(x = 0; x < 256; x++) {
        t6 = o6 + counts.c6[x];
        t5 = o5 + counts.c5[x];
        t4 = o4 + counts.c4[x];
        t3 = o3 + counts.c3[x];
        t2 = o2 + counts.c2[x];
        t1 = o1 + counts.c1[x];
        counts.c6[x] = o6;
        counts.c5[x] = o5;
        counts.c4[x] = o4;
        counts.c3[x] = o3;
        counts.c2[x] = o2;
        counts.c1[x] = o1;
        o6 = t6;
        o5 = t5;
        o4 = t4;
        o3 = t3;
        o2 = t2;
        o1 = t1;
    }
    // radix
    for(x = 0; x < asize; x++) {
        t6 = (array[x] >> 16) & 0xff;
        cpy[counts.c6[t6]] = array[x];
        counts.c6[t6]++;  }
    for(x = 0; x < asize; x++) {
        t5 = (cpy[x] >> 24) & 0xff;
        array[counts.c5[t5]] = cpy[x];
        counts.c5[t5]++;  }
    for(x = 0; x < asize; x++) {
        t4 = (array[x] >> 32) & 0xff;
        cpy[counts.c4[t4]] = array[x];
        counts.c4[t4]++;  }
    for(x = 0; x < asize; x++) {
        t3 = (cpy[x] >> 40) & 0xff;
        array[counts.c3[t3]] = cpy[x];
        counts.c3[t3]++;  }
    for(x = 0; x < asize; x++) {
        t2 = (array[x] >> 48) & 0xff;
        cpy[counts.c2[t2]] = array[x];
        counts.c2[t2]++;  }
    for(x = 0; x < asize; x++) {
        t1 = (cpy[x] >> 56) & 0xff;
        array[counts.c1[t1]] = cpy[x];
        counts.c1[t1]++;  }
    free(cpy);
    return array;
}  // End radix_sort_48_msb().

==================================

Thanks again to Rcgldr for innovative programming suggestion!
Instead of 10, 10, 9, 9, I used the fast 32 bit pattern with [4][10]

It Works, but it is quite a bit slower than the 48 MSB sort, 737 msec for 40 MSBt, 588 msec for 48 MSB. :(

Maybe I coded it poorly.

    Time=  6.108 sec = 33.668%, QSORT_UINT64_ARRAY   , hits=1
    Time=  3.060 sec = 16.866%, RADIX_SORT_UINT64_REG, hits=4, 0.765 sec each
    Time=  2.947 sec = 16.241%, RADIX_SORT_UINT64_40R, hits=4, 0.737 sec each < SLOW
    Time=  2.354 sec = 12.973%, RADIX_SORT_UINT64_48R, hits=4, 0.588 sec each
    Time=  1.542 sec =  8.498%, RADIX_SORT_UINT64_32R, hits=4, 0.385 sec each
    Time=  0.769 sec =  4.236%, RADIX_SORT_64        , hits=1

The test:

create a random, uint64_t[36M] master array

sort it with both qsort and a known good Radix Sort, radixSort() to create a standard array

Comparing Qsort and radixSort() results for identicality.

Sort a copy of the master with 32, 40, 48 and 64 MSB Radix Sorts

Compare each test sort to the Standard after masking off the ignored LSBs

Here is the code:

    //=============================================================================
// From code submitted by rcgldr, Feb 8 2020
// Optimized to use Registers and to sort on 40 MSBs, ignoring 24 LSBs
void radix_sort_r64_40(uint64_t *pData, uint64_t *pTemp, size_t count,
    EV_TIME_STR *tsa)
{
    size_t mIndex[4][1024] = { 0 };  /* index matrix */
    size_t * pmIndex;                /* ptr to row of matrix */
    size_t i, j, m, n;
    uint64_t u;
    if(tsa)  time_event(E_RADIX_SORT_UINT64_40R, tsa, E_TIME_EVENT, 1, 0);

    for (i = 0; i < count; i++) {       /* generate histograms */
        u = pData[i];
        mIndex[3][(u >> 24) & 0x3ff]++;
        mIndex[2][(u >> 34) & 0x3ff]++;
        mIndex[1][(u >> 44) & 0x3ff]++;
        mIndex[0][(u >> 54) & 0x3ff]++;
    }

    for (j = 0; j < 4; j++) {           /* convert to indices */
        pmIndex = mIndex[j];
        n = 0;
        for (i = 0; i < 1024; i++)  {
            m = pmIndex[i];
            pmIndex[i] = n;
            n += m;
        }
    }

    for (i = 0; i < count; i++)  {  /* radix sort */
        u = pData[i];
        pTemp[mIndex[3][(u >> 24) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pTemp[i];
        pData[mIndex[2][(u >> 34) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pData[i];
        pTemp[mIndex[1][(u >> 44) & 0x3ff]++] = u;
    }
    for (i = 0; i < count; i++)  {
        u = pTemp[i];
        pData[mIndex[0][(u >> 54) & 0x3ff]++] = u;
    }
}  // End Radix_Sort_R64_40().

Here is the unique dif between the FAST 32 MSB version and the cloned 40 MSB slow version.

Unique lines from "~/tmp/radix.sort.32.c":
  02) void radix_sort_r64_32(uint64_t *pData, uint64_t *pTemp, size_t count,
  05) size_t mIndex[4][256] = { 0 };      /* index matrix */
  09) if(tsa)  time_event(E_RADIX_SORT_UINT64_32R, tsa, E_TIME_EVENT, 1, 0);
  13) mIndex[3][(u >> 32) & 0xff]++;  // B4
  14) mIndex[2][(u >> 40) & 0xff]++;  // B5
  15) mIndex[1][(u >> 48) & 0xff]++;  // B6
  16) mIndex[0][(u >> 56) & 0xff]++;  // B7
  22) for (i = 0; i < 256; i++) {
  31) pTemp[mIndex[3][(u >> 32) & 0xff]++] = u;
  35) pData[mIndex[2][(u >> 40) & 0xff]++] = u;
  39) pTemp[mIndex[1][(u >> 48) & 0xff]++] = u;
  43) pData[mIndex[0][(u >> 56) & 0xff]++] = u;

Unique lines from "~/tmp/radix.sort.40.c":
  01) void radix_sort_r64_40(uint64_t *pData, uint64_t *pTemp, size_t count,
  04) size_t mIndex[4][1024] = { 0 };  /* index matrix */
  08) if(tsa)  time_event(E_RADIX_SORT_UINT64_40R, tsa, E_TIME_EVENT, 1, 0);
  12) mIndex[3][(u >> 24) & 0x3ff]++;
  13) mIndex[2][(u >> 34) & 0x3ff]++;
  14) mIndex[1][(u >> 44) & 0x3ff]++;
  15) mIndex[0][(u >> 54) & 0x3ff]++;
  21) for (i = 0; i < 1024; i++)  {
  30) pTemp[mIndex[3][(u >> 24) & 0x3ff]++] = u;
  34) pData[mIndex[2][(u >> 34) & 0x3ff]++] = u;
  38) pTemp[mIndex[1][(u >> 44) & 0x3ff]++] = u;
  42) pData[mIndex[0][(u >> 54) & 0x3ff]++] = u;

Body:
2 more sorting algorithm test results:

  Time=  6.208 sec = 21.838%, QSORT_UINT64_ARRAY   , hits=1
  Time=  3.358 sec = 11.813%, RADIX_SORT_UINT64_REG, hits=4, 0.840 sec each
  Time=  2.525 sec =  8.884%, RADIX_SORT_UI64_AA99 , hits=4, 0.631 sec each <NEW
  Time=  2.509 sec =  8.825%, RADIX_SORT_UINT64_48R, hits=4, 0.627 sec each
  Time=  2.461 sec =  8.658%, RADIX_SORT_UI64_1024 , hits=4, 0.615 sec each <NEW
  Time=  2.223 sec =  7.822%, RADIX_SORT_UINT64_42R, hits=4, 0.556 sec each
  Time=  2.215 sec =  7.791%, RADIX_SORT_UI64_40_85, hits=4, 0.554 sec each
  Time=  1.930 sec =  6.788%, RADIX_SORT_UINT64_36R, hits=4, 0.482 sec each
  Time=  1.710 sec =  6.014%, RADIX_SORT_UINT64_32R, hits=4, 0.427 sec each
  Time=  0.915 sec =  3.220%, COMP_UINT64_ARRAYS   , hits=32, 0.029 sec each

Another run without Firefox hogging the system:

  Time=  6.156 sec = 23.199%, QSORT_UINT64_ARRAY   , hits=1
  Time=  2.993 sec = 11.277%, RADIX_SORT_UINT64_REG, hits=4, 0.748 sec each
  Time=  2.409 sec =  9.077%, RADIX_SORT_UI64_AA99 , hits=4, 0.602 sec each < NEW
  Time=  2.330 sec =  8.778%, RADIX_SORT_UI64_1024 , hits=4, 0.582 sec each < NEW
  Time=  2.241 sec =  8.443%, RADIX_SORT_UINT64_48R, hits=4, 0.560 sec each
  Time=  2.124 sec =  8.002%, RADIX_SORT_UI64_40_85, hits=4, 0.531 sec each
  Time=  1.982 sec =  7.468%, RADIX_SORT_UINT64_42R, hits=4, 0.495 sec each
  Time=  1.725 sec =  6.499%, RADIX_SORT_UINT64_36R, hits=4, 0.431 sec each
  Time=  1.507 sec =  5.677%, RADIX_SORT_UINT64_32R, hits=4, 0.377 sec each
  Time=  0.889 sec =  3.348%, COMP_UINT64_ARRAYS   , hits=32, 0.028 sec each

The RADIX_SORT_UI64_AA99 uses bin bits [10, 10, 9, 9] in 4 passes.

The RADIX_SORT_UI64_1024 sorts by most significant 10 bits first.

The RADIX_SORT_UINT64_42R uses 6 bins of 7 bits each

Note the dueling 40 MSB, 8 bin 5 bit RADIX_SORT_UI64_40_85 and the 42 MSB, 7 bin 6 bit RADIX_SORT_UINT64_42R relative performance.  The 42 MSB sort is often much faster though the 40 bit edges it out at times.

The compiler is GCC, optimized for speed:

gcc -Ofast -ffast-math -m64 -march=native -funroll-loops -fopenmp -flto -finline-functions -Wuninitialized  ~/bin/pb.c  -lm  -o  ~/bin/pb_a

Are there better compiler options?

gcc version 7.4.1 20190905 [gcc-7-branch revision 275407] (SUSE Linux)

==========================

Full Code:

// =============================================================================
// Sort with bin bits 10, 10, 9,9
// From code by rcgldr StackOverflow Feb 8, 2020
void RadixSort_aa99(uint64_t *a, uint64_t *b, size_t count, EV_TIME_STR *tsa)
{
uint32_t mIndex[4][1024] = { 0 };  /* index matrix */
uint32_t * pmIndex;                /* ptr to row of matrix */
uint32_t i, j, m, n;
uint64_t u;

if(tsa)  time_event(E_RADIX_SORT_UI64_AA99, tsa, E_TIME_EVENT, 1, 0);
for (i = 0; i < count; i++) {       /* generate histograms */
    u = a[i];
    mIndex[3][(u >> 26) & 0x1ff]++;
    mIndex[2][(u >> 35) & 0x1ff]++;
    mIndex[1][(u >> 44) & 0x3ff]++;
    mIndex[0][(u >> 54) & 0x3ff]++;
}

for (j = 0; j < 2; j++) {           /* convert to indices */
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 1024; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}
for (j = 2; j < 4; j++) {
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 512; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}

pmIndex = mIndex[3];
for (i = 0; i < count; i++)  {      /* radix sort */
    u = a[i];
    b[pmIndex[(u >> 26) & 0x1ff]++] = u;
}
pmIndex = mIndex[2];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 35) & 0x1ff]++] = u;
}
pmIndex = mIndex[1];
for (i = 0; i < count; i++)  {
    u = a[i];
    b[pmIndex[(u >> 44) & 0x3ff]++] = u;
}
pmIndex = mIndex[0];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 54) & 0x3ff]++] = u;
}
}

// =============================================================================
/* split array into 1024 bins according to most significant 10 bits */
void RadixSort_1024(uint64_t *a, uint64_t *b, size_t count, EV_TIME_STR *tsa)
{
uint32_t aIndex[1025] = {0};            /* index array */
uint32_t i, m, n;
if(tsa)  time_event(E_RADIX_SORT_UI64_1024, tsa, E_TIME_EVENT, 1, 0);
for(i = 0; i < count; i++)          /* generate histogram */
    aIndex[(a[i] >> 54)]++;
n = 0;                              /* convert to indices */
for (i = 0; i < 1025; i++)  {
    m = aIndex[i];
    aIndex[i] = n;
    n += m;
}
for(i = 0; i < count; i++)          /* sort by ms 10 bits */
    b[aIndex[a[i]>>54]++] = a[i];
for(i = 1024; i; i--)               /* restore aIndex */
    aIndex[i] = aIndex[i-1];
aIndex[0] = 0;
for(i = 0; i < 1024; i++)           /* radix sort the 1024 bins */
    RadixSort3(&b[aIndex[i]], &a[aIndex[i]], aIndex[i+1]-aIndex[i]);
}

void RadixSort3(uint64_t *a, uint64_t *b, size_t count)
{
uint32_t mIndex[3][1024] = { 0 };   /* index matrix */
uint32_t * pmIndex;                 /* ptr to row of matrix */
uint32_t i, j, m, n;
uint64_t u;

for (i = 0; i < count; i++) {       /* generate histograms */
    u = a[i];
    mIndex[2][(u >> 26) & 0x1ff]++;
    mIndex[1][(u >> 35) & 0x1ff]++;
    mIndex[0][(u >> 44) & 0x3ff]++;
}

for (j = 0; j < 1; j++) {           /* convert to indices */
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 1024; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}
for (j = 1; j < 3; j++) {
    pmIndex = mIndex[j];
    n = 0;
    for (i = 0; i < 512; i++)  {
        m = pmIndex[i];
        pmIndex[i] = n;
        n += m;
    }
}

pmIndex = mIndex[2];
for (i = 0; i < count; i++)  {      /* radix sort */
    u = a[i];
    b[pmIndex[(u >> 26) & 0x1ff]++] = u;
}
pmIndex = mIndex[1];
for (i = 0; i < count; i++)  {
    u = b[i];
    a[pmIndex[(u >> 35) & 0x1ff]++] = u;
}
pmIndex = mIndex[0];
for (i = 0; i < count; i++)  {
    u = a[i];
    b[pmIndex[(u >> 44) & 0x3ff]++] = u;
}
}


答:
You could declare a variable for the div you want to affect and then use the jquery find option to just get the nested div.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');

  //Delcare variable as jquery object and just get the closest div
  var $imageDiv = $el.find('.imagem');
  $imageDiv.fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $imageDiv.fadeIn(500);
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imagem {
  display: none;
}</code>```

GARAGE

  MODEL:
  DOCUMENTS:
  PRICE:

Bugatti

Indeed

$ 320.100

      Motor: 100%

      Chassis: 100%

      Fuel: 10%

Another Car

Indeed

$ 20.000

      Motor: 100%

      Chassis: 100%

      Fuel: 100%

```

Title: How to show only one div with same class then others

Body:
I'm creating a garage system and when my user clicks on a selected item, I wish to show the car picture for it. However the divs that contain the images all have the same class name, so all cars are showing up.

I'm trying to show only the class="imagem" from the selected item (active) not all.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');
  $('.imagem').fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $('.imagem').fadeIn(500);
  }

});

.imagem {
  display: none;
}

GARAGE

  MODEL:
  DOCUMENTS:
  PRICE:

Bugatti

Indeed

$ 320.100

      Motor: 100%

      Chassis: 100%

      Fuel: 10%

Another Car

Indeed

$ 20.000

      Motor: 100%

      Chassis: 100%

      Fuel: 100%

Body:
You could declare a variable for the div you want to affect and then use the jquery find option to just get the nested div.

$(document).on('click', '.item', function() {
  let $el = $(this);
  let isActive = $el.hasClass('active');

  $('.item').removeClass('active');

  //Delcare variable as jquery object and just get the closest div
  var $imageDiv = $el.find('.imagem');
  $imageDiv.fadeOut(500);

  if (!isActive) {
    $el.addClass('active');
    $imageDiv.fadeIn(500);
  }

});

.imagem {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="title">
  <h1>GARAGE</h1>
</div>
<div id="subtitle">
  <span class="sub1">MODEL: </span>
  <span class="sub2">DOCUMENTS:</span>
  <span class="sub3">PRICE:</span>
  </br>
</div>
<div class="item" data-item-name="bugatti">
  <div id="itemname">Bugatti</div>
  <div id="itemqtd">Indeed</div>
  <div id="itempeso">$ 320.100</div>
  <div class="imagem">
    <img style="max-width: 100%; max-height: 132px;" src="http://177.54.152.85/imgallstar/bugatti.png" />
    <div class="status">
      <span class="stat1">Motor: </span><span class="stat2">100%</span></br>
      <span class="stat1">Chassis: </span><span class="stat2">100%</span></br>
      <span class="stat1">Fuel: </span><span class="stat2">10%</span></br>
    </div>
  </div>
</div>
<div class="item" data-item-name="another">
  <div id="itemname">Another Car</div>
  <div id="itemqtd">Indeed</div>
  <div id="itempeso">$ 20.000</div>
  <div class="imagem">
    <img style="max-width: 100%; max-height: 132px;" src="http://177.54.152.85/imgallstar/another.png" />
    <div class="status">
      <span class="stat1">Motor: </span><span class="stat2">100%</span></br>
      <span class="stat1">Chassis: </span><span class="stat2">100%</span></br>
      <span class="stat1">Fuel: </span><span class="stat2">100%</span></br>
    </div>
  </div>
</div>