问:
Footer will not go to bottom, showing over content
https://jsfiddle.net/z4of8fvy/

I know my code is somewhat sloppy but I am still learning. I have run it through a validator to see if I had a missing  but I didn't find one. Any help would be appreciated.

If there are any other things that you guys can point out I would appreciate that as well.
It keeps asking me for more details but I don't know what else I can say. I do know that at one point the footer was working with me keeping it position: sticky and bottom:0 but when I added more content that's when the problem appeared. That is when I tried to play with it a bit and probably ruined it even more.

```<code><div id="topBar" class="container-fluid">
    <div class="row">
        <div id="logo" class="col-xs-6">
            <a id="homelink" href="https://smithstreetmediagroup.com">
            <h1>SMG <br> Studios </h1>
            </a>
        </div>
        <div id= "menu" class = "col-xs-6">
            <a class="topBar" href="mess.html"><h4>Me$$ aka M.T.M  </h4></a>
            <a class="topBar" href="services.html"><h4>Services </h4></a>
            <a class="topBar" href="campaigns.html"><h4>Campaigns </h4></a>
            <a class="topBar" href="jeybundy.html"><h4>Jey Bundy </h4></a>
            <a class="topBar" href="store.html"><h4>Store </h4></a>
            <a class="topBar" href="contact.html"><h4>Contact </h4></a>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div  id="studioHome" class = "col-xs-4 mainOne">
            <h1> Studio Services </h1>
            <a href="services.html"> <h1 class="buttons"> Read More </h1> </a>
        </div>
        <div id="jbHome" class = "col-xs-4 mainOne">
            <h1> Jey Bundy </h1>
            <a href="services.html"> <h1 class="buttons"> Read More </h1> </a>
        </div>
        <div id="mtmHome" class = "col-xs-4 mainOne">
            <h1> Me$$ aka M.T.M </h1>
            <a href="services.html"> <h1 class="buttons"> Read More </h1> </a>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-6 mainTwo">
            <h1>Our Mission</h1>
            <p>
                Smith media groups consist of a team of polite professionals that provide high quality and affordable service. We consider our customers family so we take pride in making our customers feel as comfortable and satisfied as possible. We offer a vast variety of services such as photoshoots, music videos, parties, wedding videos/photos, real estate photos, music production & duplication, ect. If you have any questions give us a call or use our contact form and we will give you a call. Our Vison, Your Success</p>
        </div>
        <div class="col-xs-6 mainTwo">

            <iframe width="560" height="315" src="https://www.youtube.com/embed/5iSNm5c6dBs?rel=0" frameborder="0" ></iframe>

        </div>

    </div>
</div>
<div class="container">
    <div class = "row">
        <div class = "col-xs-12">
            <div id="slideshow">
                <div class="slideImg">
                    <img src="battleflyer.jpg" />
                </div>
                <div class="slideImg">
                    <img src="bluesmoke.jpg" />
                </div>
                <div class="slideImg">
                    <img src="streetview.jpg" />
                </div>
                <div class="slideImg">
                    <img src="trackboard.jpg" />
                </div>
            </div>
</div>
    </div>
</div>
<footer>
    <div class = "container-fluid">
        <div class = "row" id="bottomBar">
            <div class = "col-xs-4">

                <a href="https://www.facebook.com/smithstreetmediagroup/"> <i class="fa fa-facebook-official" aria-hidden="true"> Facebook</i></a>
                <a href="https://www.instagram.com/smithmediagroup/?hl=en"><i class="fa fa-instagram" aria-hidden="true"> Instagram</i></a>

            </div>
            <div class = "col-xs-4">

            </div>
            <div id="designer" class = "col-xs-4">
            <h6>Designed by Xavier Velez</h6>
            </div>
        </div>
    </div>

</footer>
</code>```

答:
It's actually very simple these days. One line of code.

min-height: 100vh;

https://codepen.io/rhroyston/pen/gXXMmr

Body:
https://jsfiddle.net/z4of8fvy/

I know my code is somewhat sloppy but I am still learning. I have run it through a validator to see if I had a missing  but I didn't find one. Any help would be appreciated.

If there are any other things that you guys can point out I would appreciate that as well.
It keeps asking me for more details but I don't know what else I can say. I do know that at one point the footer was working with me keeping it position: sticky and bottom:0 but when I added more content that's when the problem appeared. That is when I tried to play with it a bit and probably ruined it even more.

SMG
 Studios

Me$$ aka M.T.M

Services

Campaigns

Jey Bundy

Store

Contact

 Studio Services

 Read More

 Jey Bundy

 Read More

 Me$$ aka M.T.M

 Read More

Our Mission

                Smith media groups consist of a team of polite professionals that provide high quality and affordable service. We consider our customers family so we take pride in making our customers feel as comfortable and satisfied as possible. We offer a vast variety of services such as photoshoots, music videos, parties, wedding videos/photos, real estate photos, music production & duplication, ect. If you have any questions give us a call or use our contact form and we will give you a call. Our Vison, Your Success

                  Facebook
                 Instagram

Designed by Xavier Velez


来源: stackexchange

问:
TypeError: 'function' object is not iterable' Python 3
I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable.

```<code>import urllib.request

def readWordList():

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList()

def clean(aList):
    newList = []
    for word in aList:
        if range(len(word)) >= 2:
            newList.append(word)
    return newList

clean(clean)
</code>```

答:
Firstly you make a variable called clean and then you make a function called clean and finally you tried to use the function in the variable, both called clean. You "destroy" the variable when you defined a function. They must have different names.

Use this:

```<code>import urllib.request

    def readWordList():

    response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
    html = response.read()
    data = html.decode('utf-8').split()

    return data

    to_clean = readWordList() # Use a different name so it won't be replaced later by the function
        def clean(aList):
        newList = []
        for word in aList:
            if range(len(word)) >= 2:
                newList.append(word)
        return newList
    clean(to_clean)
</code>```

Problem solves; now they have different names.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable.

import urllib.request

def readWordList():

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList()

def clean(aList):
    newList = []
    for word in aList:
        if range(len(word)) >= 2:
            newList.append(word)
    return newList

clean(clean)

Body:
Firstly you make a variable called clean and then you make a function called clean and finally you tried to use the function in the variable, both called clean. You "destroy" the variable when you defined a function. They must have different names.

Use this:

import urllib.request

    def readWordList():

    response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
    html = response.read()
    data = html.decode('utf-8').split()

    return data

    to_clean = readWordList() # Use a different name so it won't be replaced later by the function
        def clean(aList):
        newList = []
        for word in aList:
            if range(len(word)) >= 2:
                newList.append(word)
        return newList
    clean(to_clean)

Problem solves; now they have different names.


问:
flutter.io (dart) - set padding as a percentage of device width?
How can I set padding as a percentage of screen width in Flutter?

The problem I'm trying to solve, I initially tried to solve with AspectRatio and FractionallySizedBox, as well as different attempts with Row and Columns, but the parent is a Positioned widget with a child image. Nothing worked.

答: Use MediaQuery by doing MediaQuery.of(context).size.width to get the screen width


问:
How do I save a level layout in a variable
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

```<code>import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.
</code>```

答:
You will need to calculate the pixel-positions for each tile. To draw any tile, you need to know

the size of the canvas

the size of your grid

the position of the tile in your grid

1: Finding the size of your canvas should be trivial.

2: For the second storage method you can do

```<code>height = len(level2)
width = len(level2[0]) #Assuming all rows are of equal length and there's at least one row
</code>```

3: We're going to iterate through the rows and characters which will keep track of our position in the grid on the side.

```<code>def draw_tiles(canvas_width, canvas_height, width, height, level2):
  for row in range(height):
    for column in range(width):
      if list(level2[row])[column] == 'T':
        pixel_x = int(canvas_width/width)*column
        pixel_y = int(canvas_height/height)*row
        draw_tile(pixel_x, pixel_y)
</code>```

Now all you need to do is define the draw_tile(x, y) function to draw a tile on the canvas with its top-left corner being on the pixel co-ordinates (x, y). I'm sure pygame has something for that.

Make sure you set the grid width/height so that canvas_width/width and canvas_height/height are both integers. Otherwise your tiles will be slightly offset due to rounding.

Body:
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.

Body:
You will need to calculate the pixel-positions for each tile. To draw any tile, you need to know

