问:
Can a container in Kubernetes determine its own resource utilization and limits?
How can my containerized app determine its own current resource utilization, as well as the maximum limit allocated by Kubernetes? Is there an API to get this info from cAdvisor and/or Kubelet?

For example, my container is allowed to use maximum 1 core, and it's currently consuming 800 millicores. In this situation, I want to drop/reject all incoming requests that are marked as "low priority".

-How can I see my resource utilization & limit from within my container?

Note that this assumes auto-scaling is not available, e.g. when cluster resources are exhausted, or our app is not allowed to auto-scale (further).

答:
You can use the Kubernetes Downward Api to fetch the limits and requests. The syntax is:</p>

```<code>volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "cpu_limit"
            resourceFieldRef:
              containerName: client-container
              resource: limits.cpu
              divisor: 1m
</code>```

Body:
You can use the Kubernetes Downward Api to fetch the limits and requests. The syntax is:

volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "cpu_limit"
            resourceFieldRef:
              containerName: client-container
              resource: limits.cpu
              divisor: 1m


来源: stackexchange

问:
Creating a nested object with child in a form
I'm a rails noob that's tryin to do something in his app.
My problem is:

I have a Corso model, a Libro model and an Annuncio model. Corso has_many Libro, Libro has_many Annuncio, Annuncio belongs_to Libro and Libro belongs_to Corso. I want a form where the user can create a Libro (that MUST be associated to a Corso) and meanwhile an Annuncio of that Libro must be created. I'm literally freaking out, I saw hundreds of discussions but nothing solved my problem. Every time I change something I get some different errors.

My focus is:
- how to pass the corso_id (I mean, the objects Corso are already defined in the db) to the new Libro when I submit the form;
-I don't see why a Libro object is created (all fields nil) but an Annuncio object doesn't. It seems like the code @libro.annuncios.build in LibroController/new is useless.

I hope you will help me to get this form working.

LibroController:

```<code>class LibroController < ApplicationController
  def new
    @corso = Corso.find(params[:corso_id])
    @libro = @corso.libros.build
    @libro.annuncios.build
  end

  def create
    @corso = Corso.find(params[:corso_id])
    @libro = @corso.libros.build(libro_params)
    if @libro.save
       redirect_to @libro
    else
      redirect_to root_path
    end
  end

  def show
    @libro = Libro.find(params[:id])
  end

  def index
  end

  private
    def libro_params
      params.require(:libro).permit(:titolo, :autori, :casa_editrice, :edizione, :anno_pubblicazione, :ISBN, :immagine, :corso_id, annuncios_attributes[:prezzo, :note])
  end
end
</code>```

AnnuncioController:

```<code>class AnnuncioController < ApplicationController
  def new
    @annuncio = Annuncio.new
  end

  def create
    @libro = Libro.find(params[:libro_id])
    @annuncio = @libro.annuncio.build(annuncio_params)
    if @annuncio.save
      redirect_to @libro
    else
      redirect_to root_path
    end
  end

  private
    def annuncio_params
      params.require(:annuncio).permit(:prezzo, :note)
    end
end
</code>```

Libro Model:

```<code>class Libro < ApplicationRecord
  belongs_to :corso, inverse_of: :libros
  has_many :annuncios, inverse_of: :libro

  accepts_nested_attributes_for :annuncios
end
</code>```

Annuncio Model:

```<code>class Annuncio < ApplicationRecord
  belongs_to :utente, inverse_of: :annuncios
  belongs_to :libro, optional: true, inverse_of:  :annuncios
end
</code>```

Corso Model:

```<code>class Corso < ApplicationRecord
  belongs_to :facolta
  has_many :libros
  validates :nome, uniqueness: true
end
</code>```

routes.rb (a little messed up)

```<code>Rails.application.routes.draw do

  get 'facolta/new'
  get 'sessions/create'
  get 'sessions/destroy'
  get 'users/new'
  get 'corso/index'

  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

  resources :sessions, only: [:create, :destroy]
  resource :home, only: [:show]

  root 'facolta#index'
  get 'corso_new' => 'corso#new'
  get 'libro_new' => 'libro#new'
  get 'about_us' => 'static_pages#about_us'
  get 'faq' => 'static_pages#faq'

  resources :facolta do
    resources :corso
  end

  resources :corsos, shallow: true do
    resources :libro
  end

  resources :libros do
    resources :annuncio
  end

  resources :user do
    resources :annuncio
  end
end
</code>```

views/libro/new

```<code><h1>FORM DI REGISTRAZIONE HERE</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for([@corso, @libro]) do |libro| %>
      <p>
        <%= libro.label :titolo %>
        <%= libro.text_field :titolo %>
      </p>
      <p>
        <%= libro.label :autori %>
        <%= libro.text_field :autori %>
      </p>
      <p>
        <%= libro.label :casa_editrice %>
        <%= libro.text_field :casa_editrice %>
      </p>
      <p>
        <%= libro.label :edizione %>
        <%= libro.text_field :edizione %>
      </p>
      <p>
        <%= libro.label :anno_pubblicazione %>
        <%= libro.text_field :anno_pubblicazione %>
      </p>
      <p>
        <%= libro.label :ISBN %>
        <%= libro.text_field :ISBN %>
      </p>
      <p>
        <%= libro.label :immagine %>
        <%= libro.text_field :immagine %>
      </p>

      <%= libro.fields_for :annuncios do |annuncio| %>
        <p>
          <%= annuncio.label :prezzo %>
          <%= annuncio.text_field :prezzo %>
        </p>
        <p>
          <%= annuncio.label :note %>
          <%= annuncio.text_field :note %>
        </p>
      <% end %>

       <%= libro.hidden_field :corso_id, value: params[:post_id]%>
       <%= libro.submit "Inserisci il libro", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>
</code>```

schema.rb

```<code>  create_table "annuncios", force: :cascade do |t|
    t.integer "user_id"
    t.integer "libro_id"
    t.string "prezzo"
    t.text "note"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["libro_id"], name: "index_annuncios_on_libro_id"
    t.index ["user_id"], name: "index_annuncios_on_user_id"
  end

  create_table "corsos", force: :cascade do |t|
    t.string "nome"
    t.integer "facolta_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["facolta_id"], name: "index_corsos_on_facolta_id"
  end

  create_table "facolta", force: :cascade do |t|
    t.string "nome"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "libros", force: :cascade do |t|
    t.string "titolo"
    t.string "autori"
    t.string "casa_editrice"
    t.string "edizione"
    t.string "anno_pubblicazione"
    t.string "ISBN"
    t.string "immagine"
    t.integer "corso_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["corso_id"], name: "index_libros_on_corso_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "provider"
    t.string "uid"
    t.string "name"
    t.string "oauth_token"
    t.datetime "oauth_expires_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "email"
  end
</code>```

EDIT: edited with @arieljuod advices

答:
You don't need to merge the corso_id here: @libro = @corso.libros.build(libro_params.merge({corso_id: @corso.id})). ActiveRecord already sets the corso_id since you are doing @corso.libros.build(...).

You also don't need that hidden_field with the Corso id since you already have that from the URL.

You may want to do @libro = @corso.libros.build on your new action too.

And finally, I think this is the main problem: this is wrong belongs_to :corso, inverse_of: :corsos, it should be inverse_of: :libros

Fix the other things I point out too to clean up your code.

EDIT:

to add a select do something like this:

