问:
Uncaught TypeError. indexOf is not a function error
I am a rookie and trying to create js script to hide and make visible sections on a webpage. The previous parts seem to be working fine. The last part of the snippet returns this error:

```<code>scripts.js:29 Uncaught TypeError: sections.indexOf is not a function
    at nextSection (scripts.js:29)
    at <anonymous>:1:1
</code>```

Can anyone tell me what I am not getting here?

```<code>/*
============================================
array of all sections
============================================
*/
var sections=document.querySelectorAll("section");

/*
============================================
Function to find the section that is being displayed (the one that doesn't have "not1st" as a class.)
============================================
*/

function findSection(){
for (var i=0; i<sections.length; i++) {
    if (sections[i].className.includes("not1st")){
        continue;
    } else {
        return sections[i];
    }}}

/*
============================================
Function to load the next section
============================================
*/

function nextSection() {
   sections[sections.indexOf(findSection())+1];
}
</code>```

答:
querySelectorAll doesn't return an array, it returns a NodeList. NodeLists don't have an indexOf function.

You can convert it to an array using Array.from:

```<code>var sections = Array.from(document.querySelectorAll("section"));
</code>```

...or for older browsers without Array.from, Array#slice:

```<code>var sections = Array.prototype.slice.call(document.querySelectorAll("section"));
</code>```

For more information, see the "For Array-Like Objects" part of my other answer here.

Body:
I am a rookie and trying to create js script to hide and make visible sections on a webpage. The previous parts seem to be working fine. The last part of the snippet returns this error:

scripts.js:29 Uncaught TypeError: sections.indexOf is not a function
    at nextSection (scripts.js:29)
    at <anonymous>:1:1

Can anyone tell me what I am not getting here?

/*
============================================
array of all sections
============================================
*/
var sections=document.querySelectorAll("section");

/*
============================================
Function to find the section that is being displayed (the one that doesn't have "not1st" as a class.)
============================================
*/

function findSection(){
for (var i=0; i<sections.length; i++) {
    if (sections[i].className.includes("not1st")){
        continue;
    } else {
        return sections[i];
    }}}

/*
============================================
Function to load the next section
============================================
*/

function nextSection() {
   sections[sections.indexOf(findSection())+1];
}

Body:
querySelectorAll doesn't return an array, it returns a NodeList. NodeLists don't have an indexOf function.

You can convert it to an array using Array.from:

var sections = Array.from(document.querySelectorAll("section"));

...or for older browsers without Array.from, Array#slice:

var sections = Array.prototype.slice.call(document.querySelectorAll("section"));

For more information, see the "For Array-Like Objects" part of my other answer here.


来源: stackexchange

问:
Delete Avatar from Database
I have created a destroy action for my user profile picture. The destroy action works properly and the photo is deleted. I can add another picture without any problem, but when I try to delete the picture again I receive the following error message:

Couldn't find Avatar with 'id'=1

This is what is stored in my database Avatar.all reads:

```<code>[#<Avatar id: 2, avatarpic: "cat_astronaut.jpg", user_id: 1, created_at: "2017-12-05 17:02:08", updated_at: "2017-12-05 17:02:08">]
</code>```

The id is at 2 and not 1, even though I successfully deleted the first  picture with an id of 1. Every time I delete a picture and upload a new one, the id is incremented. So when I try to delete the second uploaded picture, it can't find the right id.  I need the id to be reset to 1 every time I delete the picture.

Controller is as follows:

```<code>class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

def destroy
  @user = User.find(params[:user_id])
  @avatar = Avatar.find(params[:id])
  @avatar.user = @user
  @avatar.destroy
  redirect_to user_path(@user)
end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end
</code>```

There is only 1 photo according to my user model:

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :places
  has_many :comments, dependent: :destroy
  has_one :avatar, dependent: :destroy
end
</code>```

Code for User's view profile page:

```<code><%= link_to user_avatar_path(@user), :title => "Upload New Photo", method: :delete, data: { confirm: 'Are you sure you want to change your Photo?' } do %>
  <%= image_tag @user.avatar.avatarpic %>
<% end %>
</code>```

rake routes:

```<code>root GET    /                                     places#index
          place_comments POST   /places/:place_id/comments(.:format)  comments#create
            place_photos POST   /places/:place_id/photos(.:format)    photos#create
                  places GET    /places(.:format)                     places#index
                         POST   /places(.:format)                     places#create
               new_place GET    /places/new(.:format)                 places#new
              edit_place GET    /places/:id/edit(.:format)            places#edit
                   place GET    /places/:id(.:format)                 places#show
                         PATCH  /places/:id(.:format)                 places#update
                         PUT    /places/:id(.:format)                 places#update
                         DELETE /places/:id(.:format)                 places#destroy
            user_avatars POST   /users/:user_id/avatars(.:format)     avatars#create
             user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy
                    user GET    /users/:id(.:format)                  users#show
</code>```

routes.rb:

```<code>Rails.application.routes.draw do
  devise_for :users
  root 'places#index'
  resources :places do
    resources :comments, only: :create
    resources :photos, only: :create
  end
  resources :users, only: [:show] do
    resources :avatars, only: [:create]
    resources :avatars, only: [:destroy]
    # or resources :avatars, only: [:create, :destroy]
end
end
</code>```

Avatar Model:

```<code>class Avatar < ApplicationRecord
  belongs_to :user
  mount_uploader :avatarpic, AvatarUploader
end
</code>```

Thank you for your help.

答:
Your link_to is missing the avatar_id. Change

```<code>user_avatar_path(@user)
</code>```

To

```<code>user_avatar_path(@user, @user.avatar)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Delete Avatar from Database

Body:
I have created a destroy action for my user profile picture. The destroy action works properly and the photo is deleted. I can add another picture without any problem, but when I try to delete the picture again I receive the following error message:

Couldn't find Avatar with 'id'=1

This is what is stored in my database Avatar.all reads:

[#<Avatar id: 2, avatarpic: "cat_astronaut.jpg", user_id: 1, created_at: "2017-12-05 17:02:08", updated_at: "2017-12-05 17:02:08">]

The id is at 2 and not 1, even though I successfully deleted the first  picture with an id of 1. Every time I delete a picture and upload a new one, the id is incremented. So when I try to delete the second uploaded picture, it can't find the right id.  I need the id to be reset to 1 every time I delete the picture.

Controller is as follows:

class AvatarsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @avatar = Avatar.new(avatar_params)
    @avatar.user = @user
    @avatar.save
    # Three lines above can be replaced with
    # @user.create_avatar(params)
    redirect_to user_path(@user)
  end

def destroy
  @user = User.find(params[:user_id])
  @avatar = Avatar.find(params[:id])
  @avatar.user = @user
  @avatar.destroy
  redirect_to user_path(@user)
end

private

def avatar_params
  params.require(:avatar).permit(:avatarpic)
end

end

There is only 1 photo according to my user model:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :places
  has_many :comments, dependent: :destroy
  has_one :avatar, dependent: :destroy
end

Code for User's view profile page:

<%= link_to user_avatar_path(@user), :title => "Upload New Photo", method: :delete, data: { confirm: 'Are you sure you want to change your Photo?' } do %>
  <%= image_tag @user.avatar.avatarpic %>
<% end %>

rake routes:

root GET    /                                     places#index
          place_comments POST   /places/:place_id/comments(.:format)  comments#create
            place_photos POST   /places/:place_id/photos(.:format)    photos#create
                  places GET    /places(.:format)                     places#index
                         POST   /places(.:format)                     places#create
               new_place GET    /places/new(.:format)                 places#new
              edit_place GET    /places/:id/edit(.:format)            places#edit
                   place GET    /places/:id(.:format)                 places#show
                         PATCH  /places/:id(.:format)                 places#update
                         PUT    /places/:id(.:format)                 places#update
                         DELETE /places/:id(.:format)                 places#destroy
            user_avatars POST   /users/:user_id/avatars(.:format)     avatars#create
             user_avatar DELETE /users/:user_id/avatars/:id(.:format) avatars#destroy
                    user GET    /users/:id(.:format)                  users#show

routes.rb:

Rails.application.routes.draw do
  devise_for :users
  root 'places#index'
  resources :places do
    resources :comments, only: :create
    resources :photos, only: :create
  end
  resources :users, only: [:show] do
    resources :avatars, only: [:create]
    resources :avatars, only: [:destroy]
    # or resources :avatars, only: [:create, :destroy]
end
end

Avatar Model:

class Avatar < ApplicationRecord
  belongs_to :user
  mount_uploader :avatarpic, AvatarUploader
end

Thank you for your help.

Body:
Your link_to is missing the avatar_id. Change

user_avatar_path(@user)

To

user_avatar_path(@user, @user.avatar)


问:
How to copy (and rename) a database?
I am coding in Delphi, using a TADOConnection to access ODBC compliant databases.

How do I copy a database leaving the new copy on the same database server?

And how do I rename? (I suppose I could copy & delete the original - if I knew how to copy).

答: Are you using ODBC drivers, or ADO providers?  If the later, you can look into the ADOX library, which provides vendor neutral support for working with the structure of databases.  I don't know myself whether it supports operations on the entire database.</p>

ContentLicense: CC BY-SA 2.5

Title: How to copy (and rename) a database?


问:
Getting element text value after the class has been added
I am trying to get the text value of an element that gets a class added after being clicked on. But I cannot get it. I also tried using html().

 let selectLevel;

function selectOption(menu) {

  $(menu).on('click', "li", function() {

    $(menu).find('.activeSelection').removeClass();
    $(this).addClass('activeSelection');

  });
}

$(document).ready(function() {

  selectOption('.levelList');

  selectLevel = $('.levelList').find('.activeSelection').text();

});```

答:
The easiest way I can imagine is to trigger a custom event when you click on the list element, then bind a function to this event to update your variable.

Example below:

let selectLevel;

function selectOption(menu) {

  $(menu).on('click', "li", function() {

    $(menu).find('.activeSelection').removeClass();
    $(this).addClass('activeSelection');
    $(menu).trigger('itemChanged'); //trigger custom event
  });
}

$(document).ready(function() {

  selectOption('.levelList');

  $('.levelList').on('itemChanged', function() { // wait for event on your menu
    selectLevel = $(this).find('.activeSelection').text();
    console.log(selectLevel); // just logging the current value
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.activeSelection {
  font-weight: bold;
}</code>```

Item 1

Item 2

Item 3

```

Body:
The easiest way I can imagine is to trigger a custom event when you click on the list element, then bind a function to this event to update your variable.

Example below:

let selectLevel;

function selectOption(menu) {

  $(menu).on('click', "li", function() {

    $(menu).find('.activeSelection').removeClass();
    $(this).addClass('activeSelection');
    $(menu).trigger('itemChanged'); //trigger custom event
  });
}

$(document).ready(function() {

  selectOption('.levelList');

  $('.levelList').on('itemChanged', function() { // wait for event on your menu
    selectLevel = $(this).find('.activeSelection').text();
    console.log(selectLevel); // just logging the current value
  });

});

.activeSelection {
  font-weight: bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="levelList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>


问:
SQL combine two select across multiple tables
So I've these tables:

Table 1:

```<code>facilities   emails
Fac 1        fac1@email.com
Fac 2        fac2@email.com
Fac 1 RE     fac1@email.com
</code>```

Table 2:

```<code>facilities  emails
fac1        fac1@email.com
fac2        fac3@email.com
</code>```

Now, on those two tables, I am trying to figure out how many facilities are using each address email. I have two sql queries that do just that:

```<code>SELECT ce.email, count(*)
AS TOTAL_FACILITIES
FROM table1
AS ce
GROUP BY ce.email
ORDER BY TOTAL_FACILITIES DESC

SELECT ca.emails, count(*)
AS TOTAL_FACILITIES
FROM table2
AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC
</code>```

This gives me the different emails from each table and how many facilities use them. I'm now  trying to combine it into a single call using a join but I can't seem to figure out how to make the count work.

Any suggestions?

答:
You may want to UNION it instead.

```<code>SELECT ce.email, count(*) AS TOTAL_FACILITIES
FROM table1 AS ce
GROUP BY ce.email
UNION
SELECT ca.emails, count(*) AS TOTAL_FACILITIES
FROM table2 AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC
</code>```

A better solution is to UNION it before aggregating.

```<code>SELECT email, COUNT(*) AS TOTAL_FACILITIES
FROM (
    SELECT facilities, email
    FROM table1
    UNION ALL
    SELECT facilities, email
    FROM table2
)
GROUP BY email
ORDER BY TOTAL_FACILITIES DESC
</code>```

Body:
So I've these tables:

Table 1:

facilities   emails
Fac 1        fac1@email.com
Fac 2        fac2@email.com
Fac 1 RE     fac1@email.com

Table 2:

facilities  emails
fac1        fac1@email.com
fac2        fac3@email.com

Now, on those two tables, I am trying to figure out how many facilities are using each address email. I have two sql queries that do just that:

SELECT ce.email, count(*)
AS TOTAL_FACILITIES
FROM table1
AS ce
GROUP BY ce.email
ORDER BY TOTAL_FACILITIES DESC

SELECT ca.emails, count(*)
AS TOTAL_FACILITIES
FROM table2
AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC

This gives me the different emails from each table and how many facilities use them. I'm now  trying to combine it into a single call using a join but I can't seem to figure out how to make the count work.

Any suggestions?

Body:
You may want to UNION it instead.

SELECT ce.email, count(*) AS TOTAL_FACILITIES
FROM table1 AS ce
GROUP BY ce.email
UNION
SELECT ca.emails, count(*) AS TOTAL_FACILITIES
FROM table2 AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC

A better solution is to UNION it before aggregating.

SELECT email, COUNT(*) AS TOTAL_FACILITIES
FROM (
    SELECT facilities, email
    FROM table1
    UNION ALL
    SELECT facilities, email
    FROM table2
)
GROUP BY email
ORDER BY TOTAL_FACILITIES DESC


问:
PyCharm: Anaconda installation is not found
I had Anaconda on Windows 10 installed in C:\ProgramData\Anaconda3 before using PyCharm. Now PyCharm displays: "Anaconda installation is not found" when I try using a conda env.

I also added Anaconda to PATH.

Is there a way to show PyCharm where Anaconda is installed?

答:
There is an open bug, currently PyCharm and IDEA both seem to detect Conda installation only from %HOMEPATH%/anaconda. https://youtrack.jetbrains.com/issue/PY-26923

The easiest workaround is to create a symlink to $HOME/.anaconda

```<code>mklink /D %HOMEDRIVE%%HOMEPATH%\anaconda C:\ProgramData\Anaconda3
</code>```

Note that C:\ProgramData\Anaconda3 should be replaced with the path to your Anconda installation. If you selected to installed it for "Just Me" instead of "All Users", your default location will be

```<code>C:\Users\<your_username>\AppData\Local\Continuum\anaconda3
</code>```

UPDATE: This issue is now fixed in IDEA and PyCharm since version 2018.1. You can specify a custom path under Python Interpreter or SDK settings in Conda Environment section.

Body:
There is an open bug, currently PyCharm and IDEA both seem to detect Conda installation only from %HOMEPATH%/anaconda. https://youtrack.jetbrains.com/issue/PY-26923

The easiest workaround is to create a symlink to $HOME/.anaconda

mklink /D %HOMEDRIVE%%HOMEPATH%\anaconda C:\ProgramData\Anaconda3

Note that C:\ProgramData\Anaconda3 should be replaced with the path to your Anconda installation. If you selected to installed it for "Just Me" instead of "All Users", your default location will be

C:\Users\<your_username>\AppData\Local\Continuum\anaconda3

UPDATE: This issue is now fixed in IDEA and PyCharm since version 2018.1. You can specify a custom path under Python Interpreter or SDK settings in Conda Environment section.

ContentLicense: CC BY-SA 4.0


问:
Observer pattern in c++
I am having a bit of trouble with observer pattern
I have a beverage class that uses decorator fine.
I am trying to implement observer to let an observer( say a cell phone/text message) in this case know when there order is done. i wont include the beverage/decorator classes since they work fine.

In main i was going to do something like this:

```<code>Subject mySubject = new Subject();
Observer myObserver1 = new Observer1();
Observer myObserver2 = new Observer2();

// register observers
mySubject.Register(myObserver1);
mySubject.Register(myObserver2);

mySubject.Notify("message 1");
mySubject.Notify("message 2");
</code>```

I have a subject class, observer, phone behavior class and a cellhone1,cellphone2 classes..

Here is the subject class

```<code>#ifndef _SUBJECT_
#define _SUBJECT_

//#include "Starbuzz.h"
//#include "Starbuzz2.h"
#include "Observer.h"
#include <list>

namespace CoffeeHouse {
namespace Observers {

class Subject  {

private:
std::list< Observer* > observers;

public:
Subject();
~Subject();

void Subject::Register(Observer observer)
{

//if (!observers.(observer))
//{

observers.insert(observer);
}
//}

//void Unregister(Observer observer)
//{
// if observer is in the list, remove
//if (observers.Contains(observer))
//{
//observers.Remove(observer);
//}
//}

void Notify(std::string message)
{
//need loop
Observer observer;
observer.update(message);

}
//}
//}

//void Subject::registerObserver( Observer* o ) { assert( o );
    //_observers.push_front(o);
//}
//void Subject::removeObserver( Observer* o ) { assert( o );
//  _observers.remove(o);
//}
//void Subject::notifyObservers() const {
    //for( std::list< Observer* >::iterator iterator = _observers.begin();   _observers.end() != iterator; ++iterator ) {
        //Observer* observer = *iterator;
        //observer->update(message);
    //}
//}
};
} // namespace Observer
}

#endif
</code>```

Here is the observer class

```<code>#ifndef _OBSERVER_
#define _OBSERVER_

#include <string>

namespace CoffeeHouse {
namespace Observers {

class Subject;

class Observer {

//public: virtual ~Observer() = 0;

public: virtual void Update(std::string message) = 0;
};
</code>```

here is the phone behavior class

```<code>#ifndef _PHONEBEHAVIOR_
#define _PHONEBEHAVIOR_

namespace CoffeeHouse {
namespace Observer {

class PhoneBehavior {
public: virtual void Update() const = 0;
};
protected: virtual ~PhoneBehavior() = 0 {

};

};

} // namespace Observer
} //
</code>```

here is cellphone 1

```<code>#ifndef _CELLPHONE1_
#define _CELLPHONE1_

namespace CoffeeHouse {
namespace Observer {
include<iostream>
class CellPhone1: public Observer, public PhoneBehavior {
public:
    CellPhone1();
    ~CellPhone1();
virtual void Update(std::string message)
 {
   std::cout << "CellPhone1: " << message;
}
};

} // namespace Observer
} //

#endif
</code>```

here re the errors i am getting..

```<code>error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
1>        due to following members:
1>        'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
see declaration of 'CoffeeHouse::Observers::Observer::update'
error C2661: 'std::list<_Ty>::insert' : no overloaded function takes 1 arguments
with[_Ty=CoffeeHouse::Observers::Observer *

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
due to following members:
'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
observer.h(15) : see declaration of 'CoffeeHouse::Observers::Observer::update
</code>```

When i click on error "cannot instantiate abstract class" it takes me to:

```<code>void Subject::Register(Observer observer)
</code>```

I understand that Abstract classes are made such that they cannot be instantiated!

How could i do an update then?? any suggestions of a better way?

I appreciate any help!

答:
Problems I see:

You use a namespace and a class
called Observer in PhoneBehavior
and CellPhone1 class source files.

In CellPhone1 class source file you
don't #include <string> or use the
std namespace for the string in void
Update(string message)

In PhoneBehavior class source file
virtual void update() should have
probably have a capital "U" to stay
consistent with your coding style and
because that's how it's called in the
CellPhone1 class source file.

In CellPhone1 class source file you have Cout <<"CellPhone1:" + message);. It should be std::cout << "CellPhone1: " << message;

In CellPhone1 class source file you need to #include <iostream>

You have too many closing braces in the PhoneBehavior class source file. And only the closing brace corresponding to the opening brace of your class PhoneBehavior should have a semicolon after it.

Edit: When I say "class source file" I'm assuming your project setup with CellPhone1.cpp , PhoneBehavior.cpp files based on the way you presented your question.

Title: Observer pattern in c++

Body:
I am having a bit of trouble with observer pattern
I have a beverage class that uses decorator fine.
I am trying to implement observer to let an observer( say a cell phone/text message) in this case know when there order is done. i wont include the beverage/decorator classes since they work fine.

In main i was going to do something like this:

Subject mySubject = new Subject();
Observer myObserver1 = new Observer1();
Observer myObserver2 = new Observer2();

// register observers
mySubject.Register(myObserver1);
mySubject.Register(myObserver2);

mySubject.Notify("message 1");
mySubject.Notify("message 2");

I have a subject class, observer, phone behavior class and a cellhone1,cellphone2 classes..

Here is the subject class

#ifndef _SUBJECT_
#define _SUBJECT_

//#include "Starbuzz.h"
//#include "Starbuzz2.h"
#include "Observer.h"
#include <list>

namespace CoffeeHouse {
namespace Observers {

class Subject  {

private:
std::list< Observer* > observers;

public:
Subject();
~Subject();

void Subject::Register(Observer observer)
{

//if (!observers.(observer))
//{

observers.insert(observer);
}
//}

//void Unregister(Observer observer)
//{
// if observer is in the list, remove
//if (observers.Contains(observer))
//{
//observers.Remove(observer);
//}
//}

void Notify(std::string message)
{
//need loop
Observer observer;
observer.update(message);

}
//}
//}

//void Subject::registerObserver( Observer* o ) { assert( o );
    //_observers.push_front(o);
//}
//void Subject::removeObserver( Observer* o ) { assert( o );
//  _observers.remove(o);
//}
//void Subject::notifyObservers() const {
    //for( std::list< Observer* >::iterator iterator = _observers.begin();   _observers.end() != iterator; ++iterator ) {
        //Observer* observer = *iterator;
        //observer->update(message);
    //}
//}
};
} // namespace Observer
}

#endif

Here is the observer class

#ifndef _OBSERVER_
#define _OBSERVER_

#include <string>

namespace CoffeeHouse {
namespace Observers {

class Subject;

class Observer {

//public: virtual ~Observer() = 0;

public: virtual void Update(std::string message) = 0;
};

here is the phone behavior class

#ifndef _PHONEBEHAVIOR_
#define _PHONEBEHAVIOR_

namespace CoffeeHouse {
namespace Observer {

class PhoneBehavior {
public: virtual void Update() const = 0;
};
protected: virtual ~PhoneBehavior() = 0 {

};

};

} // namespace Observer
} //

here is cellphone 1

#ifndef _CELLPHONE1_
#define _CELLPHONE1_

namespace CoffeeHouse {
namespace Observer {
include<iostream>
class CellPhone1: public Observer, public PhoneBehavior {
public:
    CellPhone1();
    ~CellPhone1();
virtual void Update(std::string message)
 {
   std::cout << "CellPhone1: " << message;
}
};

} // namespace Observer
} //

#endif

here re the errors i am getting..

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
1>        due to following members:
1>        'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
see declaration of 'CoffeeHouse::Observers::Observer::update'
error C2661: 'std::list<_Ty>::insert' : no overloaded function takes 1 arguments
with[_Ty=CoffeeHouse::Observers::Observer *

error C2259: 'CoffeeHouse::Observers::Observer' : cannot instantiate abstract class
due to following members:
'void CoffeeHouse::Observers::Observer::update(std::string)' : is abstract
observer.h(15) : see declaration of 'CoffeeHouse::Observers::Observer::update

When i click on error "cannot instantiate abstract class" it takes me to:

void Subject::Register(Observer observer)

I understand that Abstract classes are made such that they cannot be instantiated!

How could i do an update then?? any suggestions of a better way?

I appreciate any help!


问:
Angular 4 ngIf issue
I'm trying to use *ngIf, but i'm only receiving this error:

Can't bind to 'ngIf' since it isn't a known property of 'i'

This is my code:

```<code><div class="animated fadeIn">
    <div class="row">
        <div class="col-xs-12 col-md-12">
            <div class="card">

                <div class="card-header bg-info">
                    Pedidos <i  *ngIf="collapse" class="float-right fa fa-caret-up fa-2x"></i>
                </div>

                <div class="card-body">
                    <table class='table data-table' id='pedidos'>
                    </table>
                </div>

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

答:
You need to ensure that the @NgModule(...) containing this component imports CommonModule

```<code>imports: [CommonModule]
</code>```

otherwise such directives won't be available within that module.

In the AppModule importing BrowserModule includes already CommonModule which makes ngIf and others available for components in AppModule, but other modules must import their dependencies themselves.

Title: Angular 4 ngIf issue

Body:
I'm trying to use *ngIf, but i'm only receiving this error:

Can't bind to 'ngIf' since it isn't a known property of 'i'

This is my code:

                    Pedidos

Body:
You need to ensure that the @NgModule(...) containing this component imports CommonModule

imports: [CommonModule]

otherwise such directives won't be available within that module.

In the AppModule importing BrowserModule includes already CommonModule which makes ngIf and others available for components in AppModule, but other modules must import their dependencies themselves.


问:
How to return top 3 rows if last row is tied
Suppose my table contains data like that

```<code>  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80
</code>```

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

答:
Try:

```<code>SELECT A.ID, A.MOVIENAME, A.RATING
FROM
(SELECT ID, MOVIENAME, RATING, DENSE_RANK() OVER (ORDER BY RATING DESC) AS R
FROM YOUR_TABLE) A
WHERE A.R <= 3
ORDER BY A.RATING DESC;
</code>```

Dense Rank will repeat for same ratings. So if one of the top 3 ranks have more than one occurrences, you will get more than 3 entries in the output.

Body:
Suppose my table contains data like that

  ID    MovieName                      Rating
  --------------------------------------------
  1     The Shawshank Redemption       9.20
  2     The Godfather: Part II         9.00
  3     12 Angry Men                   8.90
  4     Pulp Fiction                   8.90
  5     The Good, the Bad and the Ugly 8.80

I want to select top 3 movies according to highest rating which contains both '12 Angry Men' and 'Pulp Fiction' movies.So query should return 4 rows instead of 3.

Body:
Try:

SELECT A.ID, A.MOVIENAME, A.RATING
FROM
(SELECT ID, MOVIENAME, RATING, DENSE_RANK() OVER (ORDER BY RATING DESC) AS R
FROM YOUR_TABLE) A
WHERE A.R <= 3
ORDER BY A.RATING DESC;

Dense Rank will repeat for same ratings. So if one of the top 3 ranks have more than one occurrences, you will get more than 3 entries in the output.


问:
How do I change the scale displayed in Google Maps API v3 to imperial (miles) units
I'm simply displaying a map, with no routing or directions.  I can add the control with mapOptions = {...scaleControl: true,...} but I could find no documentation about changing the units of the scale to imperial.

Here's my code:

```<code>var mapOptions = {
    zoom: 4,
    mapTypeControl: false,
    center: new google.maps.LatLng(38.8282, -98.5795),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scaleControl: true,
    scaleControlOptions: {position: google.maps.ControlPosition.BOTTOM_LEFT}
};
google.maps.visualRefresh = true;

map = new google.maps.Map(document.getElementById('map'),mapOptions);
</code>```

Note: The ControlPosition appears not to work, always goes to bottom right.

答:
I came here from the Google Issue Tracker https://issuetracker.google.com/issues/35825255

Here's an improved full example of the "click hack" from earlier posts:

uses just js (not Jquery)

regex to only match "km" and "m"

waits 1 second so Google Map can fully load first

#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="map"></div>
<script>
  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: { lat: 42.331534, lng: -83.046651 },
      zoom: 12,
      scaleControl: true
    });

    //START hack to set scale to miles/imperial instead of km/metric:
    window.setTimeout(function() {
      var spn = document.getElementById("map").getElementsByClassName("gm-style-cc");
      for (var i in spn) {
        //look for km or m in innerText via regex https://regexr.com/3hiqa
        if ((/\d\s?(km|(m\b))/g).test(spn[i].innerText)) {
          spn[i].click();
        }
      }
    }, 1000);
    //END hack to set scale to miles/imperial instead of km/metric

  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script></code>```

Body:
I'm simply displaying a map, with no routing or directions.  I can add the control with mapOptions = {...scaleControl: true,...} but I could find no documentation about changing the units of the scale to imperial.

Here's my code:

var mapOptions = {
    zoom: 4,
    mapTypeControl: false,
    center: new google.maps.LatLng(38.8282, -98.5795),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scaleControl: true,
    scaleControlOptions: {position: google.maps.ControlPosition.BOTTOM_LEFT}
};
google.maps.visualRefresh = true;

map = new google.maps.Map(document.getElementById('map'),mapOptions);

Note: The ControlPosition appears not to work, always goes to bottom right.

Body:
I came here from the Google Issue Tracker https://issuetracker.google.com/issues/35825255

Here's an improved full example of the "click hack" from earlier posts:

uses just js (not Jquery)

regex to only match "km" and "m"

waits 1 second so Google Map can fully load first

#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<script>
  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: { lat: 42.331534, lng: -83.046651 },
      zoom: 12,
      scaleControl: true
    });

    //START hack to set scale to miles/imperial instead of km/metric:
    window.setTimeout(function() {
      var spn = document.getElementById("map").getElementsByClassName("gm-style-cc");
      for (var i in spn) {
        //look for km or m in innerText via regex https://regexr.com/3hiqa
        if ((/\d\s?(km|(m\b))/g).test(spn[i].innerText)) {
          spn[i].click();
        }
      }
    }, 1000);
    //END hack to set scale to miles/imperial instead of km/metric

  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>


问:
How do you deploy a release to a sub folder without changing the physical path on IIS
We created a release definition that deploys our build to a onsite IIS server. We need to be able to deploy to a subfolder (e.g. D:\apps\appname\v1\[deploy here]. We tried changing the Physical Path setting in the IIS Web App Manage task, but that changes the Physical Path of the entire IIS server.

How can we specify where we want to put our individual application?

答:
The problem with the IIS Web App Manage task is that it wants to configure and create IIS Web Apps, not just copy files. To just copy files you want to use the Copy Files task. If you're working with a remote machine, make sure you're running the Copy Files task on your deployment group. To do that, in your Release Definition, make sure your task is running under a Deployment group phase that specifies your Deployment Group.

Once you have this set up, your deployment should run, and it will run from whatever machine you configured in the Deployment Group. You can copy files from the build's artifacts to a folder using a path local to that machine. So for example if your IIS Website is located at d:\websites\MySite you would use that as the destination path for the Copy Files task.


问:
Editable table cell using Textarea Tag
I trying to make editable table using jQuery. See code below

HTML

```<code><tr>
      <td>1</td>
      <td>11.11.2017</td>
      <td><span class="editable-cell">11-00</span></td>
      <td><span class="editable-cell">Проведение контрольных процедур</span></td>
      <td><span class="editable-cell">Выкзд МВК в рамках задачи 56987</span></td>
      <td><span class="editable-cell">17 км</span></td>
      <td>53,31</td>
    </tr>
</code>```

When user click on table cell, textarea tag appears in this cell and let him edit text

jQuery

```<code>$('.editable-cell').mousedown(function(event){

        var oldValue = "";
        var newValue = "";

        oldValue = $(this).text();
        $(this).text("");
        $(this).append('<textarea id="edit-area" rows="5" cols="50">');
        $(this).append('</textarea>');
        $("#edit-area").val(oldValue);
        $("#edit-area").focus();

        return false;
      });
</code>```

I'm stucked on this and need help.
1. When I click on cell, textarea appears and shows the text from span. If I try to set cursor by mouse in some place of text in Textarea, the cursor is always shown at the begining of the string. How I can place the cursor in any part of text in Textarea?
2. If I click on another span in my table or any place of window the old Textarea shoud be closed. How I can catch mouse click outside Textarea?

答:
The problem is that you're appending the textarea to your span instead of the table cell. You probably want this instead:

```<code>$('.editable-cell').mousedown(function(event){
        var span = $(this);
        var oldValue = span.text();
        var ta = $('<textarea class="edit-area" rows="5" cols="50"></textarea>');
        ta.text(oldValue);
        span.parent().append(ta);
        span.remove();
        return false;
});
</code>```

Notice that the append is on the parent of the span which is the table cell

Title: Editable table cell using Textarea Tag

Body:
I trying to make editable table using jQuery. See code below

HTML

      1
      11.11.2017
      11-00
      Проведение контрольных процедур
      Выкзд МВК в рамках задачи 56987
      17 км
      53,31

When user click on table cell, textarea tag appears in this cell and let him edit text

jQuery

$('.editable-cell').mousedown(function(event){

        var oldValue = "";
        var newValue = "";

        oldValue = $(this).text();
        $(this).text("");
        $(this).append('<textarea id="edit-area" rows="5" cols="50">');
        $(this).append('</textarea>');
        $("#edit-area").val(oldValue);
        $("#edit-area").focus();

        return false;
      });

I'm stucked on this and need help.
1. When I click on cell, textarea appears and shows the text from span. If I try to set cursor by mouse in some place of text in Textarea, the cursor is always shown at the begining of the string. How I can place the cursor in any part of text in Textarea?
2. If I click on another span in my table or any place of window the old Textarea shoud be closed. How I can catch mouse click outside Textarea?

Body:
The problem is that you're appending the textarea to your span instead of the table cell. You probably want this instead:

$('.editable-cell').mousedown(function(event){
        var span = $(this);
        var oldValue = span.text();
        var ta = $('<textarea class="edit-area" rows="5" cols="50"></textarea>');
        ta.text(oldValue);
        span.parent().append(ta);
        span.remove();
        return false;
});

Notice that the append is on the parent of the span which is the table cell


问:
Is using ViewBag in MVC bad?
It seem like mvc 3 team decided to bring in a feature for dynamic data exchange between a controller and a view called the viewbag but it is A good thing against the strongly typed view we all know about? What are some of the positive and negative aspects to using the ViewBag versus using a strongly typed view?

答: The ViewBag is the same thing as ViewData in previous ASP.NET MVC 1 and 2. It just happens to be dynamic instead of needing to use it like a dictionary with keys. I don't think this will replace strongly typed views at all and in fact you should use Viewdata/Viewbag as little as possible.  Always use strongly typed views whenever possible since it will lead to fewer errors if the names in your Viewdata/Viewbag change and make the HTML cleaner by not having ViewData casts all over the place.</p>

Title: Is using ViewBag in MVC bad?


问:
Error in OBJFileLoader
There's error in OBJFILELOADER.py file from the link - https://www.pygame.org/wiki/OBJFileLoader .
I think there's python2 to python3 version error, however I tried changing the raise ValueError thing and used obj as obj=(filename)

But still there's lots of errors.

I took the .obj file from blender, I don't think that's the issue.
Can anyone tell me the exact objfileloader for Python3

Error -

```<code> Traceback (most recent call last):
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 41, in __call__
    return self._finalCall( *args, **named )
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "run.py", line 28, in <module>
    obj = OBJ('robotbase.obj')
  File "/home/warted/COMMAND CENTRE/SEDS/GUI/Simulate/objloader.py", line 97, in __init__
    glNormal3fv(self.normals[normals[i] - 1])
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 45, in __call__
    return self._finalCall( *args, **named )
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 677, in wrapperCall
    pyArgs = tuple( calculate_pyArgs( args ))
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 438, in calculate_pyArgs
    yield converter(args[index], self, args)
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arrayhelpers.py", line 112, in asArraySize
    handler = typ.getHandler( incoming )
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arraydatatype.py", line 53, in __call__
    typ.__module__, type.__name__, repr(value)[:50]
TypeError: ('No array-type handler for type builtins.type (value: <map object at 0x7f6bf0f8f4a8>) registered', <function asArrayTypeSize.<locals>.asArraySize at 0x7f6c01d6a620>)
</code>```

答:
You just seem to assign the filename to the variable obj.

Instead you have to create an instance of the OBJ class and pass the file/path name:

```<code>obj = OBJ(filename)
</code>```

To port the script to Python 3 check out the linked answer.

Try this updated version:

```<code>import pygame
from OpenGL.GL import *

def MTL(filename):
    contents = {}
    mtl = None
    for line in open(filename, "r"):
        if line.startswith('#'): continue
        values = line.split()
        if not values: continue
        if values[0] == 'newmtl':
            mtl = contents[values[1]] = {}
        elif mtl is None:
            raise ValueError("mtl file doesn't start with newmtl stmt")
        elif values[0] == 'map_Kd':
            # load the texture referred to by this declaration
            mtl[values[0]] = values[1]
            surf = pygame.image.load(mtl['map_Kd'])
            image = pygame.image.tostring(surf, 'RGBA', 1)
            ix, iy = surf.get_rect().size
            texid = mtl['texture_Kd'] = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, texid)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                GL_LINEAR)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                GL_LINEAR)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                GL_UNSIGNED_BYTE, image)
        else:
            mtl[values[0]] = list(map(float, values[1:]))
    return contents