the size of the canvas

the size of your grid

the position of the tile in your grid

1: Finding the size of your canvas should be trivial.

2: For the second storage method you can do

height = len(level2)
width = len(level2[0]) #Assuming all rows are of equal length and there's at least one row

3: We're going to iterate through the rows and characters which will keep track of our position in the grid on the side.

def draw_tiles(canvas_width, canvas_height, width, height, level2):
  for row in range(height):
    for column in range(width):
      if list(level2[row])[column] == 'T':
        pixel_x = int(canvas_width/width)*column
        pixel_y = int(canvas_height/height)*row
        draw_tile(pixel_x, pixel_y)

Now all you need to do is define the draw_tile(x, y) function to draw a tile on the canvas with its top-left corner being on the pixel co-ordinates (x, y). I'm sure pygame has something for that.

Make sure you set the grid width/height so that canvas_width/width and canvas_height/height are both integers. Otherwise your tiles will be slightly offset due to rounding.


问:
Rails 4 - Carrierwave image not uploading
UPDATE: Thanks everyone for the help in trying to figure this out. I decided to give up trying to learn and added another image attribute to the profile model. This will have to do for now.

Im trying to make an app in rails 4.

I have a user model, which has an avatar attribute on it.

I also have a profile model.

User :has one profile
Profile :belongs to User

The reason I split them is because profile contains all the variables and user contains all the fixed attributes that cannot be changed without admin permission.

The exception is that my user model has an avatar (image) attribute which I want to allow users to change.

I have user carrierwave in other parts of my code and it works. However, something is wrong in this use case.

I have an avatar uploader with:

```<code>class AvatarUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  # storage :file
  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def cache_dir
    "#{Rails.root}/tmp/uploads"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :resize_to_fit => [50, 50]
  # end

  process :resize_to_fit => [800, 800]
  # Create different versions of your uploaded files:
  version :thumb do
    process :resize_to_fill => [200,200]
  end

  version :profile do
    process :resize_to_fill => [345,245]
  end

  version :wide do
    process :resize_to_fill => [951,245]
  end

  version :preview do
    process :resize_to_fill => [90,90]
  end

  version :small do
    process :resize_to_fill => [35,35]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
     %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end
</code>```

In my user model i have:

```<code>class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end
</code>```

In my user controller - I whitelist the :avatar in strong params.

In my profile controller strong params I've tried adding:

```<code>params.require(:profile).permit(:title, :overview, user_attributes: [:avatar])
</code>```

And I have also tried allowing user attributes in my profile model (as follows):

```<code>belongs_to :user
accepts_nested_attributes_for :user
</code>```

I have a partial form in my views users folder.

```<code><%= simple_fields_for :user,  html: { multipart: true } do |f| %>
  <%= f.error_notification %>
  <div class="form-inputs">
    <%= f.input :avatar, as: :file, :label => "Add a profile image (head shot)" %>
  </div>
<% end %>
</code>```

That partial is included in my profiles form.

I then want to display the user avatar in my profile show view as:

```<code><div class="col-md-5 col-lg-4 vc-photo" style= "background-image: url(<%= image_url @profile.user.avatar.url if @profile.user.avatar? %>);"> </div>
</code>```

However, it just renders a blank.

I tried:

);">

but it still just renders blank.

Can anyone see what I've done wrong?

When i try to test in the rails console by checking the user.avatar, I get this:

u.avatar
 => #, last_sign_in_ip: #, confirmation_token: "73abb47df224dbc3a612b46ced66e1aba...", confirmed_at: "2016-04-02 07:13:57", confirmation_sent_at: "2016-04-02 22:59:44", unconfirmed_email: "testiest@gmail.com", failed_attempts: 0, unlock_token: nil, locked_at: nil, created_at: "2016-04-02 07:13:57", updated_at: "2016-04-02 22:59:43", avatar: nil, approved: false>, @mounted_as=:avatar>

TAKING THE SUGGESTION BELOW

I change my forms so that profile form now has:

```<code>  <%= render 'users/profileimgform', f: f %>
</code>```

The users/profileimgform now has:

```<code><%= simple_fields_for :user,  html: { multipart: true } do |ff| %>
  <%= f.error_notification %>

              <div class="form-inputs">

              <%= ff.input :avatar, as: :file, :label => "Add a profile image (head shot)" %>

              </div>

        <% end %>
</code>```

I'm not sure whether I need to incorporate the 'ff' into the line in my profile form. I tried replacing the last 'f' with 'ff' but got an error asking me whether it should be a single 'f'.

When I try this, the console still shows that the user.avatar is 'nil'.

答:
I had the same error. If you're on a mac, try installing imagemagik again. I used homebrew. You just need to run this command:</p>

```<code>brew install imagemagick
</code>```

Body:
UPDATE: Thanks everyone for the help in trying to figure this out. I decided to give up trying to learn and added another image attribute to the profile model. This will have to do for now.

Im trying to make an app in rails 4.

I have a user model, which has an avatar attribute on it.

I also have a profile model.

User :has one profile
Profile :belongs to User

The reason I split them is because profile contains all the variables and user contains all the fixed attributes that cannot be changed without admin permission.

The exception is that my user model has an avatar (image) attribute which I want to allow users to change.

I have user carrierwave in other parts of my code and it works. However, something is wrong in this use case.

I have an avatar uploader with:

class AvatarUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  # storage :file
  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def cache_dir
    "#{Rails.root}/tmp/uploads"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :resize_to_fit => [50, 50]
  # end

  process :resize_to_fit => [800, 800]
  # Create different versions of your uploaded files:
  version :thumb do
    process :resize_to_fill => [200,200]
  end

  version :profile do
    process :resize_to_fill => [345,245]
  end

  version :wide do
    process :resize_to_fill => [951,245]
  end

  version :preview do
    process :resize_to_fill => [90,90]
  end

  version :small do
    process :resize_to_fill => [35,35]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
     %w(jpg jpeg gif png)
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end

In my user model i have:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

In my user controller - I whitelist the :avatar in strong params.

In my profile controller strong params I've tried adding:

params.require(:profile).permit(:title, :overview, user_attributes: [:avatar])

And I have also tried allowing user attributes in my profile model (as follows):

belongs_to :user
accepts_nested_attributes_for :user

I have a partial form in my views users folder.

<%= simple_fields_for :user,  html: { multipart: true } do |f| %>
  <%= f.error_notification %>

    <%= f.input :avatar, as: :file, :label => "Add a profile image (head shot)" %>

<% end %>

That partial is included in my profiles form.

I then want to display the user avatar in my profile show view as:

<div class="col-md-5 col-lg-4 vc-photo" style= "background-image: url(<%= image_url @profile.user.avatar.url if @profile.user.avatar? %>);">

However, it just renders a blank.

I tried:

);">

but it still just renders blank.

Can anyone see what I've done wrong?

When i try to test in the rails console by checking the user.avatar, I get this:

u.avatar
 => #, last_sign_in_ip: #, confirmation_token: "73abb47df224dbc3a612b46ced66e1aba...", confirmed_at: "2016-04-02 07:13:57", confirmation_sent_at: "2016-04-02 22:59:44", unconfirmed_email: "testiest@gmail.com", failed_attempts: 0, unlock_token: nil, locked_at: nil, created_at: "2016-04-02 07:13:57", updated_at: "2016-04-02 22:59:43", avatar: nil, approved: false>, @mounted_as=:avatar>

TAKING THE SUGGESTION BELOW

I change my forms so that profile form now has:

  <%= render 'users/profileimgform', f: f %>

The users/profileimgform now has:

<%= simple_fields_for :user,  html: { multipart: true } do |ff| %>
  <%= f.error_notification %>

              <%= ff.input :avatar, as: :file, :label => "Add a profile image (head shot)" %>

        <% end %>

I'm not sure whether I need to incorporate the 'ff' into the line in my profile form. I tried replacing the last 'f' with 'ff' but got an error asking me whether it should be a single 'f'.

When I try this, the console still shows that the user.avatar is 'nil'.

Body:
I had the same error. If you're on a mac, try installing imagemagik again. I used homebrew. You just need to run this command:

brew install imagemagick


问:
iPhone: Splash screen in app - Good or Bad?
I'm going to submit a Lifestyle app to the App Store. I'm confused whether to add a Splash Screen to the App or not ?