```<code>= libro.select :corso_id, options_from_collection_for_select(Corso.all, :id, :name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a rails noob that's tryin to do something in his app.
My problem is:

I have a Corso model, a Libro model and an Annuncio model. Corso has_many Libro, Libro has_many Annuncio, Annuncio belongs_to Libro and Libro belongs_to Corso. I want a form where the user can create a Libro (that MUST be associated to a Corso) and meanwhile an Annuncio of that Libro must be created. I'm literally freaking out, I saw hundreds of discussions but nothing solved my problem. Every time I change something I get some different errors.

My focus is:
- how to pass the corso_id (I mean, the objects Corso are already defined in the db) to the new Libro when I submit the form;
-I don't see why a Libro object is created (all fields nil) but an Annuncio object doesn't. It seems like the code @libro.annuncios.build in LibroController/new is useless.

I hope you will help me to get this form working.

LibroController:

class LibroController < ApplicationController
  def new
    @corso = Corso.find(params[:corso_id])
    @libro = @corso.libros.build
    @libro.annuncios.build
  end

  def create
    @corso = Corso.find(params[:corso_id])
    @libro = @corso.libros.build(libro_params)
    if @libro.save
       redirect_to @libro
    else
      redirect_to root_path
    end
  end

  def show
    @libro = Libro.find(params[:id])
  end

  def index
  end

  private
    def libro_params
      params.require(:libro).permit(:titolo, :autori, :casa_editrice, :edizione, :anno_pubblicazione, :ISBN, :immagine, :corso_id, annuncios_attributes[:prezzo, :note])
  end
end

AnnuncioController:

class AnnuncioController < ApplicationController
  def new
    @annuncio = Annuncio.new
  end

  def create
    @libro = Libro.find(params[:libro_id])
    @annuncio = @libro.annuncio.build(annuncio_params)
    if @annuncio.save
      redirect_to @libro
    else
      redirect_to root_path
    end
  end

  private
    def annuncio_params
      params.require(:annuncio).permit(:prezzo, :note)
    end
end

Libro Model:

class Libro < ApplicationRecord
  belongs_to :corso, inverse_of: :libros
  has_many :annuncios, inverse_of: :libro

  accepts_nested_attributes_for :annuncios
end

Annuncio Model:

class Annuncio < ApplicationRecord
  belongs_to :utente, inverse_of: :annuncios
  belongs_to :libro, optional: true, inverse_of:  :annuncios
end

Corso Model:

class Corso < ApplicationRecord
  belongs_to :facolta
  has_many :libros
  validates :nome, uniqueness: true
end

routes.rb (a little messed up)

Rails.application.routes.draw do

  get 'facolta/new'
  get 'sessions/create'
  get 'sessions/destroy'
  get 'users/new'
  get 'corso/index'

  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

  resources :sessions, only: [:create, :destroy]
  resource :home, only: [:show]

  root 'facolta#index'
  get 'corso_new' => 'corso#new'
  get 'libro_new' => 'libro#new'
  get 'about_us' => 'static_pages#about_us'
  get 'faq' => 'static_pages#faq'

  resources :facolta do
    resources :corso
  end

  resources :corsos, shallow: true do
    resources :libro
  end

  resources :libros do
    resources :annuncio
  end

  resources :user do
    resources :annuncio
  end
end

views/libro/new

FORM DI REGISTRAZIONE HERE

    <%= form_for([@corso, @libro]) do |libro| %>

        <%= libro.label :titolo %>
        <%= libro.text_field :titolo %>

        <%= libro.label :autori %>
        <%= libro.text_field :autori %>

        <%= libro.label :casa_editrice %>
        <%= libro.text_field :casa_editrice %>

        <%= libro.label :edizione %>
        <%= libro.text_field :edizione %>

        <%= libro.label :anno_pubblicazione %>
        <%= libro.text_field :anno_pubblicazione %>

        <%= libro.label :ISBN %>
        <%= libro.text_field :ISBN %>

        <%= libro.label :immagine %>
        <%= libro.text_field :immagine %>

      <%= libro.fields_for :annuncios do |annuncio| %>

          <%= annuncio.label :prezzo %>
          <%= annuncio.text_field :prezzo %>

          <%= annuncio.label :note %>
          <%= annuncio.text_field :note %>

      <% end %>

       <%= libro.hidden_field :corso_id, value: params[:post_id]%>
       <%= libro.submit "Inserisci il libro", class: "btn btn-primary" %>
    <% end %>

schema.rb

  create_table "annuncios", force: :cascade do |t|
    t.integer "user_id"
    t.integer "libro_id"
    t.string "prezzo"
    t.text "note"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["libro_id"], name: "index_annuncios_on_libro_id"
    t.index ["user_id"], name: "index_annuncios_on_user_id"
  end

  create_table "corsos", force: :cascade do |t|
    t.string "nome"
    t.integer "facolta_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["facolta_id"], name: "index_corsos_on_facolta_id"
  end

  create_table "facolta", force: :cascade do |t|
    t.string "nome"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "libros", force: :cascade do |t|
    t.string "titolo"
    t.string "autori"
    t.string "casa_editrice"
    t.string "edizione"
    t.string "anno_pubblicazione"
    t.string "ISBN"
    t.string "immagine"
    t.integer "corso_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["corso_id"], name: "index_libros_on_corso_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "provider"
    t.string "uid"
    t.string "name"
    t.string "oauth_token"
    t.datetime "oauth_expires_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "email"
  end

EDIT: edited with @arieljuod advices

Body:
You don't need to merge the corso_id here: @libro = @corso.libros.build(libro_params.merge({corso_id: @corso.id})). ActiveRecord already sets the corso_id since you are doing @corso.libros.build(...).

You also don't need that hidden_field with the Corso id since you already have that from the URL.

You may want to do @libro = @corso.libros.build on your new action too.

And finally, I think this is the main problem: this is wrong belongs_to :corso, inverse_of: :corsos, it should be inverse_of: :libros

Fix the other things I point out too to clean up your code.

EDIT:

to add a select do something like this:

= libro.select :corso_id, options_from_collection_for_select(Corso.all, :id, :name)


问:
php create certificate signing request into file error/warning
I need to create a certificate signing request to file but last line give error when run:

```<code>Warning: openssl_csr_export_to_file() expects parameter 1 to be resource, boolean given
</code>```

Any idea? this is the code, it's php 7.04 - wamp.

```<code>    <?php
    $subject = array(
    "commonName" => "example.com",
    );
    $private_key = openssl_pkey_new(array(
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
    ));

    $csr = openssl_csr_new($subject, $private_key, array('digest_alg' =>
    'sha384') );
     openssl_pkey_export_to_file($private_key, 'example-priv.key');
     // Along with the subject, the CSR contains the public key corresponding to
     // the private key
    openssl_csr_export_to_file($csr, 'example-csr.pem');
</code>```

答:
Corrected:</p>

```<code>$subject = array(
    "commonName" => "example.com",
);

// vars to make private key
$private_key = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
));

// in config you put path to openssl.cnf
$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$csr = openssl_csr_new($subject , $private_key,  $Configs );

openssl_pkey_export_to_file($private_key, 'priv.key');

// openssl_csr_export_to_file($csr, 'example-csr.pem');
// better to specify path
openssl_csr_export_to_file($csr, 'C:/wamp/example-csr.pem' );

/*
or view it:
openssl_csr_export($csr, $csrout);  //  and var_dump($csrout);
echo $csrout;
*/

</code>```

Body:
I need to create a certificate signing request to file but last line give error when run:

Warning: openssl_csr_export_to_file() expects parameter 1 to be resource, boolean given

Any idea? this is the code, it's php 7.04 - wamp.

    <?php
    $subject = array(
    "commonName" => "example.com",
    );
    $private_key = openssl_pkey_new(array(
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
    ));

    $csr = openssl_csr_new($subject, $private_key, array('digest_alg' =>
    'sha384') );
     openssl_pkey_export_to_file($private_key, 'example-priv.key');
     // Along with the subject, the CSR contains the public key corresponding to
     // the private key
    openssl_csr_export_to_file($csr, 'example-csr.pem');

Body:
Corrected:

$subject = array(
    "commonName" => "example.com",
);

// vars to make private key
$private_key = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
));

// in config you put path to openssl.cnf
$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$csr = openssl_csr_new($subject , $private_key,  $Configs );

openssl_pkey_export_to_file($private_key, 'priv.key');

// openssl_csr_export_to_file($csr, 'example-csr.pem');
// better to specify path
openssl_csr_export_to_file($csr, 'C:/wamp/example-csr.pem' );

/*
or view it:
openssl_csr_export($csr, $csrout);  //  and var_dump($csrout);
echo $csrout;
*/


问:
exclude index.html from service worker cache in create-react-app
I have a reactJs app using create-react-app. The app uses service-worker and other PWA features but somehow I am seeing that despite updating the website or deploying a new build, chrome always picks index.html from service worker and does not make a network call at all.

I think caching the index.html using the service worker is the issue but have not been able to exclude it from getting cached, I did check a few questions on SO and issues on github but could not get a fix for this.

I am using the default service-worker registration

registerServiceWorker.js

```<code>// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {

    if (/*process.env.NODE_ENV === 'production' &&*/ 'serviceWorker' in navigator) {
       // alert('found' + process.env.NODE_ENV);
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
        if (publicUrl.origin !== window.location.origin) {
            // Our service worker won't work if PUBLIC_URL is on a different origin
            // from what our page is served on. This might happen if a CDN is used to
            // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (isLocalhost) {
                // This is running on localhost. Lets check if a service worker still exists or not.
                checkValidServiceWorker(swUrl);
            } else {
                // Is not local host. Just register service worker
                registerValidSW(swUrl);
            }
        });

    } else {
        //alert('not found' + process.env.NODE_ENV);
    }
}

function registerValidSW(swUrl) {
    navigator.serviceWorker
        .register(swUrl)
        .then(registration => {

            registration.onupdatefound = () => {
                const installingWorker = registration.installing;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        if (navigator.serviceWorker.controller) {
                            // At this point, the old content will have been purged and
                            // the fresh content will have been added to the cache.
                            // It's the perfect time to display a "New content is
                            // available; please refresh." message in your web app.
                            console.log('New content is available; please refresh.');
                        } else {
                            // At this point, everything has been precached.
                            // It's the perfect time to display a
                            // "Content is cached for offline use." message.
                            console.log('Content is cached for offline use.');
                        }
                    }
                };
            };
        })
        .catch(error => {
            console.error('Error during service worker registration:', error);
        });
}

function checkValidServiceWorker(swUrl) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl)
        .then(response => {
            // Ensure service worker exists, and that we really are getting a JS file.
            if (
                response.status === 404 ||
                response.headers.get('Content-Type').indexOf('javascript') === -1
            ) {
                // No service worker found. Probably a different app. Reload the page.
                navigator.serviceWorker.ready.then(registration => {
                    registration.unregister().then(() => {
                        window.location.reload();
                    });
                });
            } else {
                // Service worker found. Proceed as normal.
                registerValidSW(swUrl);
            }
        })
        .catch(() => {
            console.log(
                'No internet connection found. App is running in offline mode.'
            );
        });
}