class OBJ:
    def __init__(self, filename, swapyz=False):
        """Loads a Wavefront OBJ file. """
        self.vertices = []
        self.normals = []
        self.texcoords = []
        self.faces = []

        material = None
        for line in open(filename, "r"):
            if line.startswith('#'): continue
            values = line.split()
            if not values: continue
            if values[0] == 'v':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.vertices.append(v)
            elif values[0] == 'vn':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.normals.append(v)
            elif values[0] == 'vt':
                self.texcoords.append(list(map(float, values[1:3])))
            elif values[0] in ('usemtl', 'usemat'):
                material = values[1]
            elif values[0] == 'mtllib':
                self.mtl = MTL(values[1])
            elif values[0] == 'f':
                face = []
                texcoords = []
                norms = []
                for v in values[1:]:
                    w = v.split('/')
                    face.append(int(w[0]))
                    if len(w) >= 2 and len(w[1]) > 0:
                        texcoords.append(int(w[1]))
                    else:
                        texcoords.append(0)
                    if len(w) >= 3 and len(w[2]) > 0:
                        norms.append(int(w[2]))
                    else:
                        norms.append(0)
                self.faces.append((face, norms, texcoords, material))

        self.gl_list = glGenLists(1)
        glNewList(self.gl_list, GL_COMPILE)
        glEnable(GL_TEXTURE_2D)
        glFrontFace(GL_CCW)
        for face in self.faces:
            vertices, normals, texture_coords, material = face

            mtl = self.mtl[material]
            if 'texture_Kd' in mtl:
                # use diffuse texmap
                glBindTexture(GL_TEXTURE_2D, mtl['texture_Kd'])
            else:
                # just use diffuse colour
                glColor(*mtl['Kd'])

            glBegin(GL_POLYGON)
            for i in range(len(vertices)):
                if normals[i] > 0:
                    glNormal3fv(self.normals[normals[i] - 1])
                if texture_coords[i] > 0:
                    glTexCoord2fv(self.texcoords[texture_coords[i] - 1])
                glVertex3fv(self.vertices[vertices[i] - 1])
            glEnd()
        glDisable(GL_TEXTURE_2D)
        glEndList()