Please advise me whether it's a good or bad idea as far as usability and App Store's submission guidelines are concerned.

答:
if your app loads blazingly fast,then you can provide this method in

```<code>- (void)applicationDidFinishLaunching:(UIApplication *)application

[NSThread sleepForTimeInterval:3];
</code>```

Before your view controller is loaded.

It will halt the main thread for 3 seconds,which will give time to your splash screen.Thats the way i do and there is no problem with this method,as you are working on the main thread.

ContentLicense: CC BY-SA 2.5

Body:
if your app loads blazingly fast,then you can provide this method in

- (void)applicationDidFinishLaunching:(UIApplication *)application

[NSThread sleepForTimeInterval:3];

Before your view controller is loaded.

It will halt the main thread for 3 seconds,which will give time to your splash screen.Thats the way i do and there is no problem with this method,as you are working on the main thread.


问:
JavaScript variable changing between two values on a regular basis
I want a variable's value regularly changing between 0 and 1.  If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

答:
A more generic approach:

```<code>// possible addition: allow user to stop the timer
const rotate = (time, vals) => {
  // TODO: handle incorrect vals (non-empty array) or time (positive number)
  let idx = 0;
  setInterval(() => idx = (idx + 1) % vals.length, time);
  return {
    get val() {return vals[idx];}
  }
}

const toggle = rotate(1000, [0, 1])

toggle.val //=> depends on when you call it, changes every 1000 ms
           //   but always either 0 or 1.
</code>```

One advantage of this is that it doesn't keep the value in global scope where someone else can mess with it, but encapsulates it in a closure.

It's more generic because you can easily change the time between updates and you can choose whatever you want for values (for example, rotate(5000, ['foo', 'bar', 'baz').)

Body:
A more generic approach:

// possible addition: allow user to stop the timer
const rotate = (time, vals) => {
  // TODO: handle incorrect vals (non-empty array) or time (positive number)
  let idx = 0;
  setInterval(() => idx = (idx + 1) % vals.length, time);
  return {
    get val() {return vals[idx];}
  }
}

const toggle = rotate(1000, [0, 1])

toggle.val //=> depends on when you call it, changes every 1000 ms
           //   but always either 0 or 1.

One advantage of this is that it doesn't keep the value in global scope where someone else can mess with it, but encapsulates it in a closure.

It's more generic because you can easily change the time between updates and you can choose whatever you want for values (for example, rotate(5000, ['foo', 'bar', 'baz').)


问:
Angular/Ionic How do i add components to html page based on db data
Lets say that im pulling some data from firebase db with:

```<code>this.invData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}/inventory`).valueChanges());
    this.invData.subscribe(invdata =>{
    this.invData=invdata
    console.log(this.invData);
    console.log(this.invData.apple)//this returns 3
});
</code>```

i can display this number of apples on html page with {{invData.apple}} but for example if i want to put some clickable interactable components i mean radiobuttons or select components  how do i do that ?

Like if invData.apple is greater than 1  display a radiobutton if not do not display.

答:
Sounds like you're looking for ngIf: https://angular.io/api/common/NgIf

An example of what you're asking for is below (showing a button, not a radio in this case). The angular documentation will give other examples (e.g. else blocks)

```<code><p *ngIf="invData?.apple > 1">
      <button ion-button full (click)="closeModal()">
        Close
      </button>
</p>
</code>```

Body:
Lets say that im pulling some data from firebase db with:

this.invData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}/inventory`).valueChanges());
    this.invData.subscribe(invdata =>{
    this.invData=invdata
    console.log(this.invData);
    console.log(this.invData.apple)//this returns 3
});

i can display this number of apples on html page with {{invData.apple}} but for example if i want to put some clickable interactable components i mean radiobuttons or select components  how do i do that ?

Like if invData.apple is greater than 1  display a radiobutton if not do not display.

Body:
Sounds like you're looking for ngIf: https://angular.io/api/common/NgIf

An example of what you're asking for is below (showing a button, not a radio in this case). The angular documentation will give other examples (e.g. else blocks)

<p *ngIf="invData?.apple > 1">
      <button ion-button full (click)="closeModal()">
        Close
      </button>
</p>


问:
MongoDB: use createCodecProvider generically
Instead of having one hard-coded line per case class

```<code>  val codecRegistry = fromRegistries(
    fromProviders(
      classOf[CaseClassNameGoesHere],
      ...
    ),
    ...
    )
</code>```

I would like to create a method that could create them instead.

Both

```<code>  def method[T] = {
    Macros.createCodecProvider[T]()
  }
</code>```

and

```<code>  def method[T: ClassTag] = {
    Macros.createCodecProvider[T]()
  }
</code>```

... give me scala.ScalaReflectionException: type T is not a class

I would hope that the compiler could look at every invocation of this method and do its thing.

Is there a way of accomplishing that? Solutions "far away" from this approach will still be accepted as long as I don't have to create that list of classOfs.

答:
You'll just end up with more code, and more complex code, no?  When you pass classOf[Foo] to fromProviders, there's actually just an implicit createCodecProvider that takes a Class[Foo] and creates a CodecProvider for it. You're still going to have to "manually" pass all the codec providers into fromProviders, regardless of how you generate them.  i.e. you'd still end up with something like:

```<code>val codecRegistry = fromRegistries(
  fromProviders(
    method[Foo],
    method[Bar],
    ...
  )
</code>```

Body:
Instead of having one hard-coded line per case class

  val codecRegistry = fromRegistries(
    fromProviders(
      classOf[CaseClassNameGoesHere],
      ...
    ),
    ...
    )

I would like to create a method that could create them instead.

Both

  def method[T] = {
    Macros.createCodecProvider[T]()
  }

and

  def method[T: ClassTag] = {
    Macros.createCodecProvider[T]()
  }

... give me scala.ScalaReflectionException: type T is not a class

I would hope that the compiler could look at every invocation of this method and do its thing.

Is there a way of accomplishing that? Solutions "far away" from this approach will still be accepted as long as I don't have to create that list of classOfs.

Body:
You'll just end up with more code, and more complex code, no?  When you pass classOf[Foo] to fromProviders, there's actually just an implicit createCodecProvider that takes a Class[Foo] and creates a CodecProvider for it. You're still going to have to "manually" pass all the codec providers into fromProviders, regardless of how you generate them.  i.e. you'd still end up with something like:

val codecRegistry = fromRegistries(
  fromProviders(
    method[Foo],
    method[Bar],
    ...
  )


问:
Filtering and reassigning pyspark dataframe in a loop
I'm trying to iterate through all the columns of a Pyspark data frame, calculating the IQR to filter the upper outliers, and reassigning the same dataframe. There are 200+ columns. This is working, but it goes slower and slower as it advances through the loop. I suspect the problem may be in the reassignment of the dataframe (dfBufferOutlier=dfBufferOutlier.filter(col(i)

nameList=dfBuffer.schema.names[1:]
dfBufferOutlier=dfBuffer
for i in nameList:
    cuenta=dfBufferOutlier.filter(col(i)>0).count()
    if cuenta>0:
        Q1, Q2, Q3 = dfBufferOutlier.filter(col(i)>0).approxQuantile(col=i,probabilities=[0.25,0.5,0.75],relativeError=0.005)
        IQR=(Q3-Q1)
        top_limit=Q3+1.5*IQR
        dfBufferOutlier=dfBufferOutlier.filter(col(i)<top_limit)
```

There sure must be another way to get this better, but can't figure out how.. any help please?

答:
If you're willing to modify the procedure (arguably you should modify it anyway) a bit you can do everything in a single pass:

from pyspark.sql.functions import col, count, when
from functools import reduce
from operator import and_

def iqr_filter(df, cols, relativeError=0.005):
    # Find quantiles
    quantiles = (df
        # Convert values <= 0 to NULL
        .select([when(col(c) > 0, col(c)).alias(c) for c in cols])
        .approxQuantile(cols, [0.25, 0.5, 0.75], relativeError))

    # Compute thresholds
    thresholds = [
        q3 + 1.5 * (q3 - q1) for q1, _, q3 in quantiles
    ]
    # Create SQL expression of form c1 < t1 AND c2 < t2 AND ... AND cn < tn
    expr  = reduce(and_, [col(c) < t for c, t in zip(cols, thresholds)])
    # Filter
    return df.where(expr)
```

<p>Usage:</p>

```iqr_filter(dfBuffer, dfBuffer.schema.names[1:])
```

With very low relative error it might be still quite demanding job so I strongly suggest to relax it a bit, once number of columns grows.

Note that the result will be different from the one generated by your current approach:

In your case each pass computes quantiles on non-increasing set of rows, therefore it depends on the order of columns.

This computes quantiles once for all rows and doesn't depend on the order of columns.

Body:
I'm trying to iterate through all the columns of a Pyspark data frame, calculating the IQR to filter the upper outliers, and reassigning the same dataframe. There are 200+ columns. This is working, but it goes slower and slower as it advances through the loop. I suspect the problem may be in the reassignment of the dataframe (dfBufferOutlier=dfBufferOutlier.filter(col(i)

nameList=dfBuffer.schema.names[1:]
dfBufferOutlier=dfBuffer
for i in nameList:
    cuenta=dfBufferOutlier.filter(col(i)>0).count()
    if cuenta>0:
        Q1, Q2, Q3 = dfBufferOutlier.filter(col(i)>0).approxQuantile(col=i,probabilities=[0.25,0.5,0.75],relativeError=0.005)
        IQR=(Q3-Q1)
        top_limit=Q3+1.5*IQR
        dfBufferOutlier=dfBufferOutlier.filter(col(i)<top_limit)

There sure must be another way to get this better, but can't figure out how.. any help please?

Body:
If you're willing to modify the procedure (arguably you should modify it anyway) a bit you can do everything in a single pass:

from pyspark.sql.functions import col, count, when
from functools import reduce
from operator import and_

def iqr_filter(df, cols, relativeError=0.005):
    # Find quantiles
    quantiles = (df
        # Convert values <= 0 to NULL
        .select([when(col(c) > 0, col(c)).alias(c) for c in cols])
        .approxQuantile(cols, [0.25, 0.5, 0.75], relativeError))

    # Compute thresholds
    thresholds = [
        q3 + 1.5 * (q3 - q1) for q1, _, q3 in quantiles
    ]
    # Create SQL expression of form c1 < t1 AND c2 < t2 AND ... AND cn < tn
    expr  = reduce(and_, [col(c) < t for c, t in zip(cols, thresholds)])
    # Filter
    return df.where(expr)

Usage:

iqr_filter(dfBuffer, dfBuffer.schema.names[1:])

With very low relative error it might be still quite demanding job so I strongly suggest to relax it a bit, once number of columns grows.

Note that the result will be different from the one generated by your current approach:

In your case each pass computes quantiles on non-increasing set of rows, therefore it depends on the order of columns.

This computes quantiles once for all rows and doesn't depend on the order of columns.


问:
When is a value type / reference type constraint useful in C#?
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

```<code>... where T : struct  // when is this useful?
... where T : class   // and what about this?
</code>```

I remember seeing some very nice examples in the past but I just can't find them.

答:
The primary usefulness that I've found in it lies with Marshalling and pinning the object in memory.

For example, I do a lot of work with internal structures that can't be auto-converted, or are sent down the wire as a byte stream, so I wrote this helper:

```<code>public static T PinAndCast<T>(this Array o) where T : struct
{
    var handle = System.Runtime.InteropServices.GCHandle.Alloc(o, GCHandleType.Pinned);
    T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}
</code>```

Body:
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

... where T : struct  // when is this useful?
... where T : class   // and what about this?

I remember seeing some very nice examples in the past but I just can't find them.

Body:
The primary usefulness that I've found in it lies with Marshalling and pinning the object in memory.

For example, I do a lot of work with internal structures that can't be auto-converted, or are sent down the wire as a byte stream, so I wrote this helper:

public static T PinAndCast<T>(this Array o) where T : struct
{
    var handle = System.Runtime.InteropServices.GCHandle.Alloc(o, GCHandleType.Pinned);
    T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}


问:
CMS Login issue - after upgrade to silverstripe 3.5.4
There seems to have been a technical problem. Please click the back button, refresh your browser, and try again.

I am facing this error on the standard /admin login form (used for logging in to the CMS).

I have done the upgrade (3.1>3.5), after that upgrade this form was working fine for a while but then it stopped working and started throwing

"There seems to have been a technical problem. Please click the back button, refresh your browser, and try again."

Upon investigation found, the Form.php in the framework class is throwing this error. Please note the framework version is now 3.5.4

Any help/pointers if someone faced the same issue upon upgrade ??

Thanks

答:
I would try a dev/build?flush=all. I'm pretty sure that the Member class has had additional fields added after 3.1

You can always put your site in dev mode to see the errors.


问:
Conditional formatting based on number and symbol
This is an odd question. I have an issue I need to highlight a cell based on value, but it has a symbol in it and I cNt remove the symbol.

Value ranges are 1+   3+    5+  etc..

Need to highlight  for each series  higher than 1 but less than 3.   Higher than 3 but less than 7.   Etc...

Hope that makes sense.
Thanks
Casey

答:
You should still be able to evaluate the number with the symbol after it, Excel should treat it as text where 1+ is still less than 3+ or 5+ is greather than 3+.

In your conditional formatting the rule would look something like this;

```<code>Cell Value <= $D$1
</code>```

Where $D$1 is your selectable list which i'm assuming is possibly a validation list.

The format for the condition is whichever color you want it to highlight, and the Applies to part of the condition would be the range that you want to check against i.e. =$A:$A where all the 1+,3+,5+ numbers are.

This doesn't get you the whole answer but it should point you in the direction of setting your conditional formats.

Body:
You should still be able to evaluate the number with the symbol after it, Excel should treat it as text where 1+ is still less than 3+ or 5+ is greather than 3+.

In your conditional formatting the rule would look something like this;

Cell Value <= $D$1

Where $D$1 is your selectable list which i'm assuming is possibly a validation list.

The format for the condition is whichever color you want it to highlight, and the Applies to part of the condition would be the range that you want to check against i.e. =$A:$A where all the 1+,3+,5+ numbers are.

This doesn't get you the whole answer but it should point you in the direction of setting your conditional formats.


问:
SharePoint2013 - Javascript - Pagination in client side- Using listitemcollectionposition
I am getting data from a sharepoint list based on certain filter criteria.

I am getting the records using javascript object model. This is working fine.

I am facing issue with pagination.

I have referred this article :

http://social.technet.microsoft.com/wiki/contents/articles/18606.sharepoint-2013-paging-with-sharepoint-client-object-model.aspx

This works for "Next Page".
Doesnt work for "Previous Page" in my case, because the values are retrieved randomly. So,the IDs are not consecutive.

Does "listItemCollectionPosition" work only for data which is consecutive?

```<code>previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + myListItems.itemAt(0).get_item('ID');
</code>```

This code doesnt work properly, some records are getting missed out.

答:
You can find a good example here, how to page in CSOM:
https://code.msdn.microsoft.com/office/SharePoint-JSOM-list-5104ca92

There are some articles that gives you the following answers about paging in Sharepoint 2013.

A very important consideration to take into account:
- with JSOM or the classic webservices svc/asmx or oData, you cannot use the "$skip" particle to do paging of listitems. So it is OOTB almost impossible to do a true paging with numbers.
For items, you have to use listItemCollectionPosition in your SOAP or using $skiptoken (oData).
The only paging possible is previous/next.

Body:
I am getting data from a sharepoint list based on certain filter criteria.

I am getting the records using javascript object model. This is working fine.

I am facing issue with pagination.

I have referred this article :

http://social.technet.microsoft.com/wiki/contents/articles/18606.sharepoint-2013-paging-with-sharepoint-client-object-model.aspx

This works for "Next Page".
Doesnt work for "Previous Page" in my case, because the values are retrieved randomly. So,the IDs are not consecutive.

Does "listItemCollectionPosition" work only for data which is consecutive?

previousPagingInfo = "PagedPrev=TRUE&Paged=TRUE&p_ID=" + myListItems.itemAt(0).get_item('ID');

This code doesnt work properly, some records are getting missed out.


问:
How can I prevent duplication in event listener in vanilla javascript?
For some reason the amount of 1's duplicates every time a category is chosen. If the oneBtn is clicked, I want there to only be a single 1 added to the text field per click. In other words, for each time the category is changed (thisOne or thatOne), another 1 is strung along when the oneBtn is clicked. so if the category is changed twice, the oneBtn will input 11 per click. I would like to understand why this is happening and if it can be remedied in vanilla js.

My guess is that somewhere there is a count of clicks being storing away  and maybe that's whats affecting the outcome. If thats true, is there a way to reset this count to zero for each time a catgory is changed to prevent the duplication? I might be way off, i'm just guessing here.

/*GET MEAL CATEGORY ITEMS*/
  let thisOne = document.getElementById('thisOne');
  let thatOne = document.getElementById('thatOne');

function addOne(x){
    /*GET OPTION ITEMS*/
      let oneBtn = document.getElementById('oneBtn');
      let inputText = document.getElementById('inputText');

    /*FUNCTION TO CHANGE CATEGORY HEADER*/
      let changeHeader = () => {
        let header = document.getElementById('header');
        header.innerHTML = x.target.innerHTML;
       }; changeHeader();

    /*FUNCTION TO ADD 1 TO TEXTFIELD*/
      let addInput = (x) => {
        inputText.value += x.target.innerHTML;
       }
    oneBtn.addEventListener('click', addInput);
};

thisOne.addEventListener('click', addOne);
thatOne.addEventListener('click', addOne);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Choose category</h1>
<button class="category" id="thisOne">thisOne</button>
<button class="category" id="thatOne">thatOne</button>
<br /><br />

<div>
<h3 id="header"></h3>
  <input id="inputText" type="textfield" /><br /><br />
    <button id="oneBtn">1</button>
</div></code>```

答:
Every time you click on thisOne thatOne you attach another eventListener to the oneBtn. So all the eventListeners are executed one after the other.

Move the eventListener outside of the addOne function and it should work as expected.

Body:
For some reason the amount of 1's duplicates every time a category is chosen. If the oneBtn is clicked, I want there to only be a single 1 added to the text field per click. In other words, for each time the category is changed (thisOne or thatOne), another 1 is strung along when the oneBtn is clicked. so if the category is changed twice, the oneBtn will input 11 per click. I would like to understand why this is happening and if it can be remedied in vanilla js.

My guess is that somewhere there is a count of clicks being storing away  and maybe that's whats affecting the outcome. If thats true, is there a way to reset this count to zero for each time a catgory is changed to prevent the duplication? I might be way off, i'm just guessing here.

/*GET MEAL CATEGORY ITEMS*/
  let thisOne = document.getElementById('thisOne');
  let thatOne = document.getElementById('thatOne');

function addOne(x){
    /*GET OPTION ITEMS*/
      let oneBtn = document.getElementById('oneBtn');
      let inputText = document.getElementById('inputText');

    /*FUNCTION TO CHANGE CATEGORY HEADER*/
      let changeHeader = () => {
        let header = document.getElementById('header');
        header.innerHTML = x.target.innerHTML;
       }; changeHeader();

    /*FUNCTION TO ADD 1 TO TEXTFIELD*/
      let addInput = (x) => {
        inputText.value += x.target.innerHTML;
       }
    oneBtn.addEventListener('click', addInput);
};

thisOne.addEventListener('click', addOne);
thatOne.addEventListener('click', addOne);

Choose category

<button class="category" id="thisOne">thisOne</button>
<button class="category" id="thatOne">thatOne</button>

  <input id="inputText" type="textfield" />

    <button id="oneBtn">1</button>


问:
My col-xs-12 is ruining my row in tablet and desktop mode

.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: 10px;
    padding-left: 10px;
}
.col-md-15 img {
    height: 200px;
    width: 200px;
}
.margin20
{
 margin-top: 20px;
}
/*new set of column*/
.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: 768px) {
 /*even if i remove this nothing happen*/
.col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 992px) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 1200px) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}
*overlay*/
.img-container {
    position: relative;
    width: 100%;
}
.red {
  background-color: #B2B2B2;
}
.image {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.img-container .image {
  opacity: 0.3;
}

.img-container .middle {
  opacity: 1;
}

.text {
  background-color: transparent;
  color: white;
  font-size: 24px;
  padding: 16px 32px;
  font-family: 'Archivo Black', sans-serif;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="Custom.css" type="text/css"/>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
 <link href="https://fonts.googleapis.com/css?family=Lato|Ubuntu" rel="stylesheet">
 <link href="https://fonts.googleapis.com/css?family=Archivo+Black" rel="stylesheet">
<div class="container">
<div class="row">
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="img/sample.png" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
   </div>
   <div class="row margin20">
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
    <div class="col-md-15 col-sm-15 col-xs-12">
     <div class="img-container red">
       <img src="https://introcs.cs.princeton.edu/java/stdlib/mandrill200x200.jpg" alt="Avatar" class="image" style="width:100%">
       <div class="middle">
         <div class="text">MEN'S APPAREL</div>
       </div>
     </div>
    </div>
   </div>
  </div></code>```

I want to divide my row in 5 equal parts that is why i used col-md-15 and col-sm-15, it is working well in tablet,mobile,and desktop (if you will remove the col-xs-12 in every tag), however in mobile mode i want the images to be 1 per row that is why i inserted col-xs-12, however when i did that, the rows in tablet and desktop mode became 1 per row and stretched which is i dont want. How to fix this problem?

答:
```<code><link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="Custom.css" type="text/css"/>
</code>```

You load custom css before bootstrap css, switch that around.

Edited the example, sry, I meant the other way around. Custom css last, so it overrides the other code.

Body:
.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: 10px;
    padding-left: 10px;
}
.col-md-15 img {
    height: 200px;
    width: 200px;
}
.margin20
{
 margin-top: 20px;
}
/*new set of column*/
.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: 768px) {
 /*even if i remove this nothing happen*/
.col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 992px) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 1200px) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}
*overlay*/
.img-container {
    position: relative;
    width: 100%;
}
.red {
  background-color: #B2B2B2;
}
.image {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.img-container .image {
  opacity: 0.3;
}

.img-container .middle {
  opacity: 1;
}

.text {
  background-color: transparent;
  color: white;
  font-size: 24px;
  padding: 16px 32px;
  font-family: 'Archivo Black', sans-serif;
  text-align: center;
}

<meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="Custom.css" type="text/css"/>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
 <link href="https://fonts.googleapis.com/css?family=Lato|Ubuntu" rel="stylesheet">
 <link href="https://fonts.googleapis.com/css?family=Archivo+Black" rel="stylesheet">

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

MEN'S APPAREL

I want to divide my row in 5 equal parts that is why i used col-md-15 and col-sm-15, it is working well in tablet,mobile,and desktop (if you will remove the col-xs-12 in every tag), however in mobile mode i want the images to be 1 per row that is why i inserted col-xs-12, however when i did that, the rows in tablet and desktop mode became 1 per row and stretched which is i dont want. How to fix this problem?

Body:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="Custom.css" type="text/css"/>

You load custom css before bootstrap css, switch that around.

Edited the example, sry, I meant the other way around. Custom css last, so it overrides the other code.


问:
Convert attribute value into element
I'm trying to transform this xml:

```<code><tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>
</code>```

into this xml:

```<code><tokens>
 <a>
  <b>nomX</b>
  <c>prenomX</c>
  <d>villeX</d>
 </a>
 <a>
  <b>nomY</b>
  <c>prenomY</c>
  <d>villeY</d>
 </a>
 <e>nomZ</e>
</tokens>
</code>```

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

答:
This should do the trick:

```<code><xsl:template match="token">
  <xsl:element name="{@cle}">
    <xsl:apply-templates select="*|@*"/>
  </xsl:element>
</xsl:template>
</code>```

for more info on xsl:element see:
http://www.w3.org/TR/xslt#section-Creating-Elements-with-xsl:element

you might want to add some xsl:if to check if there really is a @cle attribute, but otherwise this should work fine

Title: Convert attribute value into element

Body:
I'm trying to transform this xml:

<tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>

into this xml:

<tokens>

  nomX
  <c>prenomX</c>
  <d>villeX</d>

  nomY
  <c>prenomY</c>
  <d>villeY</d>

 <e>nomZ</e>
</tokens>

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

Body:
This should do the trick:

<xsl:template match="token">
  <xsl:element name="{@cle}">
    <xsl:apply-templates select="*|@*"/>
  </xsl:element>
</xsl:template>

for more info on xsl:element see:
http://www.w3.org/TR/xslt#section-Creating-Elements-with-xsl:element

you might want to add some xsl:if to check if there really is a @cle attribute, but otherwise this should work fine


问:
Tensorflow unexpectedly caching sub-graph results
I'm currently trying to make an augmentation class for TF like so:

```<code>    class Augmentations:

        def __init__(self, **kwargs):
            # Some Global Kwargs Define Here
            self.transforms = tf.eye(3)

            self.img_height = kwargs['img_height']
            self.img_width = kwargs['img_width']

        def _generate_random(self, shape, seed, minval, maxval):
            return tf.random_uniform(shape=shape,
                                     minval=minval,
                                     maxval=maxval,
                                     seed=seed,
                                     dtype=tf.float32)

        def rotate(self, seed, max_angle):
            random_rotation_value = self._generate_random([1], seed, 0., max_angle)
            rotation_matrix = tf.contrib.image.angles_to_projective_transforms(
                                random_rotation_value,
                                self.img_height,
                                self.img_width)

            rotation_matrix = tf.reshape(tf.concat([rotation_matrix, [[1.]]], axis=1),
                                         [3, 3])

            self.transforms = tf.matmul(self.transforms, rotation_matrix)
            return self

        def apply(self, img):
            t = tf.reshape(tf.matmul(self.transforms[0],
                                     self.transforms[1]),
                           [1, 9])[0, :8]
            return tf.contrib.image.transform(img, t)
</code>```

I've tried both the dataset.map and tf.map_fn with both returning a consistent transform, i.e.:

```<code>augment = Augment(**kwargs).rotate(None, 30).shear(None, 30)
dataset = dataset.map(augment.apply, num_parallel_calls=10)
</code>```

and

```<code>augment = Augment(**kwargs).rotate(None, 30).shear(None, 30)
dataset = tf.map_fn(augment.apply)
</code>```

Both of these calls return different images with the same transforms applied.

The only way to return the images with random transforms is call the transform in the map():

```<code>dataset = dataset.map(Augment(**kwargs).rotate(None, 30).shear(None, 30).apply, num_parallel_calls=10)
</code>```

or move all of the random numbers into the apply().

Does the placement of random_*() calls matter in TF, I was under the idea that the placement would not matter, does it only matter for the map_fn?

答:
This is intended behavior because all the calls to your apply method share the same tf.random_uniform operation. When you invoke session.run this random operation is evaluated once and its result is used for all elements.

Invoking tf.random_uniform in apply makes a difference because you will create multiple random ops and each one will produce a different random sequence. It is basically the difference between:

```<code>sess = tf.InteractiveSession()
x = tf.random_uniform((1,))
y = tf.stack([x * tf.constant(1.0), x * tf.constant(1.0)])
y.eval()
# Prints
#   array([[ 0.67649043],
#          [ 0.67649043]], dtype=float32)
# because there is only one random operation in the graph and it is evaluated once.
</code>```

and

```<code>sess = tf.InteractiveSession()
y = tf.stack([tf.random_uniform((1,)) * tf.constant(1.0), tf.random_uniform((1,)) * tf.constant(1.0)])
y.eval()
# Prints
# array([[ 0.08824277],
#        [ 0.4801079 ]], dtype=float32)
# because there are two random operations in the graph and each yields a different value when evaluated
</code>```

It is pretty fundamental that tensorflow evaluates an op at most once per session.run() call (assuming it is not in a while loop or similar).

Body:
I'm currently trying to make an augmentation class for TF like so:

    class Augmentations:

        def __init__(self, **kwargs):
            # Some Global Kwargs Define Here
            self.transforms = tf.eye(3)

            self.img_height = kwargs['img_height']
            self.img_width = kwargs['img_width']

        def _generate_random(self, shape, seed, minval, maxval):
            return tf.random_uniform(shape=shape,
                                     minval=minval,
                                     maxval=maxval,
                                     seed=seed,
                                     dtype=tf.float32)

        def rotate(self, seed, max_angle):
            random_rotation_value = self._generate_random([1], seed, 0., max_angle)
            rotation_matrix = tf.contrib.image.angles_to_projective_transforms(
                                random_rotation_value,
                                self.img_height,
                                self.img_width)

            rotation_matrix = tf.reshape(tf.concat([rotation_matrix, [[1.]]], axis=1),
                                         [3, 3])

            self.transforms = tf.matmul(self.transforms, rotation_matrix)
            return self

        def apply(self, img):
            t = tf.reshape(tf.matmul(self.transforms[0],
                                     self.transforms[1]),
                           [1, 9])[0, :8]
            return tf.contrib.image.transform(img, t)

I've tried both the dataset.map and tf.map_fn with both returning a consistent transform, i.e.:

augment = Augment(**kwargs).rotate(None, 30).shear(None, 30)
dataset = dataset.map(augment.apply, num_parallel_calls=10)

and

augment = Augment(**kwargs).rotate(None, 30).shear(None, 30)
dataset = tf.map_fn(augment.apply)

Both of these calls return different images with the same transforms applied.

The only way to return the images with random transforms is call the transform in the map():

dataset = dataset.map(Augment(**kwargs).rotate(None, 30).shear(None, 30).apply, num_parallel_calls=10)

or move all of the random numbers into the apply().

Does the placement of random_*() calls matter in TF, I was under the idea that the placement would not matter, does it only matter for the map_fn?

Body:
This is intended behavior because all the calls to your apply method share the same tf.random_uniform operation. When you invoke session.run this random operation is evaluated once and its result is used for all elements.

Invoking tf.random_uniform in apply makes a difference because you will create multiple random ops and each one will produce a different random sequence. It is basically the difference between:

sess = tf.InteractiveSession()
x = tf.random_uniform((1,))
y = tf.stack([x * tf.constant(1.0), x * tf.constant(1.0)])
y.eval()
# Prints
#   array([[ 0.67649043],
#          [ 0.67649043]], dtype=float32)
# because there is only one random operation in the graph and it is evaluated once.

and

sess = tf.InteractiveSession()
y = tf.stack([tf.random_uniform((1,)) * tf.constant(1.0), tf.random_uniform((1,)) * tf.constant(1.0)])
y.eval()
# Prints
# array([[ 0.08824277],
#        [ 0.4801079 ]], dtype=float32)
# because there are two random operations in the graph and each yields a different value when evaluated

It is pretty fundamental that tensorflow evaluates an op at most once per session.run() call (assuming it is not in a while loop or similar).


问:
hibernate updating entity attributes to null which are not in form submit
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

```<code><form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

            <!--  first form group  -->
            <div class="form-group">

                <label class="control-label col-xs-2">First Name</label>
                <div class="col-xs-2">
                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />
                </div>

                <label class="control-label col-xs-2">Last Name</label>
                <div class="col-xs-3">
                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

            <!--  first form group end  -->
            </div>
            <br/><br/>

            <!--  third form group  -->
                <div class="form-group">
                    <label class="control-label col-xs-2">Email Address</label>
                    <div class="col-xs-2">
                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />
                    </div>

            </div>

            <div class="form-group">
                                    <div class="col-xs-2">
                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>
</code>```

Controller :

```<code>@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}
</code>```

DAO :

```<code>@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }
</code>```

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

答:
Consider annotating your entity with org.hibernate.annotations.Entity.

```<code>@Entity
@Table(name = "user")
@org.hibernate.annotations.Entity(
        dynamicInsert = true, dynamicUpdate=true
)
public class User implements java.io.Serializable {
 // your properties
}
</code>```

If you are using a 4.x version of Hibernate, you may want to use @DynamicUpdate instead since the usage of @org.hibernate.annotations.Entity has been deprecated recently.

References:

https://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/Entity.html
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/DynamicInsert.html
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/DynamicUpdate.html

Body:
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

<form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

                First Name

                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />

                Last Name

                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

                    Email Address

                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />

                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>

Controller :

@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}