export function unregister() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(registration => {
            registration.unregister();
        });
    }
}
</code>```

Please help.

答:
If you have ejected from create-react-app you can go into /config/webpack.config.js and change the default arguments for GenerateSW() to the following:

```<code>new WorkboxWebpackPlugin.GenerateSW({
          clientsClaim: true,
          exclude: [/\.map$/, /asset-manifest\.json$/, /index.html/],
          importWorkboxFrom: "cdn",
          navigateFallbackBlacklist: [
            // Exclude URLs starting with /_, as they're likely an API call
            new RegExp("^/_"),
            // Exclude URLs containing a dot, as they're likely a resource in
            // public/ and not a SPA route
            new RegExp("/[^/]+\\.[^/]+$")
          ]
</code>```

This way you don't have to manually change your serviceworker.js after every building.

Body:
I have a reactJs app using create-react-app. The app uses service-worker and other PWA features but somehow I am seeing that despite updating the website or deploying a new build, chrome always picks index.html from service worker and does not make a network call at all.

I think caching the index.html using the service worker is the issue but have not been able to exclude it from getting cached, I did check a few questions on SO and issues on github but could not get a fix for this.

I am using the default service-worker registration

registerServiceWorker.js

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {

    if (/*process.env.NODE_ENV === 'production' &&*/ 'serviceWorker' in navigator) {
       // alert('found' + process.env.NODE_ENV);
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
        if (publicUrl.origin !== window.location.origin) {
            // Our service worker won't work if PUBLIC_URL is on a different origin
            // from what our page is served on. This might happen if a CDN is used to
            // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (isLocalhost) {
                // This is running on localhost. Lets check if a service worker still exists or not.
                checkValidServiceWorker(swUrl);
            } else {
                // Is not local host. Just register service worker
                registerValidSW(swUrl);
            }
        });

    } else {
        //alert('not found' + process.env.NODE_ENV);
    }
}

function registerValidSW(swUrl) {
    navigator.serviceWorker
        .register(swUrl)
        .then(registration => {

            registration.onupdatefound = () => {
                const installingWorker = registration.installing;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        if (navigator.serviceWorker.controller) {
                            // At this point, the old content will have been purged and
                            // the fresh content will have been added to the cache.
                            // It's the perfect time to display a "New content is
                            // available; please refresh." message in your web app.
                            console.log('New content is available; please refresh.');
                        } else {
                            // At this point, everything has been precached.
                            // It's the perfect time to display a
                            // "Content is cached for offline use." message.
                            console.log('Content is cached for offline use.');
                        }
                    }
                };
            };
        })
        .catch(error => {
            console.error('Error during service worker registration:', error);
        });
}

function checkValidServiceWorker(swUrl) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl)
        .then(response => {
            // Ensure service worker exists, and that we really are getting a JS file.
            if (
                response.status === 404 ||
                response.headers.get('Content-Type').indexOf('javascript') === -1
            ) {
                // No service worker found. Probably a different app. Reload the page.
                navigator.serviceWorker.ready.then(registration => {
                    registration.unregister().then(() => {
                        window.location.reload();
                    });
                });
            } else {
                // Service worker found. Proceed as normal.
                registerValidSW(swUrl);
            }
        })
        .catch(() => {
            console.log(
                'No internet connection found. App is running in offline mode.'
            );
        });
}

export function unregister() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(registration => {
            registration.unregister();
        });
    }
}

Please help.

Body:
If you have ejected from create-react-app you can go into /config/webpack.config.js and change the default arguments for GenerateSW() to the following:

new WorkboxWebpackPlugin.GenerateSW({
          clientsClaim: true,
          exclude: [/\.map$/, /asset-manifest\.json$/, /index.html/],
          importWorkboxFrom: "cdn",
          navigateFallbackBlacklist: [
            // Exclude URLs starting with /_, as they're likely an API call
            new RegExp("^/_"),
            // Exclude URLs containing a dot, as they're likely a resource in
            // public/ and not a SPA route
            new RegExp("/[^/]+\\.[^/]+$")
          ]

This way you don't have to manually change your serviceworker.js after every building.


问:
How to start with a PHP website?
For a school project I have to produce a website using PHP that allows user to generate there own article or comment on news or others articles. I was wondering how it is best to use the GET function to show the content in an include file and also use the get function for other include files such as the login page and other content the developer (me) has added to website not as articles but as links etc. Anyone got any suggestions or good tutorials they could post up. </p>

答: Wheel has been invented, tested, rolled for a million miles: WordPress

OwnerDisplayName: Cool Hand Luke UK

ContentLicense: CC BY-SA 3.0

Title: How to start with a PHP website?

LastEditorDisplayName: Rex M

OwnerDisplayName: Rex M

ContentLicense: CC BY-SA 2.5


问:
Sticky element to top on scroll
I am trying to make my div appear at the top when the user scrolls down the page, and once the user scrolls to the top, the element should not overlap the nav bar.

I am struggling to implement this, so help would be appreciated. This is what I have tried:

```<code> <div id="floating-sidebar-sticky-wrapper" class="floating-sidebar-wrap" style="height: 696px;">
 <div id="floating-sidebar"></div>
</div>

 <script>
    $(window).on('load',function(){
      $("#floating-sidebar").sticky({ topSpacing: 0, wrapperClassName: "floating-sidebar-wrap" });
    });
  </script>
</code>```

答:
give it a try:
it doesn't use jquery or javascript.

.content-section {
  min-height: 2000px;
}
.sidebar-section {
  position: absolute;
  height: 100%;
  width: 100%;
}

.sidebar-item {
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;

 /* Position the items */
 // &:nth-child(2) { top: 25%; }
 // &:nth-child(3) { top: 50%; }
 // &:nth-child(4) { top: 75%; }
}

.make-me-sticky {
  position: -webkit-sticky;
 position: sticky;
 top: 0;

  padding: 0 15px;
}

/* Ignore This, just coloring */
body {
  background: #fff;
}

article {
  background: white;
  border-radius: 12px;
  padding: 25px 0 600px;
}

.title-section, .content-section, .sidebar-section {
  background: #fff;
  // border-radius: 12px;
  // border: solid 10px #f1f1f1;
}

.title-section {
  text-align: center;
  padding: 50px 15px;
  margin-bottom: 30px;
}

.content-section h2 {
  text-align: center;
  margin: 0;
  padding-top: 200px;
}

.sidebar-item {
  text-align: center;

  h3 {
    background: gold;
    max-width: 100%;
    margin: 0 auto;
    padding: 50px 0 100px;
    border-bottom: solid 1px #fff;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
   <div class="container-fluid">
   <div class="row">
   <div class="col">
   <div class="title-section">
        <h1>Your Navigation Bar</h1>
   </div>
   </div>
   </div>

   <div class="row">
   <div class="col-7">

   <div class="content-section">
        <h2>Your Body Content Section</h2>
   </div>
   </div>
   <div class="col-5">

   <div class="sidebar-item">
   <div class="make-me-sticky">
        <h3>Your Sidebar</h3>
   </div>
   </div>

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

source:codepen

Title: Sticky element to top on scroll

Body:
give it a try:
it doesn't use jquery or javascript.

.content-section {
  min-height: 2000px;
}
.sidebar-section {
  position: absolute;
  height: 100%;
  width: 100%;
}

.sidebar-item {
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;

 /* Position the items */
 // &:nth-child(2) { top: 25%; }
 // &:nth-child(3) { top: 50%; }
 // &:nth-child(4) { top: 75%; }
}

.make-me-sticky {
  position: -webkit-sticky;
 position: sticky;
 top: 0;

  padding: 0 15px;
}

/* Ignore This, just coloring */
body {
  background: #fff;
}

article {
  background: white;
  border-radius: 12px;
  padding: 25px 0 600px;
}

.title-section, .content-section, .sidebar-section {
  background: #fff;
  // border-radius: 12px;
  // border: solid 10px #f1f1f1;
}

.title-section {
  text-align: center;
  padding: 50px 15px;
  margin-bottom: 30px;
}

.content-section h2 {
  text-align: center;
  margin: 0;
  padding-top: 200px;
}

.sidebar-item {
  text-align: center;

  h3 {
    background: gold;
    max-width: 100%;
    margin: 0 auto;
    padding: 50px 0 100px;
    border-bottom: solid 1px #fff;
  }
}

<article>
   <div class="container-fluid">
   <div class="row">
   <div class="col">
   <div class="title-section">
        <h1>Your Navigation Bar</h1>
   </div>
   </div>
   </div>

   <div class="row">
   <div class="col-7">

   <div class="content-section">
        <h2>Your Body Content Section</h2>
   </div>
   </div>
   <div class="col-5">

   <div class="sidebar-item">
   <div class="make-me-sticky">
        <h3>Your Sidebar</h3>
   </div>
   </div>

   </div>
   </div>
   </div>
</article>

source:codepen


问:
How to create a grid in ASP.NET Core MVC using C# in which we insert the record and save the whole data to the database?
I want to create a grid or table that accepts multiple data as we do in ASP.NET webforms.

There will be a form with Name, FName, Class, and Gender fields and textbox including an Add button at the end of the form to add the data in the table/grid.

The grid/table will have the same name columns as the fields name. The grid/table will be below the form and there will be a Save button below the table/grid. When I click on the Save button then the data in table/grid should be saved in the database.

I want to try this in ASP.NET Core MVC using C# with SQL Server at its backend.

I expect the form's data should be added in the table/grid and then I should be able to Save the data in grid/table to Database by clicking on the Save button.

Guys, Do you have any suggestion for this?

答:
You could try using JQuery to get the added data list and send them to the controller.

Here is a simple demo :

Model StudentInfo and StudentViewModel

```<code>public class StudentInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FName { get; set; }
    public string Class { get; set; }
    public string Gender { get; set; }
}

public class StudentViewModel
{
    public  List<StudentInfo> StudentInfos { get; set; }
}
</code>```

Controller

```<code> [HttpPost]
    public async Task<IActionResult> InsertStudents([FromBody]StudentViewModel studentVM)
    {
        List<StudentInfo> model = studentVM.StudentInfos;
        _context.AddRange(model);
        int insertedRecords=await _context.SaveChangesAsync();
        return Json(insertedRecords);

    }
</code>```

The view

```<code><table id="tblStudents" class="table" cellpadding="0" cellspacing="0">
<thead>
    <tr>
        <th style="width:150px">Name</th>
        <th style="width:150px">FName</th>
        <th style="width:150px">Class</th>
        <th style="width:150px">Gender</th>
        <th></th>
    </tr>
</thead>
<tbody>
</tbody>
<tfoot>
    <tr>
        <td><input type="text" id="txtName" /></td>
        <td><input type="text" id="txtFName" /></td>
        <td><input type="text" id="txtClass" /></td>
        <td><input type="text" id="txtGender" /></td>
        <td><input type="button" id="btnAdd" value="Add" /></td>
    </tr>
</tfoot>
</table>
<br />
<input type="button" id="btnSave" value="Save All" />
</code>```

The javascript

```<code>@section Scripts
{
<script type="text/javascript">
$("body").on("click", "#btnAdd", function () {
    //Reference the Name and Country TextBoxes.
    var txtName = $("#txtName");
    var txtFName = $("#txtFName");
    var txtClass = $("#txtClass");
    var txtGender = $("#txtGender");

    //Get the reference of the Table's TBODY element.
    var tBody = $("#tblStudents > TBODY")[0];

    //Add Row.
    var row = tBody.insertRow(-1);

    //Add Name cell.
    var cell = $(row.insertCell(-1));
    cell.html(txtName.val());
    //Add FName cell.
    cell = $(row.insertCell(-1));
    cell.html(txtFName.val());
    //Add Class cell.
    cell = $(row.insertCell(-1));
    cell.html(txtClass.val());
    //Add Gender cell.
    cell = $(row.insertCell(-1));
    cell.html(txtGender.val());

    //Clear the TextBoxes.
    txtName.val("");
    txtFName.val("");
    txtClass.val("");
    txtGender.val("");
});

$("body").on("click", "#btnSave", function () {
    //Loop through the Table rows and build a JSON array.
    var students = new Array();
    $("#tblStudents TBODY TR").each(function () {
        var row = $(this);
        var student = {};
        student.Name = row.find("TD").eq(0).html();
        student.FName = row.find("TD").eq(1).html();
        student.Class = row.find("TD").eq(2).html();
        student.Gender = row.find("TD").eq(3).html();
        students.push(student);
    });

    //Populate invoice data
    var studentVM = {};
    studentVM.StudentInfos = students;

    //Send the JSON array to Controller using AJAX.
    $.ajax({
        type: "POST",
        url: "/StudentInfoes/InsertStudents",
        data: JSON.stringify(studentVM),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r + " record(s) inserted.");
        }
    });
});
</script>
}
</code>```

Body:
You could try using JQuery to get the added data list and send them to the controller.

Here is a simple demo :

Model StudentInfo and StudentViewModel

public class StudentInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FName { get; set; }
    public string Class { get; set; }
    public string Gender { get; set; }
}

public class StudentViewModel
{
    public  List<StudentInfo> StudentInfos { get; set; }
}

Controller

 [HttpPost]
    public async Task<IActionResult> InsertStudents([FromBody]StudentViewModel studentVM)
    {
        List<StudentInfo> model = studentVM.StudentInfos;
        _context.AddRange(model);
        int insertedRecords=await _context.SaveChangesAsync();
        return Json(insertedRecords);

    }

The view

<table id="tblStudents" class="table" cellpadding="0" cellspacing="0">
<thead>
    <tr>
        <th style="width:150px">Name</th>
        <th style="width:150px">FName</th>
        <th style="width:150px">Class</th>
        <th style="width:150px">Gender</th>
        <th></th>
    </tr>
</thead>
<tbody>
</tbody>
<tfoot>
    <tr>
        <td><input type="text" id="txtName" /></td>
        <td><input type="text" id="txtFName" /></td>
        <td><input type="text" id="txtClass" /></td>
        <td><input type="text" id="txtGender" /></td>
        <td><input type="button" id="btnAdd" value="Add" /></td>
    </tr>
</tfoot>
</table>
<br />
<input type="button" id="btnSave" value="Save All" />

The javascript

@section Scripts
{
<script type="text/javascript">
$("body").on("click", "#btnAdd", function () {
    //Reference the Name and Country TextBoxes.
    var txtName = $("#txtName");
    var txtFName = $("#txtFName");
    var txtClass = $("#txtClass");
    var txtGender = $("#txtGender");

    //Get the reference of the Table's TBODY element.
    var tBody = $("#tblStudents > TBODY")[0];

    //Add Row.
    var row = tBody.insertRow(-1);

    //Add Name cell.
    var cell = $(row.insertCell(-1));
    cell.html(txtName.val());
    //Add FName cell.
    cell = $(row.insertCell(-1));
    cell.html(txtFName.val());
    //Add Class cell.
    cell = $(row.insertCell(-1));
    cell.html(txtClass.val());
    //Add Gender cell.
    cell = $(row.insertCell(-1));
    cell.html(txtGender.val());

    //Clear the TextBoxes.
    txtName.val("");
    txtFName.val("");
    txtClass.val("");
    txtGender.val("");
});

$("body").on("click", "#btnSave", function () {
    //Loop through the Table rows and build a JSON array.
    var students = new Array();
    $("#tblStudents TBODY TR").each(function () {
        var row = $(this);
        var student = {};
        student.Name = row.find("TD").eq(0).html();
        student.FName = row.find("TD").eq(1).html();
        student.Class = row.find("TD").eq(2).html();
        student.Gender = row.find("TD").eq(3).html();
        students.push(student);
    });

    //Populate invoice data
    var studentVM = {};
    studentVM.StudentInfos = students;

    //Send the JSON array to Controller using AJAX.
    $.ajax({
        type: "POST",
        url: "/StudentInfoes/InsertStudents",
        data: JSON.stringify(studentVM),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r + " record(s) inserted.");
        }
    });
});
</script>
}


问:
Click event for group header on ag-grid angular
I am using ag-angular-grid in this I have group header and child columns also.
I want to know click event of that group header click.
below how I create header :

```<code>  {
            headerName: "<span id='performanceData'>Performance</span> <i class='fa fa-eye group-open-settings-button' aria-hidden='true' data-group='PerformanceData' ></i>",
            groupId: "PerformanceData",
            marryChildren: false,
            onCellValueChanged:event=>{
                console.log('trst');
            },
            children: [
                {
                    headerName: "Talent Decision",
                    headerTooltip: "Talent Decision",
</code>```

on click   this i wants to open a popup.

any idea?

答:
You will need to create a separate component for your custom group header. This can be done by implementing the IHeaderGroupAngularComp and using headerGroupComponentFramework, as stated on the documentation for the Header Group component.

Here is a rough sketch on how you can get it done.

First and foremost, on your main component that is using ag-grid, we will need to bind the input properties for frameworkComponents, and import your custom header group component.

On the component.html,

```<code><ag-grid-angular style="width: 100%; height: 350px;" class="ag-theme-balham"
  [columnDefs]="columnDefs"
  [frameworkComponents]="frameworkComponents"
  <!-- other properties -->
</ag-grid-angular>
</code>```

On the component.ts, define the component which will be binded to your frameworkComponents, and for your custom header.

```<code>import { CustomHeaderGroupComponent } from '../custom-header-group-component/custom-header-group.component';

constructor() {
  this.frameworkComponents = {
    customHeaderGroupComponent: CustomHeaderGroupComponent,
  };

  this.columnDefs = [
    {
      headerGroupComponent: 'customHeaderGroupComponent',
      // other properties for your group header
    }

  ];
}
</code>```

Do not forget to include your custom header group component on your module.ts too:

```<code>import { CustomHeaderGroupComponent } from "./custom-header-group-component/custom-header-group.component";

@NgModule({
    imports: [
        AgGridModule.withComponents(
            [
              CustomHeaderGroupComponent
            ]
        ),
        // other imports
    ],
    declarations: [
      CustomHeaderGroupComponent,
     // other components
    ],
    // others
})
</code>```

On your custom component.html template for the header group, you can then bind the (click) event to the header to it:

```<code><div (click)="openPopup($event)"><span id='performanceData'>Performance</span> <i class='fa fa-eye group-open-settings-button' aria-hidden='true' data-group='PerformanceData' ></i></div>
</code>```

And on your component.ts for the header group, you can define the openPopup() method:

```<code>import { Component } from '@angular/core';
import { IHeaderGroupAngularComp } from 'ag-grid-angular';
import { IHeaderGroupParams } from 'ag-grid-community';

.
.
.

export class CustomHeaderGroupComponent implements IHeaderGroupAngularComp {
  params: IHeaderGroupParams;

  agInit(params: IHeaderGroupParams) {
    this.params = params;
  }
  .
  .
  openPopup() {
    // handle the rest to enable to opening of the popup
  }

}
</code>```

The full working demo is actually available here, though it is a complete demo for all the features.

Body:
I am using ag-angular-grid in this I have group header and child columns also.
I want to know click event of that group header click.
below how I create header :

  {
            headerName: "Performance ",
            groupId: "PerformanceData",
            marryChildren: false,
            onCellValueChanged:event=>{
                console.log('trst');
            },
            children: [
                {
                    headerName: "Talent Decision",
                    headerTooltip: "Talent Decision",

on click   this i wants to open a popup.

any idea?

Body:
You will need to create a separate component for your custom group header. This can be done by implementing the IHeaderGroupAngularComp and using headerGroupComponentFramework, as stated on the documentation for the Header Group component.

Here is a rough sketch on how you can get it done.

First and foremost, on your main component that is using ag-grid, we will need to bind the input properties for frameworkComponents, and import your custom header group component.

On the component.html,

<ag-grid-angular style="width: 100%; height: 350px;" class="ag-theme-balham"
  [columnDefs]="columnDefs"
  [frameworkComponents]="frameworkComponents"
  <!-- other properties -->
</ag-grid-angular>

On the component.ts, define the component which will be binded to your frameworkComponents, and for your custom header.

import { CustomHeaderGroupComponent } from '../custom-header-group-component/custom-header-group.component';

constructor() {
  this.frameworkComponents = {
    customHeaderGroupComponent: CustomHeaderGroupComponent,
  };

  this.columnDefs = [
    {
      headerGroupComponent: 'customHeaderGroupComponent',
      // other properties for your group header
    }

  ];
}

Do not forget to include your custom header group component on your module.ts too:

import { CustomHeaderGroupComponent } from "./custom-header-group-component/custom-header-group.component";

@NgModule({
    imports: [
        AgGridModule.withComponents(
            [
              CustomHeaderGroupComponent
            ]
        ),
        // other imports
    ],
    declarations: [
      CustomHeaderGroupComponent,
     // other components
    ],
    // others
})

On your custom component.html template for the header group, you can then bind the (click) event to the header to it:

<div (click)="openPopup($event)"><span id='performanceData'>Performance</span> <i class='fa fa-eye group-open-settings-button' aria-hidden='true' data-group='PerformanceData' ></i></div>

And on your component.ts for the header group, you can define the openPopup() method:

import { Component } from '@angular/core';
import { IHeaderGroupAngularComp } from 'ag-grid-angular';
import { IHeaderGroupParams } from 'ag-grid-community';

.
.
.

export class CustomHeaderGroupComponent implements IHeaderGroupAngularComp {
  params: IHeaderGroupParams;

  agInit(params: IHeaderGroupParams) {
    this.params = params;
  }
  .
  .
  openPopup() {
    // handle the rest to enable to opening of the popup
  }

}

The full working demo is actually available here, though it is a complete demo for all the features.


问:
Convert Float to String without losing precision - Java
I want to convert a Float number to String without losing its precision.

When I convert 40075016.68557849 to String, it is being represented as 4.0075016E7.

I need to get it represented exactly as the entered value, that is "40075016.68557849".

I've tried String.valueOf(), Float(40075016.68557849f).toString() but nothing is working in the proper way.

答:
BigDecimal

If you need to maintain your fractional number precisely, you cannot use the floating-point types float/Float and double/Double. Floating-point technology trades away accuracy for speed of execution. And there are limits to the size of numbers they can hold.

Instead use BigDecimal. Much slower but accurate.

```<code>new BigDecimal( "40075016.68557849" )
</code>```

Body:
BigDecimal

If you need to maintain your fractional number precisely, you cannot use the floating-point types float/Float and double/Double. Floating-point technology trades away accuracy for speed of execution. And there are limits to the size of numbers they can hold.

Instead use BigDecimal. Much slower but accurate.

new BigDecimal( "40075016.68557849" )


问:
Eclipse 3.5 Unable to install plugins
I really don't know what's going on with Eclipse 3.5 (3.5.0 or 3.5.1, same issues), but it's been now 2 days that I'm struggling with Eclipse to find a way to make the plugins installation work via the "Install New Software screen"!!! I have visited a lot of forums and blogs, tried many solutions but in vain: each time the current problem disappears and a new one appears.

I'm trying to make it work at my office, so behind proxy. The best advice I got so far is the one regarding the known issue with NTLM proxies: http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies. I put in place the hint, but now I have a new error message: Eclipse cannot find the repositories at all... For instance here is what I get now with the Galileo update site itself:

```<code>org.eclipse.equinox.internal.provisional.p2.core.ProvisionException: No repository found at http://download.eclipse.org/releases/galileo.
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.fail(AbstractRepositoryManager.java:380)
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.loadRepository(AbstractRepositoryManager.java:606)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:92)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.loadMetadataRepository(ProvisioningUtil.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager.doLoadRepository(QueryableMetadataRepositoryManager.java:55)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadRepository(QueryableRepositoryManager.java:195)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadAll(QueryableRepositoryManager.java:108)
    at org.eclipse.equinox.internal.p2.ui.sdk.PreloadingRepositoryHandler$2.run(PreloadingRepositoryHandler.java:71)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
</code>```

Samething with http://download.eclipse.org/eclipse/updates/3.5, or http://download.eclipse.org/tools/mylyn/update/e3.4/ and whatever the site: no one works.

Please somebody help!

PS: Some more details below:

I have the same issue with third party software too... for instance: http://www.epic-ide.org/updates/testing/site.xml.... same error message.

If I go to Preferences > Install / Updates > Available Software Sites, click on whatever the site and on Test Connection I get a ProvisionException with this error message (when I click on details):

Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Server redirected too many  times (20)

the solution is:
add following lines to your eclipse.ini file (before -vmargs):
(verified on 3.5 ; 3.5.1; 3.6.2)

```<code>-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1
</code>```

答:
Its the Windows OS that make the problem. I got the same problem. Then I tried some other app which use JavaVM to connect the internet, and they fails. Try update JRE, you will notice it. If JRE cannot update itself, then there is some socket inaccessibility that prevent internet access apart from using native windows API.
I reinstall Win7 and it fixed the problem.</p>

Title: Eclipse 3.5 Unable to install plugins

Body:
I really don't know what's going on with Eclipse 3.5 (3.5.0 or 3.5.1, same issues), but it's been now 2 days that I'm struggling with Eclipse to find a way to make the plugins installation work via the "Install New Software screen"!!! I have visited a lot of forums and blogs, tried many solutions but in vain: each time the current problem disappears and a new one appears.

I'm trying to make it work at my office, so behind proxy. The best advice I got so far is the one regarding the known issue with NTLM proxies: http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies. I put in place the hint, but now I have a new error message: Eclipse cannot find the repositories at all... For instance here is what I get now with the Galileo update site itself:

org.eclipse.equinox.internal.provisional.p2.core.ProvisionException: No repository found at http://download.eclipse.org/releases/galileo.
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.fail(AbstractRepositoryManager.java:380)
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.loadRepository(AbstractRepositoryManager.java:606)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:92)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.loadMetadataRepository(ProvisioningUtil.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager.doLoadRepository(QueryableMetadataRepositoryManager.java:55)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadRepository(QueryableRepositoryManager.java:195)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadAll(QueryableRepositoryManager.java:108)
    at org.eclipse.equinox.internal.p2.ui.sdk.PreloadingRepositoryHandler$2.run(PreloadingRepositoryHandler.java:71)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

Samething with http://download.eclipse.org/eclipse/updates/3.5, or http://download.eclipse.org/tools/mylyn/update/e3.4/ and whatever the site: no one works.

Please somebody help!

PS: Some more details below:

I have the same issue with third party software too... for instance: http://www.epic-ide.org/updates/testing/site.xml.... same error message.

If I go to Preferences > Install / Updates > Available Software Sites, click on whatever the site and on Test Connection I get a ProvisionException with this error message (when I click on details):

Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Server redirected too many  times (20)

the solution is:
add following lines to your eclipse.ini file (before -vmargs):
(verified on 3.5 ; 3.5.1; 3.6.2)

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1


问:
Flask app can't find module when deployed to azure - works fine locally
Azure gives a module import error but the same code runs perfectly locally.

```<code>2019-05-29T02:50:47.388004719Z: [ERROR]  Traceback (most recent call last):
2019-05-29T02:50:47.388027419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-05-29T02:50:47.388031719Z: [ERROR]      worker.init_process()
2019-05-29T02:50:47.388035419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-05-29T02:50:47.388039419Z: [ERROR]      self.load_wsgi()
2019-05-29T02:50:47.388043019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-05-29T02:50:47.388047119Z: [ERROR]      self.wsgi = self.app.wsgi()
2019-05-29T02:50:47.388050819Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-05-29T02:50:47.388054619Z: [ERROR]      self.callable = self.load()
2019-05-29T02:50:47.388075019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-05-29T02:50:47.388084919Z: [ERROR]      return self.load_wsgiapp()
2019-05-29T02:50:47.388088619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-05-29T02:50:47.388092219Z: [ERROR]      return util.import_app(self.app_uri)
2019-05-29T02:50:47.388095619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-05-29T02:50:47.388099119Z: [ERROR]      __import__(module)
2019-05-29T02:50:47.388102419Z: [ERROR]    File "/home/site/wwwroot/app.py", line 102, in <module>
2019-05-29T02:50:47.388106219Z: [ERROR]      from views.auth import register_user_bp, user_login_bp, user_logout_bp
2019-05-29T02:50:47.388109619Z: [ERROR]    File "/home/site/wwwroot/views/auth.py", line 4, in <module>
2019-05-29T02:50:47.388113619Z: [ERROR]      from Forms import *
2019-05-29T02:50:47.388116919Z: [ERROR]  ModuleNotFoundError: No module named 'Forms'
</code>```

It seems to find one of my custom modules, but not the one in the root directory from a subdirectory. However, it appears to successfully import Config.py from app.py, which are both in the root directory.

The program runs from app.py in the root directory if that is important

I think there is something about the way that gunicorn/WSGI works that I don't understand. I can't figure out what changes the way imports behave.

```<code>project_root
├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations
├── Models.py
├── requirements.txt
├── static
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py
</code>```

I'm not sure why it works fine locally, but can't import from Forms.py when on the webapp. I'm pretty sure it has something to do with the file structure, but I can't figure out what and how to fix it.

答:
Try move the Forms.py to folder views or

add these two line in auth.py

import sys

sys.path.append('../')

to add the '../' path to the PYTHONPATH.

Hope it works.

Body:
Azure gives a module import error but the same code runs perfectly locally.

2019-05-29T02:50:47.388004719Z: [ERROR]  Traceback (most recent call last):
2019-05-29T02:50:47.388027419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-05-29T02:50:47.388031719Z: [ERROR]      worker.init_process()
2019-05-29T02:50:47.388035419Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-05-29T02:50:47.388039419Z: [ERROR]      self.load_wsgi()
2019-05-29T02:50:47.388043019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-05-29T02:50:47.388047119Z: [ERROR]      self.wsgi = self.app.wsgi()
2019-05-29T02:50:47.388050819Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-05-29T02:50:47.388054619Z: [ERROR]      self.callable = self.load()
2019-05-29T02:50:47.388075019Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-05-29T02:50:47.388084919Z: [ERROR]      return self.load_wsgiapp()
2019-05-29T02:50:47.388088619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-05-29T02:50:47.388092219Z: [ERROR]      return util.import_app(self.app_uri)
2019-05-29T02:50:47.388095619Z: [ERROR]    File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-05-29T02:50:47.388099119Z: [ERROR]      __import__(module)
2019-05-29T02:50:47.388102419Z: [ERROR]    File "/home/site/wwwroot/app.py", line 102, in <module>
2019-05-29T02:50:47.388106219Z: [ERROR]      from views.auth import register_user_bp, user_login_bp, user_logout_bp
2019-05-29T02:50:47.388109619Z: [ERROR]    File "/home/site/wwwroot/views/auth.py", line 4, in <module>
2019-05-29T02:50:47.388113619Z: [ERROR]      from Forms import *
2019-05-29T02:50:47.388116919Z: [ERROR]  ModuleNotFoundError: No module named 'Forms'

It seems to find one of my custom modules, but not the one in the root directory from a subdirectory. However, it appears to successfully import Config.py from app.py, which are both in the root directory.

The program runs from app.py in the root directory if that is important

I think there is something about the way that gunicorn/WSGI works that I don't understand. I can't figure out what changes the way imports behave.

project_root
├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations
├── Models.py
├── requirements.txt
├── static
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py

I'm not sure why it works fine locally, but can't import from Forms.py when on the webapp. I'm pretty sure it has something to do with the file structure, but I can't figure out what and how to fix it.


问:
Narrator does not read the text in a TextBlock as expected. Only in the selected TextBox
I have a Visual Studio 2019 solution that contains two projects: a Class Library (Universal Windows) that contains a login Page and a Blank App (Universal Windows) that simply navigates to said login Page.

One of my requirements is that the overall solution must pass an accessibility test. The test involves having Narrator (it must be Narrator) read all of the text on the screen.

My problem is that Narrator only reads the text of the TextBox that has focus when the Page loads. I expected Narrator to read the text in the Image element and TextBlock elements as well. Here is an abridged version of the XAML that I'm using in the Page:

```<code><Page>
    <RelativePanel>
        <Image
             x:Name="Logo"
             AutomationProperties.Name="Logo"/>
        <TextBlock
             x:Name="WelcomeTo"
             x:Uid="WelcomeTo"
             Text="Welcome to" />
        <TextBlock
             x:Name="ServiceName"
             x:Uid="ServiceName"
             Text="Service Name" />
        <TextBox
             x:Name="UserId"
             x:Uid="UserId"
             PlaceholderText="User ID"/>
        <TextBox
             x:Name="Password"
             x:Uid="Password"
             PlaceholderText="Password"/>
        <Button
             x:Name="SignIn"
             x:Uid="SignIn"
             Content="Sign In"/>
        <TextBlock
             x:Name="Footer"
             x:Uid="Footer"
             Text="Footer Text" />
    </RelativePanel>
</Page>
</code>```

As a sanity test, I removed the two TextBox elements to see if focus was the issue. In that case, Narrator did not say any text from the screen. I also tried changing several of the AutomationProperties fields to no avail (i.e. AccessibilityView="Control", LiveSetting="Assertive", etc). I also used the Inspect tool to verify that all of the TextBoxes appeared in the Control view.

Am I missing something?

Any help or suggestions are greatly appreciated. Thank you!

答:
Narrator does not read the text in a  as expected. Only in the selected TextBox

If you want to read the text of TextBlock, please turn Narrator scan mode on. And then use direction key to read the TextBlock you selected on the page.

Open Narrator : Ctrl + Win + Enter

Turn scan model on : CapsLock + Spacebar

Body:
I have a Visual Studio 2019 solution that contains two projects: a Class Library (Universal Windows) that contains a login Page and a Blank App (Universal Windows) that simply navigates to said login Page.

One of my requirements is that the overall solution must pass an accessibility test. The test involves having Narrator (it must be Narrator) read all of the text on the screen.

My problem is that Narrator only reads the text of the TextBox that has focus when the Page loads. I expected Narrator to read the text in the Image element and TextBlock elements as well. Here is an abridged version of the XAML that I'm using in the Page:

<Page>
    <RelativePanel>
        <Image
             x:Name="Logo"
             AutomationProperties.Name="Logo"/>
        <TextBlock
             x:Name="WelcomeTo"
             x:Uid="WelcomeTo"
             Text="Welcome to" />
        <TextBlock
             x:Name="ServiceName"
             x:Uid="ServiceName"
             Text="Service Name" />
        <TextBox
             x:Name="UserId"
             x:Uid="UserId"
             PlaceholderText="User ID"/>
        <TextBox
             x:Name="Password"
             x:Uid="Password"
             PlaceholderText="Password"/>
        <Button
             x:Name="SignIn"
             x:Uid="SignIn"
             Content="Sign In"/>
        <TextBlock
             x:Name="Footer"
             x:Uid="Footer"
             Text="Footer Text" />
    </RelativePanel>
</Page>

As a sanity test, I removed the two TextBox elements to see if focus was the issue. In that case, Narrator did not say any text from the screen. I also tried changing several of the AutomationProperties fields to no avail (i.e. AccessibilityView="Control", LiveSetting="Assertive", etc). I also used the Inspect tool to verify that all of the TextBoxes appeared in the Control view.

Am I missing something?

Any help or suggestions are greatly appreciated. Thank you!


问:
Augury doesn't work when angular's mode is dev
I want to use Augury to debug my angular project, and I have used isDevMode to make sure that the mode is dev, but it doesn't work.

The Augury hint that

This application is running in production mode and therefore cannot be inspected using Augury. If this is an Angular application, please rebuild your application in debug mode or remove the call to enableProdMode().

The project isn't created by angular cli, and Augury can work well with the project created by angular cli in my browser. What is going wrong?

答:
In tscofig.json add the below option

```<code>"angularCompilerOptions": { "debug": true }
</code>```

in main.ts comment out enableProdMode();

```<code>// enableProdMode();
</code>```

Reference : Issue -> Solution

Body:
In tscofig.json add the below option

"angularCompilerOptions": { "debug": true }

in main.ts comment out enableProdMode();

// enableProdMode();

Reference : Issue -> Solution


问:
Convert TSV to CSV, where TSV field has commas in it
I have a TSV with fields that look like:

```<code>name   location   1,2,3,4,5
</code>```

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

```<code>sed 's/,/\w/g'
</code>```

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

```<code>name, location,1 2 3 4 5,
</code>```

Body:
I have a TSV with fields that look like:

name   location   1,2,3,4,5

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

sed 's/,/\w/g'

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

name, location,1 2 3 4 5,

Body:
Depending on your real requirements:

$ awk -F'\t' -v OFS=',' '{for (i=1;i<=NF;i++) $i="\""$i"\""} 1' file
"name","location","1,2,3,4,5"

$ awk -F'\t' -v OFS=',' '{for (i=1;i<=NF;i++) gsub(OFS," ",$i); $1=$1} 1' file
name,location,1 2 3 4 5

$ awk -F'\t' -v OFS=',' '{for (i=1;i<=NF;i++) gsub(OFS," ",$i); $(NF+1)=""} 1' file
name,location,1 2 3 4 5,

$ echo 'a"b' | awk -F'\t' -v OFS=',' '{for (i=1;i<=NF;i++) { gsub(/"/,"\"\"",$i); $i="\""$i"\"" } } 1'
"a""b"


问:
AWS - Search all faces in an image against collection
SearchFacesByImage API takes only the the largest face in the image and searches against the collectionId. I want to search all the faces in the input image against the collectionId

On the API of SearchFacesByImage It's write: "To search for all faces in an input image, you might first call the operation, and then use the face IDs returned in subsequent calls to the operation."
But i don't understand what i have to do.

答:
The documentation you are reading appears to have a missing function name.

For example, the boto3 documentation for search_faces_by_image() reads exactly as you have quoted.

Fortunately, the official SearchFacesByImage API documentation has the full text of the paragraph:

To search for all faces in an input image, you might first call the IndexFaces operation, and then use the face IDs returned in subsequent calls to the SearchFaces operation.

This makes a lot more sense!

It is saying that you could call IndexFaces to convert multiple faces in an image into a list of Face IDs. Then, you could loop through each of those Face IDs and call SearchFaces, passing in the Face ID.


问:
Making new dataframes from old dataframes by column number
I'm trying to re-organize my dataframes by Column orders

for Example

```<code>x <- data.frame("A" = c(1,1), "B" = c(2,2), "C" = c(3,3))
y <- data.frame("A" = c(2,2), "B" = c(3,3), "C" = c(4,4))
z <- data.frame("A" = c(3,3), "B" = c(4,4), "C" = c(5,5))
</code>```

Say I have dataframes as above.
What I want to do is make new dataframes by column orders of those above dataframes. (Simply put, I want to put all the "A"s ,"B"s and "C"s, to 3 new dataframes.

the below dataframes are my wanted results

```<code>a <-  data.frame("A" = c(1,1), "A" = c(2,2), "A" = c(3,3))
b <- data.frame("B" = c(2,2), "B" = c(3,3), "B" = c(4,4))
c <- data.frame("C" = c(3,3), "C" = c(4,4), "C" = c(5,5))
</code>```

答:
We can do this with tidyverse

```<code>library(tidyverse)
list(x, y, z) %>%
     transpose %>%
     map(~ do.call(cbind, .x))
</code>```

Or with base R

```<code>lapply(names(x), function(nm) cbind(x[, nm], y[, nm], z[, nm]))
</code>```

Body:
I'm trying to re-organize my dataframes by Column orders

for Example

x <- data.frame("A" = c(1,1), "B" = c(2,2), "C" = c(3,3))
y <- data.frame("A" = c(2,2), "B" = c(3,3), "C" = c(4,4))
z <- data.frame("A" = c(3,3), "B" = c(4,4), "C" = c(5,5))

Say I have dataframes as above.
What I want to do is make new dataframes by column orders of those above dataframes. (Simply put, I want to put all the "A"s ,"B"s and "C"s, to 3 new dataframes.

the below dataframes are my wanted results

a <-  data.frame("A" = c(1,1), "A" = c(2,2), "A" = c(3,3))
b <- data.frame("B" = c(2,2), "B" = c(3,3), "B" = c(4,4))
c <- data.frame("C" = c(3,3), "C" = c(4,4), "C" = c(5,5))

Body:
We can do this with tidyverse

library(tidyverse)
list(x, y, z) %>%
     transpose %>%
     map(~ do.call(cbind, .x))

Or with base R

lapply(names(x), function(nm) cbind(x[, nm], y[, nm], z[, nm]))


问:
Bootstrap div- align to center of page
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

```<code><div class="panel-group col-sm-6" style="float: none;">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>
</code>```

答:
You can align a div to center of the page using the CSS. Following CSS works for me. You can try using this CSS.

.col-sm-6 {
          position: absolute;
   margin: auto;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   width: 100px;
   height: 100px;
   background-color: #ccc;
   border-radius: 3px;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel-group col-sm-6">
   <div class="panel panel-default">
  <div class="panel-heading">
            <h5 class="card-title">test</h5>
         </div>
         <div class="panel-body">
            <p class="card-text">test</p>
         </div>
   </div>
</div></code>```

Title: Bootstrap div- align to center of page

Body:
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

test

test

Body:
You can align a div to center of the page using the CSS. Following CSS works for me. You can try using this CSS.

.col-sm-6 {
          position: absolute;
   margin: auto;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   width: 100px;
   height: 100px;
   background-color: #ccc;
   border-radius: 3px;
   text-align: center;
}

<div class="panel-group col-sm-6">
   <div class="panel panel-default">
  <div class="panel-heading">
            <h5 class="card-title">test</h5>
         </div>
         <div class="panel-body">
            <p class="card-text">test</p>
         </div>
   </div>
</div>


问:
What all should an expert C#/.Net/WPF developer know?
I have some 5+ years' background in C++/Unix development. I have been trying my hand at C#/.Net/WPF based software development for some time now. I am at a stage where I can write functioning applications fluently, but am not sure how to take my skills to the next level.

So, my question(s) to you all, especially to those who are experienced in C#/.Net/WPF:

What are the component skills and knowledge that an expert developer on this platform should have?

What technology-specific books would you expect a would-be expert to have read?

What other deliberate steps can I take to become really good at application development using C#/.Net/WPF?

Many thanks in advance! I would be especially grateful for comprehensive answers - I'm pretty sure many other developers have similar questions.

答:
I would add unit testing, TDD, and mocking frameworks to your list of things to know.

I have "The Art of Unit Testing"  and found it helpful.


问:
Print percentage of task completed from foreach loop
I am processing a file content using a foeach loop in unix environment and I would like to print the percentage of task completed in a single line on the xterm. something like an increasing counter.

```<code>foreach xxx (`cat file1`)
 set total = `wc -l file1`
 # count definination
 # print percentage completed => count/total
end
</code>```

Content of file1 is some test in a single column

```<code>aaa
bbb
ccc
ddd
</code>```

Output expected is

```<code>> 25%
> 50%
</code>```

updated numbers overwrite the previous status on the same line. something like a live ticker

答:
This is what I have discovered that satisfies my requirements </p>

```<code>set ccc = 0
foreach xxx ( `cat file1 ` )
set nnn = ` wc -l file1`
set ccc = `expr $ccc + 1`
echo $ccc $nnn | awk '{printf ("\r%-5s completed out of %s",$1,$2)}'
end
</code>```

<p>The key element that worked for me is '\r' option in the print command, this option would replace the text on the current line. </p>

Body:
I am processing a file content using a foeach loop in unix environment and I would like to print the percentage of task completed in a single line on the xterm. something like an increasing counter.

foreach xxx (`cat file1`)
 set total = `wc -l file1`
 # count definination
 # print percentage completed => count/total
end

Content of file1 is some test in a single column

aaa
bbb
ccc
ddd

Output expected is

> 25%
> 50%

updated numbers overwrite the previous status on the same line. something like a live ticker

Body:
This is what I have discovered that satisfies my requirements

set ccc = 0
foreach xxx ( `cat file1 ` )
set nnn = ` wc -l file1`
set ccc = `expr $ccc + 1`
echo $ccc $nnn | awk '{printf ("\r%-5s completed out of %s",$1,$2)}'
end

The key element that worked for me is '\r' option in the print command, this option would replace the text on the current line.


问:
How to loop multiple axvspan shades for recurring events?
I am trying to loop 2 time series, on the same plot, and mark the condition they were collected in as an axvspan block.
The data looks something like this:

```<code>    time    seriesA sereiesB    Condition
0.00    10  2   A
0.12    4   20  A
0.24    14  16  A
0.36    5   16  A
0.48    8   13  A
0.6     5   16  B
0.72    17  3   B
0.84    8   20  B
0.96    3   3   B
1.08    18  20  C
1.20    11  13  C
1.32    8   10  C
1.44    17  11  A
1.56    15  2   A
1.68    1   1   A
1.8     20  2   A
1.92    11  19  B
2.04    8   13  B
2.16    5   8   B
2.28    14  18  B
2.40    7   2   B
2.52    12  5   C
2.64    4   11  C
2.76    1   13  C
2.88    16  9   C
3       14  17  C
</code>```

I would like to look something like this:
shaded time-series example

答:
You need to save the beginning and end of each region of colors and then using matplotlib.axvspan, color these regions. For instance, here assuming the following dataframe:

```<code>import matplotlib.pyplot as plt
import numpy as np
df = {'time': [0.00,0.12,0.24,0.36, 0.48],
  'A':[10,4,14,5,8],
  'B':[2,20,16,16,13],
  'C':['A','A','B','C','A']}
A = []
B = []
C = []
for i in range(1,len(df)+1):
    if i== len(df)+1:
        df['time'][i] = 0.48
    elif df['C'][i] == 'A':
        A.append([df['time'][i-1], df['time'][i]])
    elif df['C'][i] == 'B':
        B.append([df['time'][i-1], df['time'][i]])
    else:
        C.append([df['time'][i-1], df['time'][i]])
</code>```

Now begining and end of each region is saved in each array (A, B, C) and you can plot these regions using

```<code>plt.plot(df['time'], df['A'])
plt.plot(df['time'], df['B'])
for i in A:
    plt.axvspan(i[0],i[1], facecolor='orange', alpha=0.5)
for i in B:
    plt.axvspan(i[0],i[1], facecolor='crimson', alpha=0.5)
for i in C:
    plt.axvspan(i[0],i[1], facecolor='lavender', alpha=0.5)
plt.show()
plt.savefig('x.png')
</code>```

Body:
I am trying to loop 2 time series, on the same plot, and mark the condition they were collected in as an axvspan block.
The data looks something like this:

    time    seriesA sereiesB    Condition
0.00    10  2   A
0.12    4   20  A
0.24    14  16  A
0.36    5   16  A
0.48    8   13  A
0.6     5   16  B
0.72    17  3   B
0.84    8   20  B
0.96    3   3   B
1.08    18  20  C
1.20    11  13  C
1.32    8   10  C
1.44    17  11  A
1.56    15  2   A
1.68    1   1   A
1.8     20  2   A
1.92    11  19  B
2.04    8   13  B
2.16    5   8   B
2.28    14  18  B
2.40    7   2   B
2.52    12  5   C
2.64    4   11  C
2.76    1   13  C
2.88    16  9   C
3       14  17  C

I would like to look something like this:
shaded time-series example

Body:
You need to save the beginning and end of each region of colors and then using matplotlib.axvspan, color these regions. For instance, here assuming the following dataframe:

import matplotlib.pyplot as plt
import numpy as np
df = {'time': [0.00,0.12,0.24,0.36, 0.48],
  'A':[10,4,14,5,8],
  'B':[2,20,16,16,13],
  'C':['A','A','B','C','A']}
A = []
B = []
C = []
for i in range(1,len(df)+1):
    if i== len(df)+1:
        df['time'][i] = 0.48
    elif df['C'][i] == 'A':
        A.append([df['time'][i-1], df['time'][i]])
    elif df['C'][i] == 'B':
        B.append([df['time'][i-1], df['time'][i]])
    else:
        C.append([df['time'][i-1], df['time'][i]])

Now begining and end of each region is saved in each array (A, B, C) and you can plot these regions using

plt.plot(df['time'], df['A'])
plt.plot(df['time'], df['B'])
for i in A:
    plt.axvspan(i[0],i[1], facecolor='orange', alpha=0.5)
for i in B:
    plt.axvspan(i[0],i[1], facecolor='crimson', alpha=0.5)
for i in C:
    plt.axvspan(i[0],i[1], facecolor='lavender', alpha=0.5)
plt.show()
plt.savefig('x.png')


问:
pasting a large amount of text into the clojure repl running in tmux results in errors and mixed up text
I'm having trouble pasting multiple function definitions into the clojure repl running in tmux. (the general case is pasting over a large amount of code)

When I manually paste the following clojure definitions (as one paste operation) into the clojure repl not running in tmux it pastes over fine.

But when pasting from tslime or directly into tmux running the clojure repl, some of the final defs get their text garbled and only some of the definitions get completed properly. (gets screwy around the make-exponentiation def)

Anyone else experience this or have any ideas on what might be going on?

```
<code>
; Some expiriments and exercises for
; Lecture 3B of SICP

(ns deriv)

(defn variable?
  [x]
  (symbol? x))

(defn same-variable?
  [v1 v2]
  (and (variable? v1) (variable? v2) (= v1 v2)))

(defn sum?
  [x]
  (and (seq? x) (= (first x) '+)))

(defn make-sum
  [a1 a2]
  (cond
    (= a1 0) a2
    (= a2 0) a1
    (and (number? a1) (number? a2)) (+ a1 a2)
    :else (list '+ a1 a2)))

(defn make-product
  [a1 a2]
  (cond
    (or (= a1 0) (= a2 0)) 0
    (= a1 1) a2
    (= a2 1) a1
    (and (number? a1) (number? a2)) (* a1 a2)
    :else (list '* a1 a2)))

(defn product?
  [x]
  (and (seq? x) (= (first x) '*)))

(defn addend
  [[op addend & augend]]
    addend)

(defn augend
  [[op addend & augend]]
  (if (next augend)
    (conj augend '+)
    (first augend)))

(defn multiplier
  [[op multiplier & multiplicand]]
    multiplier)

(defn multiplicand
  [[op multiplier & multiplicand]]
  (if (next multiplicand)
    (conj multiplicand '*)
    (first multiplicand)))

(defn exponentiation?
  [x]
  (and (seq? x) (= (first x) '**)))

(defn base
  [[op base exponent]]
  base)

(defn exponent
  [[op base exponent]]
  exponent)

(defn make-exponentiation
  [base exponent]
  (cond
    (= exponent 0) 1
    (= exponent 1) base
    :else (list '** base exponent)))

(defn deriv
  [exp var]
  (cond
    (number? exp) 0
    (variable? exp) (if
                      (same-variable? exp var)
                      1
                      0)
    (sum? exp) (make-sum
                 (deriv (addend exp) var)
                 (deriv (augend exp) var))
    (product? exp) (make-sum
                     (make-product (multiplier exp)
                                   (deriv (multiplicand exp) var))
                     (make-product (multiplicand exp)
                                   (deriv (multiplier exp) var)))
    (exponentiation? exp) (make-product
                            (deriv (base exp) var)
                            (make-product
                              (exponent exp)
                              (make-exponentiation
                                (base exp)
                                (- (exponent exp) 1))))
    :else
      (throw (Exception. (str "unknown expression type -- DERIV " exp)))))

</code>
```

答:
I use tmux almost daily.  I normally use emacs + swank/slime and don't have issues.  JLine seems to avoid this issue as well.  I tried rlwrap instead and noticed similar behavior.  This most certainly seems to be an rlwrap issue.  If you want to keep the same REPL you are using I suggest giving JLine a try.  You just need to download the jar and put it in your path or declare it as a Leiningen dependency.  You can then start a REPL up with JLine support like so:

```<code>java -cp "lib/*:lib/dev/*" jline.ConsoleRunner clojure.main
</code>```

After that you should be good to go.

Body:
I'm having trouble pasting multiple function definitions into the clojure repl running in tmux. (the general case is pasting over a large amount of code)

When I manually paste the following clojure definitions (as one paste operation) into the clojure repl not running in tmux it pastes over fine.

But when pasting from tslime or directly into tmux running the clojure repl, some of the final defs get their text garbled and only some of the definitions get completed properly. (gets screwy around the make-exponentiation def)

Anyone else experience this or have any ideas on what might be going on?

; Some expiriments and exercises for
; Lecture 3B of SICP

(ns deriv)

(defn variable?
  [x]
  (symbol? x))

(defn same-variable?
  [v1 v2]
  (and (variable? v1) (variable? v2) (= v1 v2)))

(defn sum?
  [x]
  (and (seq? x) (= (first x) '+)))

(defn make-sum
  [a1 a2]
  (cond
    (= a1 0) a2
    (= a2 0) a1
    (and (number? a1) (number? a2)) (+ a1 a2)
    :else (list '+ a1 a2)))

(defn make-product
  [a1 a2]
  (cond
    (or (= a1 0) (= a2 0)) 0
    (= a1 1) a2
    (= a2 1) a1
    (and (number? a1) (number? a2)) (* a1 a2)
    :else (list '* a1 a2)))

(defn product?
  [x]
  (and (seq? x) (= (first x) '*)))

(defn addend
  [[op addend & augend]]
    addend)

(defn augend
  [[op addend & augend]]
  (if (next augend)
    (conj augend '+)
    (first augend)))

(defn multiplier
  [[op multiplier & multiplicand]]
    multiplier)

(defn multiplicand
  [[op multiplier & multiplicand]]
  (if (next multiplicand)
    (conj multiplicand '*)
    (first multiplicand)))

(defn exponentiation?
  [x]
  (and (seq? x) (= (first x) '**)))

(defn base
  [[op base exponent]]
  base)

(defn exponent
  [[op base exponent]]
  exponent)

(defn make-exponentiation
  [base exponent]
  (cond
    (= exponent 0) 1
    (= exponent 1) base
    :else (list '** base exponent)))

(defn deriv
  [exp var]
  (cond
    (number? exp) 0
    (variable? exp) (if
                      (same-variable? exp var)
                      1
                      0)
    (sum? exp) (make-sum
                 (deriv (addend exp) var)
                 (deriv (augend exp) var))
    (product? exp) (make-sum
                     (make-product (multiplier exp)
                                   (deriv (multiplicand exp) var))
                     (make-product (multiplicand exp)
                                   (deriv (multiplier exp) var)))
    (exponentiation? exp) (make-product
                            (deriv (base exp) var)
                            (make-product
                              (exponent exp)
                              (make-exponentiation
                                (base exp)
                                (- (exponent exp) 1))))
    :else
      (throw (Exception. (str "unknown expression type -- DERIV " exp)))))

Body:
I use tmux almost daily.  I normally use emacs + swank/slime and don't have issues.  JLine seems to avoid this issue as well.  I tried rlwrap instead and noticed similar behavior.  This most certainly seems to be an rlwrap issue.  If you want to keep the same REPL you are using I suggest giving JLine a try.  You just need to download the jar and put it in your path or declare it as a Leiningen dependency.  You can then start a REPL up with JLine support like so:

java -cp "lib/*:lib/dev/*" jline.ConsoleRunner clojure.main

After that you should be good to go.