</code>```

Title: Error in OBJFileLoader

Body:
There's error in OBJFILELOADER.py file from the link - https://www.pygame.org/wiki/OBJFileLoader .
I think there's python2 to python3 version error, however I tried changing the raise ValueError thing and used obj as obj=(filename)

But still there's lots of errors.

I took the .obj file from blender, I don't think that's the issue.
Can anyone tell me the exact objfileloader for Python3

Error -

 Traceback (most recent call last):
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 41, in __call__
    return self._finalCall( *args, **named )
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "run.py", line 28, in <module>
    obj = OBJ('robotbase.obj')
  File "/home/warted/COMMAND CENTRE/SEDS/GUI/Simulate/objloader.py", line 97, in __init__
    glNormal3fv(self.normals[normals[i] - 1])
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 45, in __call__
    return self._finalCall( *args, **named )
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 677, in wrapperCall
    pyArgs = tuple( calculate_pyArgs( args ))
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 438, in calculate_pyArgs
    yield converter(args[index], self, args)
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arrayhelpers.py", line 112, in asArraySize
    handler = typ.getHandler( incoming )
  File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arraydatatype.py", line 53, in __call__
    typ.__module__, type.__name__, repr(value)[:50]
TypeError: ('No array-type handler for type builtins.type (value: <map object at 0x7f6bf0f8f4a8>) registered', <function asArrayTypeSize.<locals>.asArraySize at 0x7f6c01d6a620>)

Body:
You just seem to assign the filename to the variable obj.

Instead you have to create an instance of the OBJ class and pass the file/path name:

obj = OBJ(filename)

To port the script to Python 3 check out the linked answer.

Try this updated version:

import pygame
from OpenGL.GL import *

def MTL(filename):
    contents = {}
    mtl = None
    for line in open(filename, "r"):
        if line.startswith('#'): continue
        values = line.split()
        if not values: continue
        if values[0] == 'newmtl':
            mtl = contents[values[1]] = {}
        elif mtl is None:
            raise ValueError("mtl file doesn't start with newmtl stmt")
        elif values[0] == 'map_Kd':
            # load the texture referred to by this declaration
            mtl[values[0]] = values[1]
            surf = pygame.image.load(mtl['map_Kd'])
            image = pygame.image.tostring(surf, 'RGBA', 1)
            ix, iy = surf.get_rect().size
            texid = mtl['texture_Kd'] = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, texid)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                GL_LINEAR)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                GL_LINEAR)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA,
                GL_UNSIGNED_BYTE, image)
        else:
            mtl[values[0]] = list(map(float, values[1:]))
    return contents

class OBJ:
    def __init__(self, filename, swapyz=False):
        """Loads a Wavefront OBJ file. """
        self.vertices = []
        self.normals = []
        self.texcoords = []
        self.faces = []

        material = None
        for line in open(filename, "r"):
            if line.startswith('#'): continue
            values = line.split()
            if not values: continue
            if values[0] == 'v':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.vertices.append(v)
            elif values[0] == 'vn':
                v = list(map(float, values[1:4]))
                if swapyz:
                    v = v[0], v[2], v[1]
                self.normals.append(v)
            elif values[0] == 'vt':
                self.texcoords.append(list(map(float, values[1:3])))
            elif values[0] in ('usemtl', 'usemat'):
                material = values[1]
            elif values[0] == 'mtllib':
                self.mtl = MTL(values[1])
            elif values[0] == 'f':
                face = []
                texcoords = []
                norms = []
                for v in values[1:]:
                    w = v.split('/')
                    face.append(int(w[0]))
                    if len(w) >= 2 and len(w[1]) > 0:
                        texcoords.append(int(w[1]))
                    else:
                        texcoords.append(0)
                    if len(w) >= 3 and len(w[2]) > 0:
                        norms.append(int(w[2]))
                    else:
                        norms.append(0)
                self.faces.append((face, norms, texcoords, material))

        self.gl_list = glGenLists(1)
        glNewList(self.gl_list, GL_COMPILE)
        glEnable(GL_TEXTURE_2D)
        glFrontFace(GL_CCW)
        for face in self.faces:
            vertices, normals, texture_coords, material = face

            mtl = self.mtl[material]
            if 'texture_Kd' in mtl:
                # use diffuse texmap
                glBindTexture(GL_TEXTURE_2D, mtl['texture_Kd'])
            else:
                # just use diffuse colour
                glColor(*mtl['Kd'])

            glBegin(GL_POLYGON)
            for i in range(len(vertices)):
                if normals[i] > 0:
                    glNormal3fv(self.normals[normals[i] - 1])
                if texture_coords[i] > 0:
                    glTexCoord2fv(self.texcoords[texture_coords[i] - 1])
                glVertex3fv(self.vertices[vertices[i] - 1])
            glEnd()
        glDisable(GL_TEXTURE_2D)
        glEndList()


问:
Saving information in controller symfony relation ManyToMany HELPPPPP
Hi I need to save information in my db, what I mean is, how to persist when the relationship is manytomany, I am doing like this but it doesn't work!...I will put some code of entity Menu.

```<code>     /** Agrega nuevo menù
         *
         * @Route("/save", name="admin_menu_save")
         * @Method({"GET", "POST"})
         * @param Request $request
         * @return Response
         */
        public function saveAction(Request $request)
        {
            $em = $this->getDoctrine()->getManager();
            $fecha_menu = $request->get('fecha');
            $fecha_comprar = $request->get('fechacomprado');
            $fecha_vencimiento = $request->get('fechavencimiento');
            $alimentos = $request->get('select_alimentos');
            $a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
            $menu = new Menu();
            $menu->setFecha(new \DateTime($fecha_menu));
            $menu->setFechacomprar(new \DateTime($fecha_comprar));
            $menu->setFechavence(new \DateTime($fecha_vencimiento));
            $menu->setPrecio(6);
            $menu->addAlimento($a);
            $em->persist($menu);
            $em->flush();
            return new Response('Guardado OK');
        }
 //Menu Entity Definition (Just the necessary code):

       /**
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return ArrayCollection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }

}
</code>```

I have not experience working with manytomany relations, I hope to solve this problem, that´s show very good, but I don´t know how to save,edit or remove in that manytomany table!....

答:
First, this bit seems weird.

```<code>$alimentos = $request->get('select_alimentos');
$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
</code>```

Doctrine findBy takes an array with the entity field as a key and the specific entity value as the value. Like this:

```<code>$em-getRepository('AdminBundle:Alimento')->findBy(['id' => $id]);
</code>```

If that's how your $alimentos variable is structured, that's fine. It just looks strange.

If this is a bi-directional relationship, you have to update both entities. So your controller code is like:

```<code>$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
$menu = new Menu();

// -- more code ---//

$menu->addAlimento($a);
$a->addMenu($menu);
$em->persist($menu);
$em->flush();
</code>```

Check this documentation.

Body:
Hi I need to save information in my db, what I mean is, how to persist when the relationship is manytomany, I am doing like this but it doesn't work!...I will put some code of entity Menu.

     /** Agrega nuevo menù
         *
         * @Route("/save", name="admin_menu_save")
         * @Method({"GET", "POST"})
         * @param Request $request
         * @return Response
         */
        public function saveAction(Request $request)
        {
            $em = $this->getDoctrine()->getManager();
            $fecha_menu = $request->get('fecha');
            $fecha_comprar = $request->get('fechacomprado');
            $fecha_vencimiento = $request->get('fechavencimiento');
            $alimentos = $request->get('select_alimentos');
            $a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
            $menu = new Menu();
            $menu->setFecha(new \DateTime($fecha_menu));
            $menu->setFechacomprar(new \DateTime($fecha_comprar));
            $menu->setFechavence(new \DateTime($fecha_vencimiento));
            $menu->setPrecio(6);
            $menu->addAlimento($a);
            $em->persist($menu);
            $em->flush();
            return new Response('Guardado OK');
        }
 //Menu Entity Definition (Just the necessary code):

       /**
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return ArrayCollection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }

}

I have not experience working with manytomany relations, I hope to solve this problem, that´s show very good, but I don´t know how to save,edit or remove in that manytomany table!....

Body:
First, this bit seems weird.

$alimentos = $request->get('select_alimentos');
$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);

Doctrine findBy takes an array with the entity field as a key and the specific entity value as the value. Like this:

$em-getRepository('AdminBundle:Alimento')->findBy(['id' => $id]);

If that's how your $alimentos variable is structured, that's fine. It just looks strange.

If this is a bi-directional relationship, you have to update both entities. So your controller code is like:

$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
$menu = new Menu();

// -- more code ---//

$menu->addAlimento($a);
$a->addMenu($menu);
$em->persist($menu);
$em->flush();

Check this documentation.


问:
In mercurial, is there a way to recover from a deleted 00changelog.d?
00changelog.d got deleted accidentally.

Is there a way to recover from this?

Or recover the changes made since the last push?

答:
It is technically possible, though with some information loss as the 00changelog.d file contain information such as the changeset author, the date of the commit, the commit message, and the named branch of the changeset. That said, it is possible to reconstruct the data to a high degree of certainty based on parent information in the 00manifest.{d,i}.

The data in the 00changelog.d is part of the changeset's hash, and as such it is important that the data that is shared with an upstream repository is exactly the same, so in order to reconstruct the changelog you need a clone of your upstream repository (what was local only we have some leeway on).

In short, preparation before we begin:

A clone of the upstream repository (let's assume it's in ./upstream/)

A backup of your local repository (let's assume it's in ./local-backup/)

Your local repository (let's assume it's in ./local/)

rm ./local/.hg/store/00changelog.* to start from a fresh slate

Next you need the following Mercurial extension I wrote for the occasion:

import os
import weakref

from mercurial.commands import command
from mercurial import scmutil, changelog, error, node

@command('reconstruct', [], '<path to 00changelog.i>')
def reconstruct(ui, repo, changelog_index):
    'reconstructs repository from upstream changelog if local changelog has been deleted'
    other_opener = scmutil.vfs(os.path.dirname(changelog_index),
                               expandpath=True,
                               realpath=True)
    upstream_changelog = changelog.changelog(other_opener)
    local_manifest = repo.manifest
    local_changelog = repo.changelog

    if len(local_changelog) != 0:
        raise error.Abort('not running on repository with actual changelog data')

    local_manifest_nodes = {local_manifest.node(rev): rev for rev in local_manifest}
    reconstructed_manifests = set()
    reconstructed_manifests_map = {}

    lock = repo.lock()
    try:
        tr = repo.transaction('reconstruct')
        trp = weakref.proxy(tr)

        for rev in upstream_changelog:
            data = upstream_changelog.read(upstream_changelog.node(rev))
            prevs = upstream_changelog.parentrevs(rev)
            p1 = node.nullid if prevs[0] == -1 else upstream_changelog.node(prevs[0])
            p2 = node.nullid if prevs[1] == -1 else upstream_changelog.node(prevs[1])
            if data[0] in local_manifest_nodes:
                n = local_changelog.add(data[0], data[3], data[4],
                                       trp, p1, p2,
                                       data[1], data[2], data[5])
                reconstructed_manifests.add(data[0])
                reconstructed_manifests_map[data[0]] = n

        missing_manifests = sorted(
                ((n, r) for n, r in local_manifest_nodes.iteritems()
                        if n not in reconstructed_manifests),
                key=lambda (x,y): y)

        for n, rev in missing_manifests:
            p1, p2 = local_manifest.parents(n)
            p1 = node.nullid if p1 == node.nullid else reconstructed_manifests_map[p1]
            p2 = node.nullid if p2 == node.nullid else reconstructed_manifests_map[p2]

            n2 = local_changelog.add(n, '', 'missing', trp, p1, p2, 'user')
            reconstructed_manifests_map[n] = n2
        tr.close()
    finally:
        if tr:
            tr.release()
        lock.release()
```

Place this file in ./reconstruct.py. Now we're able to revive the changes:

cd local

hg --config extensions.reconstruct=../reconstruct.py reconstruct ../upstream/.hg/store/00changelog.i

wait for a while (there's no progress)

All changes that were local only will have completely bogus changelog information, but this can be fixed up manually using either the histedit or mq extensions.

Note that the extension above makes a few simplifying assumptions: the manifest corresponds 1:1 to your changelog. Since you only deleted your 00changelog.d and not your 00changelog.i it would be possible to use the more accurate parent information from 00changelog.i but that would require substantially more code.

Also note that the extension above uses somewhat recent Python features, so your Mercurial will need to be based on Python 2.7.

Body:
It is technically possible, though with some information loss as the 00changelog.d file contain information such as the changeset author, the date of the commit, the commit message, and the named branch of the changeset. That said, it is possible to reconstruct the data to a high degree of certainty based on parent information in the 00manifest.{d,i}.

The data in the 00changelog.d is part of the changeset's hash, and as such it is important that the data that is shared with an upstream repository is exactly the same, so in order to reconstruct the changelog you need a clone of your upstream repository (what was local only we have some leeway on).

In short, preparation before we begin:

A clone of the upstream repository (let's assume it's in ./upstream/)

A backup of your local repository (let's assume it's in ./local-backup/)

Your local repository (let's assume it's in ./local/)

rm ./local/.hg/store/00changelog.* to start from a fresh slate

Next you need the following Mercurial extension I wrote for the occasion:

import os
import weakref

from mercurial.commands import command
from mercurial import scmutil, changelog, error, node

@command('reconstruct', [], '<path to 00changelog.i>')
def reconstruct(ui, repo, changelog_index):
    'reconstructs repository from upstream changelog if local changelog has been deleted'
    other_opener = scmutil.vfs(os.path.dirname(changelog_index),
                               expandpath=True,
                               realpath=True)
    upstream_changelog = changelog.changelog(other_opener)
    local_manifest = repo.manifest
    local_changelog = repo.changelog

    if len(local_changelog) != 0:
        raise error.Abort('not running on repository with actual changelog data')

    local_manifest_nodes = {local_manifest.node(rev): rev for rev in local_manifest}
    reconstructed_manifests = set()
    reconstructed_manifests_map = {}

    lock = repo.lock()
    try:
        tr = repo.transaction('reconstruct')
        trp = weakref.proxy(tr)

        for rev in upstream_changelog:
            data = upstream_changelog.read(upstream_changelog.node(rev))
            prevs = upstream_changelog.parentrevs(rev)
            p1 = node.nullid if prevs[0] == -1 else upstream_changelog.node(prevs[0])
            p2 = node.nullid if prevs[1] == -1 else upstream_changelog.node(prevs[1])
            if data[0] in local_manifest_nodes:
                n = local_changelog.add(data[0], data[3], data[4],
                                       trp, p1, p2,
                                       data[1], data[2], data[5])
                reconstructed_manifests.add(data[0])
                reconstructed_manifests_map[data[0]] = n

        missing_manifests = sorted(
                ((n, r) for n, r in local_manifest_nodes.iteritems()
                        if n not in reconstructed_manifests),
                key=lambda (x,y): y)

        for n, rev in missing_manifests:
            p1, p2 = local_manifest.parents(n)
            p1 = node.nullid if p1 == node.nullid else reconstructed_manifests_map[p1]
            p2 = node.nullid if p2 == node.nullid else reconstructed_manifests_map[p2]

            n2 = local_changelog.add(n, '', 'missing', trp, p1, p2, 'user')
            reconstructed_manifests_map[n] = n2
        tr.close()
    finally:
        if tr:
            tr.release()
        lock.release()

Place this file in ./reconstruct.py. Now we're able to revive the changes:

cd local

hg --config extensions.reconstruct=../reconstruct.py reconstruct ../upstream/.hg/store/00changelog.i

wait for a while (there's no progress)

All changes that were local only will have completely bogus changelog information, but this can be fixed up manually using either the histedit or mq extensions.

Note that the extension above makes a few simplifying assumptions: the manifest corresponds 1:1 to your changelog. Since you only deleted your 00changelog.d and not your 00changelog.i it would be possible to use the more accurate parent information from 00changelog.i but that would require substantially more code.

Also note that the extension above uses somewhat recent Python features, so your Mercurial will need to be based on Python 2.7.


问:
Wrap every 4 divs - wrong behavior
I'm using the code below to wrap every 4 divs with class .wrap4 inside a div with class .wrapList

Js code:

```<code>function Wrap(){
        var $children = $('.wrap4');
        for(var i = 0, l = $children.length; i < l; i += 4) {
            $children.slice(i, i+4).wrapAll('<div class="wrapList"></div>');
        }
};
</code>```

for example:

```<code><div class="row">
  <div class="wrap4">1</div>
  <div class="wrap4">2</div>
  <div class="wrap4">3</div>
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div>
</code>```

Result:

```<code><div class="row">
  <div class="wrapList">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
    <div class="wrap4">4</div>
   </div>
   <div class="wrapList">
    <div class="wrap4">5</div>
    <div class="wrap4">6</div>
    <div class="wrap4">7</div>
  </div>
</div>
</code>```

It works great, but if the divs before the wrapping are in two rows instead of one, for example:

```<code><div class="row">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
</div>
<div class="row">
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
</div>
</code>```

The result will not respect the rows and it will move the 4 to the top row to complete a line of 4 divs, for example:

```<code><div class="row">
  <div class="wrapList">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
    <div class="wrap4">4</div> (this div belong to the row below)
  </div>
</div>
<div class="row">
  <div class="wrapList">
    <div class="wrap4">5</div>
    <div class="wrap4">6</div>
    <div class="wrap4">7</div>
  </div>
</div>
</code>```

How can I make the code respect the rows?

Thank you very much!!!

答:
You could iterate through your rows, performing the wrap only on children of each row:

function Wrap(){
        var $rows = $('.row');
        for (var h = 0, r; r = $rows[h]; h++) {
            var $children = $(r).find('.wrap4');
            for(var i = 0, l = $children.length; i < l; i += 4) {
                $children.slice(i, i+4).wrapAll('

');
            }
        }
};

Wrap();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
  background-color: silver;
  border: 3px solid red;
}

.wrapList {
  border: 1px solid black;
  margin: 3px 0;
}</code>```

1

2

3

4

5

6

7

8

```

Title: Wrap every 4 divs - wrong behavior

Body:
I'm using the code below to wrap every 4 divs with class .wrap4 inside a div with class .wrapList

Js code:

function Wrap(){
        var $children = $('.wrap4');
        for(var i = 0, l = $children.length; i < l; i += 4) {
            $children.slice(i, i+4).wrapAll('

');
        }
};

for example:

1

2

3

4

5

6

7

Result:

1

2

3

4

5

6

7

It works great, but if the divs before the wrapping are in two rows instead of one, for example:

1

2

3

4

5

6

7

The result will not respect the rows and it will move the 4 to the top row to complete a line of 4 divs, for example:

1

2

3

4
 (this div belong to the row below)

5

6

7

How can I make the code respect the rows?

Thank you very much!!!

Body:
You could iterate through your rows, performing the wrap only on children of each row:

function Wrap(){
        var $rows = $('.row');
        for (var h = 0, r; r = $rows[h]; h++) {
            var $children = $(r).find('.wrap4');
            for(var i = 0, l = $children.length; i < l; i += 4) {
                $children.slice(i, i+4).wrapAll('<div class="wrapList"></div>');
            }
        }
};

Wrap();

.row {
  background-color: silver;
  border: 3px solid red;
}

.wrapList {
  border: 1px solid black;
  margin: 3px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="wrap4">1</div>
    <div class="wrap4">2</div>
    <div class="wrap4">3</div>
</div>
<div class="row">
  <div class="wrap4">4</div>
  <div class="wrap4">5</div>
  <div class="wrap4">6</div>
  <div class="wrap4">7</div>
  <div class="wrap4">8</div>
</div>


问:
Add empty inputs to an array with the value of 0
As a project I am building a "barebones" budgeting web-app. I have a form with a number of inputs to fill out income sources and amounts.

```<code><form>
      <div class="form-group">
        <input type="text" class="form-control" id="incomeSrc1" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc2" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc3" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc4" placeholder="Enter Source" name="incomeSrc">
      </div>
    </form>
</code>```

And

```<code><form>
      <div class="form-group">
        <input type="number" class="form-control" id="amount1" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount2" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount3" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount4" placeholder="Enter Amount" name="incAmount">
      </div>
    </form>
</code>```

I tried to put all the inputs into a array amountArr so that I could add them together and determine the largest source of income.

This was my latest attempt :

```<code>var incAmount = document.getElementsByName("incAmount");
var amountArr = [];
//Income input function
for (var index = 0; index < incAmount.length; index++) {
    incAmount[index].addEventListener("input", add3);
    function add3() {
        for (var i = 0; i < incAmount.length; i++) {
             amountArr[i] = parseFloat(incAmount[i].value);
            if (incAmount[i].value === NaN) {
                amountArr[i] = 0;
            };
        };
    };
};
</code>```

The goal is that if an input wasn't filled then its value in the array will be 0. However all my attempts either threw errors like -

incAmount[i].value is undefined

or the array was filled with NaN's.

I also tried

```<code>if (amountArr[i].value !== NaN)
</code>```

and

```<code>if (isNaN(amountArr[i]))
</code>```

None of them returned true (executed the ensuing code)

Why doesn't amountArr or an empty incAmount reurn true when compared to NaN/null/undefined?

答:
I found a solution that works.

```<code>for (var i = 0; i < incAmount.length; i++) {
         amountArr[i] = parseFloat(incAmount[i].value) || 0;
</code>```

The array amountArr will show 0's for all empty inputs.

Body:
As a project I am building a "barebones" budgeting web-app. I have a form with a number of inputs to fill out income sources and amounts.

<form>

        <input type="text" class="form-control" id="incomeSrc1" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc2" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc3" placeholder="Enter Source" name="incomeSrc">
        <input type="text" class="form-control" id="incomeSrc4" placeholder="Enter Source" name="incomeSrc">

    </form>

And

<form>

        <input type="number" class="form-control" id="amount1" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount2" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount3" placeholder="Enter Amount" name="incAmount">
        <input type="number" class="form-control" id="amount4" placeholder="Enter Amount" name="incAmount">

    </form>

I tried to put all the inputs into a array amountArr so that I could add them together and determine the largest source of income.

This was my latest attempt :

var incAmount = document.getElementsByName("incAmount");
var amountArr = [];
//Income input function
for (var index = 0; index < incAmount.length; index++) {
    incAmount[index].addEventListener("input", add3);
    function add3() {
        for (var i = 0; i < incAmount.length; i++) {
             amountArr[i] = parseFloat(incAmount[i].value);
            if (incAmount[i].value === NaN) {
                amountArr[i] = 0;
            };
        };
    };
};

The goal is that if an input wasn't filled then its value in the array will be 0. However all my attempts either threw errors like -

incAmount[i].value is undefined

or the array was filled with NaN's.

I also tried

if (amountArr[i].value !== NaN)

and

if (isNaN(amountArr[i]))

None of them returned true (executed the ensuing code)

Why doesn't amountArr or an empty incAmount reurn true when compared to NaN/null/undefined?

Body:
I found a solution that works.

for (var i = 0; i < incAmount.length; i++) {
         amountArr[i] = parseFloat(incAmount[i].value) || 0;

The array amountArr will show 0's for all empty inputs.


问:
How does Cake PHP model associations work between different Data Sources
I have been playing around with cakephp for the last few days, and I am trying to work out how the associations work between different data sources. I have been searching on google, but haven't had much success.

For instance, lets say I have two models, one that stores its data in a MySQL database, and another that stores data in an XML file. They both have HABTM set linking to each other. So, when one is searched for, how does the system join both data sources, and how efficient is it (i.e. avoiding the N+1 problem)?

答:
I just ran into similar problem using cake 3.

I am using Postgres and my data resides in different schemas which I define as different datasources. To make relations work I had to make addition to table definition for cake to issue separate query to join data.

Here is relationship definition from my AccountsTable which is stored in comp_x.accounts and belongs to Banks which is stored in public.banks

```<code>$this->belongsTo('Banks', [
        'foreignKey' => 'bank_id',
        'strategy' => 'select' // this is the change I made
]);
</code>```

This way cake makes separate query to fetch bank data and not to try join to non existing table comp_x.banks in same query.

In your question you mentioned HABTM relationships. I believe it could be similar. I have nothing to add about efficiency as I have not tested it yet on large datasets.

Body:
I just ran into similar problem using cake 3.

I am using Postgres and my data resides in different schemas which I define as different datasources. To make relations work I had to make addition to table definition for cake to issue separate query to join data.

Here is relationship definition from my AccountsTable which is stored in comp_x.accounts and belongs to Banks which is stored in public.banks

$this->belongsTo('Banks', [
        'foreignKey' => 'bank_id',
        'strategy' => 'select' // this is the change I made
]);

This way cake makes separate query to fetch bank data and not to try join to non existing table comp_x.banks in same query.

In your question you mentioned HABTM relationships. I believe it could be similar. I have nothing to add about efficiency as I have not tested it yet on large datasets.


问:
What is the difference between the following GPO settings?
While doing some GPO work today and setting up some firewall inbound rules that I want distributed through GP I became confused between these two GPs. They function very similarly, yet I couldn't find any differences.

Computer Configuration > Policies > Windows Settings > Security Settings > Windows Firewall with Advanced Security > Inbound Rules

and

Computer Configuration > Policies > Administrative Templates > Network > Network Connections > Windows Firewall > Domain Profile > Windows Firewall: Define Inbound Port Exception

So, what are their diffrences?

答:
The two different Group Policy locations for Windows Firewall settings are due to feature differences in the Windows Firewall itself between older and newer Windows OS versions.

If you are using Windows Vista/Windows 7/Windows Server 2008 or newer operating systems, use this Group Policy path to configure Firewall policies, as these operating systems have the Windows Firewall "with Advanced Security":

Computer Configuration > Policies > Windows Settings > Security
  Settings > Windows Firewall with Advanced Security > Inbound Rules

If you are using Windows XP or Windows Server 2003, use only the Group Policy path below to configure Firewall policies.  Reason is because these older  operating systems have the older Windows Firewall without the "Advanced Security", and only the Group Policy path shown below will work with these older systems.

Computer Configuration > Policies > Administrative Templates >Network>
  Network Connections > Windows Firewall > Domain Profile > Windows Firewall: Define Inbound Port Exception

I navigated through a ton of research and stumbled across the answer inside this Windows Server 2008 Firewall training video by ITFreeTraining (published on 9/05/2011), where it is explained at the 25:45 mark:   Windows Server 2008 Firewall

Unrelated, but since this is a coding Q&A site, you might want to take a look at managing Group Policy through PowerShell.


问:
Microsoft SQL Server Management Studio Opening Error
I installed SQL Server Management Studio and it worked fine. After that I updated my Visual Studio from 2010 to 2013 Express edition, now it is not working with this error message :

Cannot find one or more components. Please re install the application

I re-installed it but still same issue. Any suggestion?

答:
Just in case none of the registry edits or software reinstalls mentioned in the other answers work for you, I was having this issue due to anti-virus. In this case it was Crowdstrike, but others can cause it as well.

Try disabling your AV to test, and if that's the culprit, put an exception in for SSMS 2014/2016.


问:
How to redirect all http, https request in network to apache server for creating firewall in raspberrypi..?
How to redirect all http, https request in network  to apache server for creating firewall in raspberrypi..?

For example , if i have 3 PC in my network with IP addresses as 192.168.1.8, 192.168.1.9 and 192.168.1.10 and if from any PC i try to visit https://www/google.com then i should navigate or redirect to some IP like 192.168.1.10.

I want to implement this using linux and mostly using raspberry pi.
Please help me..

Thank you in advance.

答:
It sounds like what you need is a Raspberry Pi router. There are multiple tutorials out there that accomplish what you need in different ways using the same principles. I included a couple links for you to read through.

https://www.raspberrypi.org/documentation/configuration/wireless/access-point.md

https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/overview

As you go through the tutorials, take notes of what you don't understand and create new questions for the community to help.

Good luck!


问:
How to replace commas with semicolons except for commas in Quotes?
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

```<code>012,ABC,"DE,FG",345
</code>```

must become:

```<code>012;ABC;"DE,FG";345
</code>```

How can I do that via Batch?

答:
If you happen to have the JREPL.BAT regular expression text processing utility (v7.9 or later), then you can use:

```<code>jrepl "," ";" /p "([\c\q]+)|\q.*?\q" /prepl "$1?{$0}:$0" /f "test.csv" /o -
</code>```

Use call jrepl if you put the command within a batch script.

The original file will be overwritten. You can substitute a new file name for - if you don't want to overwrite the original.

JREPL.BAT is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward - no 3rd party .exe file required.

The JREPL solution works by performing the replacement in two steps.

1) The /P option breaks each line into unquoted strings and quoted strings. The /PREPL option passes unquoted strings on to the normal FIND/REPLACE, and unquoted strings are preserved as is.

2) The main FIND/REPLACE substitutes ; for ,

It is possible to reliably accomplish this with pure batch using a variant of a technique developed by jeb at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell. Although any pure batch solution will be significantly slower than hybrid solutions like JREPL.BAT, ParseCSV.bat, or a powershell solution.

Here is a batch script derived from jeb's technique - simply pass the name of the CSV file as the one and only argument. The original file will be overwritten. It should be trivial to modify the script to write the output to a new file instead. See jeb's post for an overview of how this seemingly magical technique works.

```<code>@echo off
setlocal disableDelayedExpansion
>"%~1.new" (
  for /f usebackq^ delims^=^ eol^= %%A in ("%~1") do (
    set "ln=%%A"
    call :repl
  )
)
move /y "%~1.new" "%~1" >nul
exit /b

:repl
set "ln=%ln:"=""%"
set "ln=%ln:^=^^%"
set "ln=%ln:&=^&%"
set "ln=%ln:|=^|%"
set "ln=%ln:<=^<%"
set "ln=%ln:>=^>%"

set "ln=%ln:,=^,^,%"
set ln=%ln:""="%
set "ln=%ln:"=""%"

set "ln=%ln:,,=;%"
set "ln=%ln:^,^,=,%"
set "ln=%ln:""="%"
setlocal enableDelayedExpansion
echo(!ln!
exit /b
</code>```

The script should be able to process almost any valid CSV file input. The only restrictions are:

Empty lines are stripped from the output (should not be a problem with CSV)

Line lengths are limited to around 8 kb. The exact limit is dependent on how many intermediate substitutions must be performed.

Body:
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

012,ABC,"DE,FG",345

must become:

012;ABC;"DE,FG";345

How can I do that via Batch?

Body:
If you happen to have the JREPL.BAT regular expression text processing utility (v7.9 or later), then you can use:

jrepl "," ";" /p "([\c\q]+)|\q.*?\q" /prepl "$1?{$0}:$0" /f "test.csv" /o -

Use call jrepl if you put the command within a batch script.

The original file will be overwritten. You can substitute a new file name for - if you don't want to overwrite the original.

JREPL.BAT is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward - no 3rd party .exe file required.

The JREPL solution works by performing the replacement in two steps.

1) The /P option breaks each line into unquoted strings and quoted strings. The /PREPL option passes unquoted strings on to the normal FIND/REPLACE, and unquoted strings are preserved as is.

2) The main FIND/REPLACE substitutes ; for ,

It is possible to reliably accomplish this with pure batch using a variant of a technique developed by jeb at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell. Although any pure batch solution will be significantly slower than hybrid solutions like JREPL.BAT, ParseCSV.bat, or a powershell solution.

Here is a batch script derived from jeb's technique - simply pass the name of the CSV file as the one and only argument. The original file will be overwritten. It should be trivial to modify the script to write the output to a new file instead. See jeb's post for an overview of how this seemingly magical technique works.

@echo off
setlocal disableDelayedExpansion
>"%~1.new" (
  for /f usebackq^ delims^=^ eol^= %%A in ("%~1") do (
    set "ln=%%A"
    call :repl
  )
)
move /y "%~1.new" "%~1" >nul
exit /b

:repl
set "ln=%ln:"=""%"
set "ln=%ln:^=^^%"
set "ln=%ln:&=^&%"
set "ln=%ln:|=^|%"
set "ln=%ln:<=^<%"
set "ln=%ln:>=^>%"

set "ln=%ln:,=^,^,%"
set ln=%ln:""="%
set "ln=%ln:"=""%"

set "ln=%ln:,,=;%"
set "ln=%ln:^,^,=,%"
set "ln=%ln:""="%"
setlocal enableDelayedExpansion
echo(!ln!
exit /b

The script should be able to process almost any valid CSV file input. The only restrictions are:

Empty lines are stripped from the output (should not be a problem with CSV)

Line lengths are limited to around 8 kb. The exact limit is dependent on how many intermediate substitutions must be performed.


问:
Convert encoded application/x-www-form-urlencoded post data to json object
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:

```<code>  var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "processData": false,
  "data": "{\n\t\"practice\": [\"Learning\"]\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

But the API expects to be able to get req.body as a JSON object it can immediately use:

```<code>"{"practice":["Learning"]}"
</code>```

Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)

答:
You can actually post JSON as body.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "dataType" : "json"
  "processData": false,
  "data": { "practice": ["Learning"] }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
```

Notice that theirs a new property which tells that data type to be posted is JSON and and now in data property the value is in JSON format instead of string.

Hope this solves your problem.

Body:
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:

  var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "processData": false,
  "data": "{\n\t\"practice\": [\"Learning\"]\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

But the API expects to be able to get req.body as a JSON object it can immediately use:

"{"practice":["Learning"]}"

Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)

Body:
You can actually post JSON as body.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "dataType" : "json"
  "processData": false,
  "data": { "practice": ["Learning"] }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

Notice that theirs a new property which tells that data type to be posted is JSON and and now in data property the value is in JSON format instead of string.

Hope this solves your problem.


问:
Substring of a line from a file is not working for one specific line in Java
Before I start I know this isnt the only way of getting the information from the file I need, since I can use a scanner. However when i've been trying to read it this way the substring seems to be causing problems with this line from the Contract.txt file:07-Jun-2016 1   3   1   N   JB847N  900 S Trotter

Which thorws a NormatFormatException "00    " because it is trying to then parse a tab. This is the only line that does this.

```<code>public String averageCostOflarge() {
    int numberOfBundles = 0;
    int total = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader("Contract.txt"));

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.charAt(14) == '3') {
                numberOfBundles++;
                if(line.charAt(32)=='\t'){
                    total+=Integer.parseInt(line.substring(28, 32));
                }else{
                    total+=Integer.parseInt(line.substring(28, 31));
                }
            }

        }
        reader.close();
        return Integer.toString(numberOfBundles);
    } catch (FileNotFoundException e) {
        return "Error";
    } catch (IOException ex) {
        Logger.getLogger(ContractSummary.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}
</code>```

However the it seems to mainly be this part: 1  3   1   N   JB847N  900 as this part comes up multiple times in the file.

Contract file: https://pastebin.com/GFG1Um4g

I have removed all the lines that have been causing this problem and the code works just fine.

The section of code needs to check if the third row is set as 3 and then get the cost in the seventh row. The pieces of information are seperated by tabs not spaces and I have tried manually typing the line that is causing the problem to see if it was a formatting error in the file.

Any explanation as to why my code is doing this would be greatly appreciated.

答:
You need to added trim() to remove spaces

```<code>if (line.charAt(32) == '\t') {
    total += Integer.parseInt(line.substring(28, 32).trim());
} else {
    total += Integer.parseInt(line.substring(28, 31).trim());
}
</code>```

Body:
Before I start I know this isnt the only way of getting the information from the file I need, since I can use a scanner. However when i've been trying to read it this way the substring seems to be causing problems with this line from the Contract.txt file:07-Jun-2016 1   3   1   N   JB847N  900 S Trotter

Which thorws a NormatFormatException "00    " because it is trying to then parse a tab. This is the only line that does this.

public String averageCostOflarge() {
    int numberOfBundles = 0;
    int total = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader("Contract.txt"));

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.charAt(14) == '3') {
                numberOfBundles++;
                if(line.charAt(32)=='\t'){
                    total+=Integer.parseInt(line.substring(28, 32));
                }else{
                    total+=Integer.parseInt(line.substring(28, 31));
                }
            }

        }
        reader.close();
        return Integer.toString(numberOfBundles);
    } catch (FileNotFoundException e) {
        return "Error";
    } catch (IOException ex) {
        Logger.getLogger(ContractSummary.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}

However the it seems to mainly be this part: 1  3   1   N   JB847N  900 as this part comes up multiple times in the file.

Contract file: https://pastebin.com/GFG1Um4g

I have removed all the lines that have been causing this problem and the code works just fine.

The section of code needs to check if the third row is set as 3 and then get the cost in the seventh row. The pieces of information are seperated by tabs not spaces and I have tried manually typing the line that is causing the problem to see if it was a formatting error in the file.

Any explanation as to why my code is doing this would be greatly appreciated.

Body:
You need to added trim() to remove spaces

if (line.charAt(32) == '\t') {
    total += Integer.parseInt(line.substring(28, 32).trim());
} else {
    total += Integer.parseInt(line.substring(28, 31).trim());
}


问:
Define expected parameters for a controller action in Rails
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

```<code>def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end
</code>```

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)

答:
Try this code:

```<code>before_filter :check_params

private
def check_params
    needed_params=[:links]
    needed_params.each do |x|
        render :text=>"Missing param #{x}", :status=>400
        return
    end
</code>```

end

Put this code at the end of your class. It will work for every action. Also, you want to return an error code 400 (Bad Request), not an error 404 (File Not Found).

Body:
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)

Body:
Try this code:

before_filter :check_params

private
def check_params
    needed_params=[:links]
    needed_params.each do |x|
        render :text=>"Missing param #{x}", :status=>400
        return
    end

end

Put this code at the end of your class. It will work for every action. Also, you want to return an error code 400 (Bad Request), not an error 404 (File Not Found).


问:
Usage of '@@' syntax in python
I ran into the double @@ symbol in the following code: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py

I understand that the @ is used as a decorator. But I can't seem to find any information on the use of @@?

答:
The @@ is used only in docstrings not in code. It is no valid Python syntax.

An external tool uses this for generating links to other classes in the documentation.

Title: Usage of '@@' syntax in python