DAO :

@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

Body:
Consider annotating your entity with org.hibernate.annotations.Entity.

@Entity
@Table(name = "user")
@org.hibernate.annotations.Entity(
        dynamicInsert = true, dynamicUpdate=true
)
public class User implements java.io.Serializable {
 // your properties
}

If you are using a 4.x version of Hibernate, you may want to use @DynamicUpdate instead since the usage of @org.hibernate.annotations.Entity has been deprecated recently.

References:

https://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/Entity.html
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/DynamicInsert.html
https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/DynamicUpdate.html


问:
Docker image fails in CentOS but works on MacOS
I'm using the following Dockerfile:

```<code>FROM centos
RUN yum -y -q install epel-release && yum -y -q update && yum clean all \
&& yum -y -q install python-pip
COPY requirements.txt /tmp/
RUN pip install -q pyvmomi==6.5.0.2017.5.post1
</code>```

Not sure why it does work fine on MacOS using docker 17.09.0-ce but it does not using CentOS with docker 17.11.0-ce-rc3. There is an error in the pip installation, in this example I use pyvmomi but I have a similar error with other packages.

```<code>Step 3/3 : RUN pip install pyvmomi==6.5.0.2017.5.post1
 ---> Running in 49d94b300e7f
Collecting pyvmomi==6.5.0.2017.5.post1
  Downloading pyvmomi-6.5.0.2017.5-1.tar.gz (252kB)
Collecting requests>=2.3.0 (from pyvmomi==6.5.0.2017.5.post1)
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
Collecting six>=1.7.3 (from pyvmomi==6.5.0.2017.5.post1)
  Downloading six-1.11.0-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
Collecting idna<2.7,>=2.5 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
Collecting urllib3<1.23,>=1.21.1 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
Installing collected packages: certifi, chardet, idna, urllib3, requests, six, pyvmomi
  Found existing installation: chardet 2.2.1
    Uninstalling chardet-2.2.1:
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 326, in run
    strip_file_prefix=options.strip_file_prefix,
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 736, in install
    requirement.uninstall(auto_confirm=True)
  File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/usr/lib64/python2.7/shutil.py", line 299, in move
    rmtree(src)
  File "/usr/lib64/python2.7/shutil.py", line 256, in rmtree
    onerror(os.rmdir, path, sys.exc_info())
  File "/usr/lib64/python2.7/shutil.py", line 254, in rmtree
    os.rmdir(path)
OSError: [Errno 39] Directory not empty: '/usr/lib/python2.7/site-packages/chardet'
</code>```

Any idea why the same image fails to build across different operating systems? Also I tried this using ubuntu as the docker image and works perfect in both.
Thanks.

答:
The error is caused by a conflict between the chardet package installed by epel-release
see epel package list and the one required by that specific version of pyvmomi.

Use the OS package version to avoid this conflict i.e. yum -q install python2-pyvmomi

The non-deterministic appearance of this error will be due to changes upstream in package verions in epel-release and those used in pip install

Body:
I'm using the following Dockerfile:

FROM centos
RUN yum -y -q install epel-release && yum -y -q update && yum clean all \
&& yum -y -q install python-pip
COPY requirements.txt /tmp/
RUN pip install -q pyvmomi==6.5.0.2017.5.post1

Not sure why it does work fine on MacOS using docker 17.09.0-ce but it does not using CentOS with docker 17.11.0-ce-rc3. There is an error in the pip installation, in this example I use pyvmomi but I have a similar error with other packages.

Step 3/3 : RUN pip install pyvmomi==6.5.0.2017.5.post1
 ---> Running in 49d94b300e7f
Collecting pyvmomi==6.5.0.2017.5.post1
  Downloading pyvmomi-6.5.0.2017.5-1.tar.gz (252kB)
Collecting requests>=2.3.0 (from pyvmomi==6.5.0.2017.5.post1)
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
Collecting six>=1.7.3 (from pyvmomi==6.5.0.2017.5.post1)
  Downloading six-1.11.0-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
Collecting chardet<3.1.0,>=3.0.2 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
Collecting idna<2.7,>=2.5 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
Collecting urllib3<1.23,>=1.21.1 (from requests>=2.3.0->pyvmomi==6.5.0.2017.5.post1)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
Installing collected packages: certifi, chardet, idna, urllib3, requests, six, pyvmomi
  Found existing installation: chardet 2.2.1
    Uninstalling chardet-2.2.1:
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 326, in run
    strip_file_prefix=options.strip_file_prefix,
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 736, in install
    requirement.uninstall(auto_confirm=True)
  File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/usr/lib64/python2.7/shutil.py", line 299, in move
    rmtree(src)
  File "/usr/lib64/python2.7/shutil.py", line 256, in rmtree
    onerror(os.rmdir, path, sys.exc_info())
  File "/usr/lib64/python2.7/shutil.py", line 254, in rmtree
    os.rmdir(path)
OSError: [Errno 39] Directory not empty: '/usr/lib/python2.7/site-packages/chardet'

Any idea why the same image fails to build across different operating systems? Also I tried this using ubuntu as the docker image and works perfect in both.
Thanks.


问:
Can't get data out of service in angularjs
I'm using a service in order to pass data between different instances of an AngularJS controller. I know that this is not the best way to do it but it's the way that fits my case. The problem is that I cannot get data out of that Service.

```<code>var app = angular.module('MovieApp', ['ngResource']);

app.factory('factMovies', function($resource) { //this returns some movies from MongoDB
  return $resource('/movies');
});

app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function() {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        return tempDataset;
      }
    });
  };
});

app.controller('TileController', function(SnapshotService) {
  this.dataset = [];
  this.filters = [];
  this.init = function() {
    var ctrl = this;
    var data = SnapshotService.init(function() {
      console.log(ctrl.data); //doesn't even get to the callback function
    });
  };
});
</code>```

I really can't figure out what I'm doing wrong..

答:
SnapshotService.init() doesn't take any parameters - meaning the anonymous function you pass in with the SnapshotService.init() call in TileController does nothing.

What you need to do is add the parameter to the init function definition and then call it in the code:

```<code>app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function(cb) {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        cb(ctrl.snapshots);
      }
    });
  };
});
</code>```

Body:
I'm using a service in order to pass data between different instances of an AngularJS controller. I know that this is not the best way to do it but it's the way that fits my case. The problem is that I cannot get data out of that Service.

var app = angular.module('MovieApp', ['ngResource']);

app.factory('factMovies', function($resource) { //this returns some movies from MongoDB
  return $resource('/movies');
});

app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function() {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        return tempDataset;
      }
    });
  };
});

app.controller('TileController', function(SnapshotService) {
  this.dataset = [];
  this.filters = [];
  this.init = function() {
    var ctrl = this;
    var data = SnapshotService.init(function() {
      console.log(ctrl.data); //doesn't even get to the callback function
    });
  };
});

I really can't figure out what I'm doing wrong..

Body:
SnapshotService.init() doesn't take any parameters - meaning the anonymous function you pass in with the SnapshotService.init() call in TileController does nothing.

What you need to do is add the parameter to the init function definition and then call it in the code:

app.service('SnapshotService', function(factMovies) {
  //this is used to pass data to different instances of the same controller
  //omitted getters/setters
  this.snapshots = [];

  this.init = function(cb) {
    var ctrl = this;
    var resp = factMovies.query({}, function() {
      if (resp.error) {
        console.log(resp.error)
      } else {
        tempDataset = []
        //do stuff and put the results in tempDataset
        ctrl.snapshots.push(tempDataset);
        console.log(tempDataset); //prints fine
        cb(ctrl.snapshots);
      }
    });
  };
});


问:
Array class and IEnumerable<T>
I have 2 questions about the following code:

```<code> IEnumerable<int> arr = new int[] { 2, 17, 4, 6 };
 Console.WriteLine(arr.GetType());
</code>```

The output is:

```<code> System.Int32[]
</code>```

What is the class of "arr" variable? is it Array class? Does Array class equal every XXX[]?

if arr is from Array class, how is it successfully converted to IEnumerable(int) interface? I see that Array implements only IEnumerable, but not IEnumerable(T)

Thanks

答:
The type is System.Int32[]. Yes, this is an instance of the Array class. Edit: See Hans' comment below.

From the documentation of Array Class: https://msdn.microsoft.com/en-us/library/system.array.aspx

Starting with the .NET Framework 2.0, the Array class implements the
  System.Collections.Generic.IList<T>,
  System.Collections.Generic.ICollection<T>, and
  System.Collections.Generic.IEnumerable<T> generic interfaces. The
  implementations are provided to arrays at run time, and as a result,
  the generic interfaces do not appear in the declaration syntax for the
  Array class

Title: Array class and IEnumerable<T>

Body:
I have 2 questions about the following code:

 IEnumerable<int> arr = new int[] { 2, 17, 4, 6 };
 Console.WriteLine(arr.GetType());

The output is:

 System.Int32[]

What is the class of "arr" variable? is it Array class? Does Array class equal every XXX[]?

if arr is from Array class, how is it successfully converted to IEnumerable(int) interface? I see that Array implements only IEnumerable, but not IEnumerable(T)

Thanks


问:
React browserHistory.push giving Uncaught TypeError: Cannot read property 'push' of undefined
I am trying to change the page on click.
Here is the click function

```<code>import React, { Component } from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom';
import { browserHistory } from 'react-router';
class Buttons extends Component {
skipClick(){
    browserHistory.push('/sessionstate2');
}
render() {
return (<a className={skipShow} onClick={this.skipClick}>Skip</a>)
}
}
</code>```

and index.js

```<code>import browserHistory from 'react-router';
ReactDOM.render(
    <Router history={browserHistory}>
    <div>
      <Route exact path="/" component={App} />
      <Route exact path="/sessionstate1" component={Template1}/>
      <Route exact path="/sessionstate2" component={Template2}/>
      <Route exact path="/sessionstate3" component={Template3}/>
</div>
  </Router>,
   document.getElementById('root')
 );
</code>```

It is giving

Uncaught TypeError: Cannot read property 'push' of undefined

Can you please tell me what am I doing wrong here?

答:
You don't need to use browserHistory anymore.
React-router-dom inject into your component route related props and context.
One of these props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

```<code>redirectToSessionStatePage() {
 this.props.history.push('/sessionstate2'); OR
 this.context.router.history.push('/sessionstate2');
}
</code>```

while in a function base stateless component

```<code>redirectToSessionStatePage() {
 props.history.push('/sessionstate2'); OR
 context.router.history.push('/sessionstate2');
}
</code>```

Body:
I am trying to change the page on click.
Here is the click function

import React, { Component } from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom';
import { browserHistory } from 'react-router';
class Buttons extends Component {
skipClick(){
    browserHistory.push('/sessionstate2');
}
render() {
return (Skip)
}
}

and index.js

import browserHistory from 'react-router';
ReactDOM.render(
    <Router history={browserHistory}>

      <Route exact path="/" component={App} />
      <Route exact path="/sessionstate1" component={Template1}/>
      <Route exact path="/sessionstate2" component={Template2}/>
      <Route exact path="/sessionstate3" component={Template3}/>

  </Router>,
   document.getElementById('root')
 );

It is giving

Uncaught TypeError: Cannot read property 'push' of undefined

Can you please tell me what am I doing wrong here?

Body:
You don't need to use browserHistory anymore.
React-router-dom inject into your component route related props and context.
One of these props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

redirectToSessionStatePage() {
 this.props.history.push('/sessionstate2'); OR
 this.context.router.history.push('/sessionstate2');
}

while in a function base stateless component

redirectToSessionStatePage() {
 props.history.push('/sessionstate2'); OR
 context.router.history.push('/sessionstate2');
}


问:
Repeat Customers with multiple purchases on the same day counts a 1
I am trying to wrap my head around this problem.  I was asked to create a report that show repeat customers in our database.

One of the requirements is if a customer has more than 1 order on a specific date, it would only count as 1.
Then if they have more than 1 purchase date, they would then count as a repeat customer.

Searching on here, I found this which works for finding the Customers with more then 1 purchase on a specific purchase date.

```<code>SELECT DISTINCT s.[CustomerName], s.PurchaseDate

FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''

GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)

HAVING COUNT(*) > 1;
</code>```

This MSSQL code works like it should, by showing customers who had more than 1 purchase on the same date.
My problem is what would the best approach be to Join this into another query (this is where i need help) that then shows a complete repeat customer list where customers with more than 1 purchase would be returned.

I am using MSSQL.  Any help would be greatly appreciated.

答:
If you want to pass a parameter to a query and join the result, that's what table-valued functions are for. When you join it, you use CROSS APPLY or OUTER APPLY instead of an INNER JOIN or a LEFT JOIN.

Also, I think this goes without saying, but when you check if PurchaseDate is empty:

```<code>WHERE s.PurchaseDate <> ''
</code>```

Could be issues there... it implies it's a varchar field instead of a datetime (yes?) and doesn't handle null values. You might, at least, want to replace that with ISNULL(s.PurchaseDate, '') <> ''. If it's actually a datetime, use IS NOT NULL instead of <> ''.

(Edited to add sample data and DDL statements. I recommend adding these to SQL posts to assist answerers. Also, I made purchasedate a varchar instead of a datetime because of the string comparison in the query.)

https://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx

```<code>CREATE TABLE company (company_name VARCHAR(25))
INSERT INTO company VALUES ('Company1'), ('Company2')

CREATE TABLE vw_repeat (customername VARCHAR(25), purchasedate VARCHAR(25), company VARCHAR(25))
INSERT INTO vw_repeat VALUES ('Cust1', '11/16/2017', 'Company1')
INSERT INTO vw_repeat VALUES ('Cust1', '11/16/2017', 'Company1')
INSERT INTO vw_repeat VALUES ('Cust2', '11/16/2017', 'Company2')

CREATE FUNCTION [dbo].tf_customers
(
    @company varchar(25)
)
RETURNS TABLE AS RETURN
(
    SELECT s.[CustomerName], cast(s.PurchaseDate as date) PurchaseDate
    FROM vw_Repeat s
    WHERE s.PurchaseDate <> '' AND s.Company = @company
    GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)
    HAVING COUNT(*) > 1
)
GO

SELECT *
FROM company c
CROSS APPLY tf_customers(c.company_name)
</code>```

Body:
I am trying to wrap my head around this problem.  I was asked to create a report that show repeat customers in our database.

One of the requirements is if a customer has more than 1 order on a specific date, it would only count as 1.
Then if they have more than 1 purchase date, they would then count as a repeat customer.

Searching on here, I found this which works for finding the Customers with more then 1 purchase on a specific purchase date.

SELECT DISTINCT s.[CustomerName], s.PurchaseDate

FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''

GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)

HAVING COUNT(*) > 1;

This MSSQL code works like it should, by showing customers who had more than 1 purchase on the same date.
My problem is what would the best approach be to Join this into another query (this is where i need help) that then shows a complete repeat customer list where customers with more than 1 purchase would be returned.

I am using MSSQL.  Any help would be greatly appreciated.

Body:
If you want to pass a parameter to a query and join the result, that's what table-valued functions are for. When you join it, you use CROSS APPLY or OUTER APPLY instead of an INNER JOIN or a LEFT JOIN.

Also, I think this goes without saying, but when you check if PurchaseDate is empty:

WHERE s.PurchaseDate <> ''

Could be issues there... it implies it's a varchar field instead of a datetime (yes?) and doesn't handle null values. You might, at least, want to replace that with ISNULL(s.PurchaseDate, '') <> ''. If it's actually a datetime, use IS NOT NULL instead of <> ''.

(Edited to add sample data and DDL statements. I recommend adding these to SQL posts to assist answerers. Also, I made purchasedate a varchar instead of a datetime because of the string comparison in the query.)

https://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx

CREATE TABLE company (company_name VARCHAR(25))
INSERT INTO company VALUES ('Company1'), ('Company2')

CREATE TABLE vw_repeat (customername VARCHAR(25), purchasedate VARCHAR(25), company VARCHAR(25))
INSERT INTO vw_repeat VALUES ('Cust1', '11/16/2017', 'Company1')
INSERT INTO vw_repeat VALUES ('Cust1', '11/16/2017', 'Company1')
INSERT INTO vw_repeat VALUES ('Cust2', '11/16/2017', 'Company2')

CREATE FUNCTION [dbo].tf_customers
(
    @company varchar(25)
)
RETURNS TABLE AS RETURN
(
    SELECT s.[CustomerName], cast(s.PurchaseDate as date) PurchaseDate
    FROM vw_Repeat s
    WHERE s.PurchaseDate <> '' AND s.Company = @company
    GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)
    HAVING COUNT(*) > 1
)
GO

SELECT *
FROM company c
CROSS APPLY tf_customers(c.company_name)