问:
Trouble removing Stop Words python
I need to remove stop words from a movie transcript, the stop words and transcript are in separate text files.

```<code>def stopWords():
    fi = open('stoplist.txt', 'r')
    stopWords = []
    for line in fi:
        line = line.strip()
        stopWords.append(line)
    fi.close
    return None

def readText():
    stopWords()
    fi = open('holy-grail.txt', 'r')
    removeStopWords = ''.join(fi)
    for word in stopWords:
        removeStopWords = removeStopWords.replace(" " + word + " ", " ")
    transcript = []
    for line in fi:
        line = line.strip().lower().split(':')
        transcript.append(line)
    fi.close
    return transcript
</code>```

When I run this code I receive the error message:
Traceback (most recent call last):
  File "", line 1, in
    readText()
  File "C:\Users\Adam Sitzmann\Desktop\hw9\hw9.py", line 14, in readText
    for word in stopWords:
TypeError: 'function' object is not iterable

答:
Here: for word in stopWords you try to iterate over a function. You have a naming clash in your code. stopWords is both a function and a variable. Name your variable differently.

EDIT:
As you are new to python I'd like to suggest a few improvements:
1. You do not need to write return None. Functions without return will always give you None.
2. Having said that it's worth noticing that you can use return to pass the output of stopWords() function to process it further.
3. Naming conventions: it's common in python to use underscored_names instead of camelCase

Title: Trouble removing Stop Words python

Body:
I need to remove stop words from a movie transcript, the stop words and transcript are in separate text files.

def stopWords():
    fi = open('stoplist.txt', 'r')
    stopWords = []
    for line in fi:
        line = line.strip()
        stopWords.append(line)
    fi.close
    return None

def readText():
    stopWords()
    fi = open('holy-grail.txt', 'r')
    removeStopWords = ''.join(fi)
    for word in stopWords:
        removeStopWords = removeStopWords.replace(" " + word + " ", " ")
    transcript = []
    for line in fi:
        line = line.strip().lower().split(':')
        transcript.append(line)
    fi.close
    return transcript

When I run this code I receive the error message:
Traceback (most recent call last):
  File "", line 1, in
    readText()
  File "C:\Users\Adam Sitzmann\Desktop\hw9\hw9.py", line 14, in readText
    for word in stopWords:
TypeError: 'function' object is not iterable


来源: stackexchange

问:
Excel "Refresh All" with OpenXML
I have an excel 2007 file (OpenXML format) with a connection to an xml file. This connection generates an excel table and pivot charts.

I am trying to find a way with OpenXML SDK v2 to do the same as the "Refresh All" button in Excel. So that I could automatically update my file as soon as a new xml file is provided.

Thank you.

答:
You can't do this with Open XML.  Open XML allows you to work with the data stored in the file and change the data and formulas and definitions and such.  It doesn't actually do any calculations.

Excel automation technically would work, but it's absolutely not recommended for a server environment and is best avoided on the desktop if at all possible.

ContentLicense: CC BY-SA 3.0

Title: Excel "Refresh All" with OpenXML

ContentLicense: CC BY-SA 2.5


问:
Creating Step Builder with ByteBuddy
I'm trying to get ByteBuddy to implement a step builder, given an interface for that builder. I'm stuck on 2 places.

How to create a setter that returns the current instance for method chaining?

I started with:

```<code>.method(ElementMatchers.isSetter())
.intercept(FieldAccessor.ofBeanProperty());
</code>```

only I'd like to return the current builder instance so we can chain calls like:

```<code>final Object obj = ...builder().id(100).name("test").build();
</code>```

so instead I created an interceptor like this, which seems like a hack and I'd like to avoid reflection where possible:

```<code>@RuntimeType
public Object intercept(@RuntimeType Object arg, @This Object source, @Origin Method method)
{
  try
  {
    // Field name is same as method name.
    final Field field = source.getClass().getDeclaredField(method.getName());
    field.setAccessible(true);
    field.set(source, arg);
  }
  catch (Throwable ex)
  {
    throw new Error(ex);
  }

  // Return current builder instance.
  return source;
}
</code>```

Is there an easy way to access defined fields on a class I'm defining without reflection?

Currently I add fields to the builder class in a loop and my build method on the builder is intercepted like this:

```<code>private static final class InterBuilder
{
  private final Collection<String> fields;
  private final Constructor<?> constructor;

  InterBuilder(final Constructor<?> constructor, final Collection<String> fields)
  {
    this.constructor = constructor;
    this.fields = fields;
  }

  @RuntimeType
  public Object intercept(@This Object source, @Origin Method method)
  {
    try
    {
      final Object[] args = Arrays.stream(source.getClass().getDeclaredFields())
        .filter(f -> this.fields.contains(f.getName()))
        .map(f ->  { try {
          f.setAccessible(true);
          return f.get(source); }
          catch (Throwable ex) { throw new Error(ex); } })
        .toArray();

      // Invoke a constructor passing in the private field values from the builder...
      return this.constructor.newInstance(args);
    }
    catch (Throwable ex)
    {
      throw new Error(ex);
    }
  }
}
</code>```

I saw the @FieldValue annoation. I don't suppose there is something that will give me all fields without knowing their names up front?

The code is a proof of concept at this point. Are there better ways to do what I'm doing here?

Thank you!

答:
You can compose two implementations:

```<code>FieldAccessor.ofBeanProperty().setsArgumentAt(0).andThen(FixedValue.self());
</code>```

This will set the setters first (index 0) argument and then return this.

If you wanted to set a field from a MethodDelegation without reflection, have a look at FieldProxy.

Title: Creating Step Builder with ByteBuddy

Body:
I'm trying to get ByteBuddy to implement a step builder, given an interface for that builder. I'm stuck on 2 places.

How to create a setter that returns the current instance for method chaining?

I started with:

.method(ElementMatchers.isSetter())
.intercept(FieldAccessor.ofBeanProperty());

only I'd like to return the current builder instance so we can chain calls like:

final Object obj = ...builder().id(100).name("test").build();

so instead I created an interceptor like this, which seems like a hack and I'd like to avoid reflection where possible:

@RuntimeType
public Object intercept(@RuntimeType Object arg, @This Object source, @Origin Method method)
{
  try
  {
    // Field name is same as method name.
    final Field field = source.getClass().getDeclaredField(method.getName());
    field.setAccessible(true);
    field.set(source, arg);
  }
  catch (Throwable ex)
  {
    throw new Error(ex);
  }

  // Return current builder instance.
  return source;
}

Is there an easy way to access defined fields on a class I'm defining without reflection?

Currently I add fields to the builder class in a loop and my build method on the builder is intercepted like this:

private static final class InterBuilder
{
  private final Collection<String> fields;
  private final Constructor<?> constructor;

  InterBuilder(final Constructor<?> constructor, final Collection<String> fields)
  {
    this.constructor = constructor;
    this.fields = fields;
  }

  @RuntimeType
  public Object intercept(@This Object source, @Origin Method method)
  {
    try
    {
      final Object[] args = Arrays.stream(source.getClass().getDeclaredFields())
        .filter(f -> this.fields.contains(f.getName()))
        .map(f ->  { try {
          f.setAccessible(true);
          return f.get(source); }
          catch (Throwable ex) { throw new Error(ex); } })
        .toArray();

      // Invoke a constructor passing in the private field values from the builder...
      return this.constructor.newInstance(args);
    }
    catch (Throwable ex)
    {
      throw new Error(ex);
    }
  }
}

I saw the @FieldValue annoation. I don't suppose there is something that will give me all fields without knowing their names up front?

The code is a proof of concept at this point. Are there better ways to do what I'm doing here?

Thank you!

Body:
You can compose two implementations:

FieldAccessor.ofBeanProperty().setsArgumentAt(0).andThen(FixedValue.self());

This will set the setters first (index 0) argument and then return this.

If you wanted to set a field from a MethodDelegation without reflection, have a look at FieldProxy.


问:
can't install bootstrap on ruby on rails
I'm a beginer in Ruby on rails and i tried to install Bootstrap but always it failed

Here is how i proceded to install it .

1)

```<code>source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.6'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'bootstrap', '~> 4.0.0.beta2.1'
gem 'sprockets-rails', '~> 3.2', '>= 3.2.1'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

2)

```<code> @import "bootstrap";
</code>```

3) In the file application.js i paste this :

```<code>//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
</code>```

4) I got an error in the application.html.erb file so i changed "application" in the two lines to "application.scss" and "application.js" and then i installed Node.js

```<code>    <!DOCTYPE html>
<html>
  <head>
    <title>Bali</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application.scss', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application.js', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
</code>```

I did Bundle Install and reset the server. Then nothing happen to the homepage, the font didn't change...

Thank for your help

Ok now i have this, it seem that bootstrap is not displayed totaly

答:
Bootstrap has been installed successfully you however need to create an HTML page to leverage that new CSS you have.

Run this in your terminal to make your own custom page.

```<code>rails generate controller home index
</code>```

You can now update the app/views/home/index.html.erb file to contain whatever Bootstrap styled HTML you want.

The last step in order for you to view your page would be to modify the routes.rb file.
In that file, add the line root 'home#index' to see your new page when you visit your Rails app.

Body:
I'm a beginer in Ruby on rails and i tried to install Bootstrap but always it failed

Here is how i proceded to install it .

1)

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.6'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'bootstrap', '~> 4.0.0.beta2.1'
gem 'sprockets-rails', '~> 3.2', '>= 3.2.1'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

2)

 @import "bootstrap";

3) In the file application.js i paste this :

//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .

4) I got an error in the application.html.erb file so i changed "application" in the two lines to "application.scss" and "application.js" and then i installed Node.js

    <!DOCTYPE html>

    <title>Bali</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application.scss', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application.js', 'data-turbolinks-track': 'reload' %>

    <%= yield %>

I did Bundle Install and reset the server. Then nothing happen to the homepage, the font didn't change...

Thank for your help

Ok now i have this, it seem that bootstrap is not displayed totaly

Body:
Bootstrap has been installed successfully you however need to create an HTML page to leverage that new CSS you have.

Run this in your terminal to make your own custom page.

rails generate controller home index

You can now update the app/views/home/index.html.erb file to contain whatever Bootstrap styled HTML you want.

The last step in order for you to view your page would be to modify the routes.rb file.
In that file, add the line root 'home#index' to see your new page when you visit your Rails app.


问:
Flexbox with fixed header and footer and scrollable content
I am trying to make a flexbox design work. I am not an HTML/css expert. :(

I have a flexbox design with fixed header and footer and content that occupies the rest of the available real estate of the page.

When I put data in the content area which is longer than that available space the content is scrolling. But I want to achieve a different thing.

I would like to have several divs (below each other) in the content area and each div should be as high as the content area (even if the content is small) so I have a kind of paging inside the content area.

A couple of days I have tried a lot and read a lot but can't get it  working. How can I make a div inside the scrollable content area occupy the whole space (height) ?

答:
You can do something like this:

html, body {
  margin: 0;
  height: 100%; /* can also use viewport units (height: 100vh) */
}

#container {
  display: flex; /* displays flex-items (children) inline */
  flex-direction: column; /* stacks them vertically */
  height: 100%; /* needs to take the parents height, alternative: body {display: flex} */
}

main {
  flex: 1; /* takes the remaining height of the "container" div */
  overflow: auto; /* to scroll just the "main" div */
}

section {
  height: 100%; /* takes the visible area of the "main" div */
  overflow: auto; /* recommended */
  border-bottom: 1px solid;
  background: lightgreen;
}

header {background: #f88}
section:last-child {border: none}
footer {background: lightblue}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>top</header>
  <main>
    <section>1st</section>
    <section>2nd</section>
    <section>3rd<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
    </section>
    <section>4th</section>
    <section>5th</section>
  </main>
  <footer>bottom</footer>
</div></code>```

Body:
You can do something like this:

html, body {
  margin: 0;
  height: 100%; /* can also use viewport units (height: 100vh) */
}

#container {
  display: flex; /* displays flex-items (children) inline */
  flex-direction: column; /* stacks them vertically */
  height: 100%; /* needs to take the parents height, alternative: body {display: flex} */
}

main {
  flex: 1; /* takes the remaining height of the "container" div */
  overflow: auto; /* to scroll just the "main" div */
}

section {
  height: 100%; /* takes the visible area of the "main" div */
  overflow: auto; /* recommended */
  border-bottom: 1px solid;
  background: lightgreen;
}

header {background: #f88}
section:last-child {border: none}
footer {background: lightblue}

<div id="container">
  <header>top</header>
  <main>
    <section>1st</section>
    <section>2nd</section>
    <section>3rd<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
    </section>
    <section>4th</section>
    <section>5th</section>
  </main>
  <footer>bottom</footer>
</div>

ContentLicense: CC BY-SA 4.0


问:
Can a stored procedure on the master DB create a regular DB? SQL Server 2012 and later
I have all my scripts and procedures ready for this database project but I'd like to have a stored procedure that creates my database and all my tables. Potentially drop it (if it exists) in the proc as well but for now I'll just focus on creating it.

I assume it's something to do with the Master DB but can't figure it out.

Would it look something like this:

```<code>USE master

IF OBJECT_ID('dbo.myDB' ) IS NULL

CREATE PROCEDURE myNewDatabase
BEGIN
CREATE DATABASE myDB
END

ELSE
PRINT 'myDB Database already exists'
</code>```

Note: then I would have to do another stored proc to create all the tables right? Also a bit confused as the 'if object_id is null' usually checks for procedure names but this one is checking database name?

Can someone tell me whether my thinking is on the right track at lease?

Thank you

答:
I'm not saying it's a good idea to create databases this way (because it isn't), but if you really want to, here's how:</p>

```<code>CREATE PROC dbo.myNewDatabase
AS
SET NOCOUNT ON;

DECLARE @dbname VARCHAR(100) = 'myDB'
        ,@path VARCHAR(1000) = 'C:\Test\'
        ,@sql VARCHAR(1000);

IF DB_ID(@dbname) IS NULL
BEGIN
    SELECT
        @sql =
        'CREATE DATABASE ' + @dbname + ' ON (NAME = ' + @dbname
        + '_Data, FILENAME = ''' + @path + @dbname + '.mdf'')'
        + ' LOG ON (NAME = ' + @dbname + '_Log, FILENAME = ''' + @path + @dbname
        + '.ldf'')';
    EXEC(@sql);
END
ELSE
PRINT 'myDB Database already exists'

GO
</code>```

Body:
I have all my scripts and procedures ready for this database project but I'd like to have a stored procedure that creates my database and all my tables. Potentially drop it (if it exists) in the proc as well but for now I'll just focus on creating it.

I assume it's something to do with the Master DB but can't figure it out.

Would it look something like this:

USE master

IF OBJECT_ID('dbo.myDB' ) IS NULL

CREATE PROCEDURE myNewDatabase
BEGIN
CREATE DATABASE myDB
END

ELSE
PRINT 'myDB Database already exists'

Note: then I would have to do another stored proc to create all the tables right? Also a bit confused as the 'if object_id is null' usually checks for procedure names but this one is checking database name?

Can someone tell me whether my thinking is on the right track at lease?

Thank you

Body:
I'm not saying it's a good idea to create databases this way (because it isn't), but if you really want to, here's how:

CREATE PROC dbo.myNewDatabase
AS
SET NOCOUNT ON;

DECLARE @dbname VARCHAR(100) = 'myDB'
        ,@path VARCHAR(1000) = 'C:\Test\'
        ,@sql VARCHAR(1000);

IF DB_ID(@dbname) IS NULL
BEGIN
    SELECT
        @sql =
        'CREATE DATABASE ' + @dbname + ' ON (NAME = ' + @dbname
        + '_Data, FILENAME = ''' + @path + @dbname + '.mdf'')'
        + ' LOG ON (NAME = ' + @dbname + '_Log, FILENAME = ''' + @path + @dbname
        + '.ldf'')';
    EXEC(@sql);
END
ELSE
PRINT 'myDB Database already exists'

GO


问:
I am getting an error when installing youtube-dl via the pip command on macOS High Sierra
Long story short, I am creating a discord bot and I need youtube-dl to do so. When I went to install it on terminal, I used the command

```<code>pip install youtube-dl
</code>```

and I got this

```<code>Collecting youtube-dl
  Using cached youtube_dl-2017.12.2-py2.py3-none-any.whl
Installing collected packages: youtube-dl
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/youtube_dl'
</code>```

I don't really know what to make of this or weather or not it is a bug with the pip command itself in High Sierra. Any help would be appreciated. Thanks!

答:
I would recommend that you not change the system Python, but instead use homebrew to install Python, then install youtube-dl:

```<code>brew install python
brew install youtube-dl
</code>```

Body:
Long story short, I am creating a discord bot and I need youtube-dl to do so. When I went to install it on terminal, I used the command

pip install youtube-dl

and I got this

Collecting youtube-dl
  Using cached youtube_dl-2017.12.2-py2.py3-none-any.whl
Installing collected packages: youtube-dl
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/youtube_dl'

I don't really know what to make of this or weather or not it is a bug with the pip command itself in High Sierra. Any help would be appreciated. Thanks!

Body:
I would recommend that you not change the system Python, but instead use homebrew to install Python, then install youtube-dl:

brew install python
brew install youtube-dl


问:
Django OneToOneField Unique fails when extending User model
I'm trying to extends Django User model by means of an Actor model but I'm getting some problems.

There is my code:

```<code>class Actor(models.Model):
    usuario = models.OneToOneField('auth.User', unique = True, null = True)

    def __str__(self):
        return self.usuario.get_full_name() + ' (' + self.usuario.get_username() + ')'
</code>```

The problem is that one-to-one relationship is not unique so I can create two differents actors and relate them with the same user.

Use case idea: I create a User (User model by Django) then I create an actor and relate him with the user I created before. If I create a second actor, there would not must be posible related him with the same user.

答: I would suggest you use ForeignKey with unique=True.

Body:
I'm trying to extends Django User model by means of an Actor model but I'm getting some problems.

There is my code:

class Actor(models.Model):
    usuario = models.OneToOneField('auth.User', unique = True, null = True)

    def __str__(self):
        return self.usuario.get_full_name() + ' (' + self.usuario.get_username() + ')'

The problem is that one-to-one relationship is not unique so I can create two differents actors and relate them with the same user.

Use case idea: I create a User (User model by Django) then I create an actor and relate him with the user I created before. If I create a second actor, there would not must be posible related him with the same user.


问:
Event handle on customized ListView
```<code>public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}
</code>```

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.

答:
It sounds like you want to handle the onCheckedChanged event or onClick event in ActivityForShow.

If so, have ActivityForShow create a OnCheckedChangeListener instance and OnClickListener instance (e.g. as local anonymous inner classes) and have ActivityForShow give them to SingleRowAdapter (e.g. as constructor params) to attach to the checkbox and button widgets as their callbacks.

Alternatively, define your own custom handler interface(s) to be called when the button is clicked or the checkbox is checked. Have ActivityForShow to instantiate an instance of the custom interface(s) with code to process the event.  Have ActivityForShow give them to SingleRowAdapter.   Finally, have SingleRowAdapter create event handlers to attach to the checkboxes and buttons - these event handlers simply call your own custom handlers.

Title: Event handle on customized ListView

Body:
public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.


问:
Is it possible for ZipEntry.getCrc() to be incorrect without an exception occurring?
I am using Java's ZIP archive APIs in the java.util.zip package. Some code that I am looking at in Apache NetBeans' source repository calculates the CRC32 of every entry in a ZIP archive being read using the following routine:

```<code>private long computeCRC32(InputStream is) throws IOException {
    byte[] buf = new byte[4096];
    CRC32 crc32 = new CRC32();
    int read;
    while ((read = is.read(buf)) != -1) {
        crc32.update(buf, 0, read);
    }
    return crc32.getValue();
}
</code>```

This routine is called once for each ZIP entry:

```<code>File f = new File("a.zip");
try (ZipFile zipFile = new ZipFile(f)) {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        long crc;
        try (InputStream is = zipFile.getInputStream(entry)) {
            crc = computeCRC32(is);
        }
        // do something with `crc'
    }
}
</code>```

I am wondering if it would be better to simply call ZipEntry.getCrc() (if it returns something other than -1) rather than call computeCRC32().

One concern I have is that if the ZIP archive is malformed, getCrc() might return an incorrect value.

Is it possible for ZipEntry.getCrc() to return a value other than -1, and other than what computeCRC32() would calculate, for some ZIP entry, and to fully read through the malformed ZIP archive without any exception occurring?

UPDATE I used a hex editor to alter the CRC32 stored in a local file header of a test ZIP archive. Running my test program, I did not observe an exception, but getCrc() returned the correct CRC32 rather than the altered value.

For reference, here is my test program:

```<code>import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipCrcTest {

    public static void main(String[] args) throws IOException {
        File f = new File("a.zip");
        try (ZipFile zipFile = new ZipFile(f)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                long crc;
                try (InputStream is = zipFile.getInputStream(entry)) {
                    crc = computeCRC32(is);
                }
                System.out.printf("%s %x (computed %x)\n", entry.getName(), entry.getCrc(), crc);
                if (entry.getCrc() != -1L && entry.getCrc() != crc) {
                    System.err.printf("Crc different for %s!\n", entry.getName());
                }
            }
        }
    }

    private static long computeCRC32(InputStream is) throws IOException {
        byte[] buf = new byte[4096];
        CRC32 crc32 = new CRC32();
        int read;
        while ((read = is.read(buf)) != -1) {
            crc32.update(buf, 0, read);
        }
        return crc32.getValue();
    }
}
</code>```

答:
It turns out that the answer is "Yes".

When I similarly altered the copy of the zip entry's CRC32 in the central directory portion of the ZIP archive, getCrc() returned the altered value and no exception was thrown.

Body:
I am using Java's ZIP archive APIs in the java.util.zip package. Some code that I am looking at in Apache NetBeans' source repository calculates the CRC32 of every entry in a ZIP archive being read using the following routine:

private long computeCRC32(InputStream is) throws IOException {
    byte[] buf = new byte[4096];
    CRC32 crc32 = new CRC32();
    int read;
    while ((read = is.read(buf)) != -1) {
        crc32.update(buf, 0, read);
    }
    return crc32.getValue();
}

This routine is called once for each ZIP entry:

File f = new File("a.zip");
try (ZipFile zipFile = new ZipFile(f)) {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        long crc;
        try (InputStream is = zipFile.getInputStream(entry)) {
            crc = computeCRC32(is);
        }
        // do something with `crc'
    }
}

I am wondering if it would be better to simply call ZipEntry.getCrc() (if it returns something other than -1) rather than call computeCRC32().

One concern I have is that if the ZIP archive is malformed, getCrc() might return an incorrect value.

Is it possible for ZipEntry.getCrc() to return a value other than -1, and other than what computeCRC32() would calculate, for some ZIP entry, and to fully read through the malformed ZIP archive without any exception occurring?

UPDATE I used a hex editor to alter the CRC32 stored in a local file header of a test ZIP archive. Running my test program, I did not observe an exception, but getCrc() returned the correct CRC32 rather than the altered value.

For reference, here is my test program:

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipCrcTest {

    public static void main(String[] args) throws IOException {
        File f = new File("a.zip");
        try (ZipFile zipFile = new ZipFile(f)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                long crc;
                try (InputStream is = zipFile.getInputStream(entry)) {
                    crc = computeCRC32(is);
                }
                System.out.printf("%s %x (computed %x)\n", entry.getName(), entry.getCrc(), crc);
                if (entry.getCrc() != -1L && entry.getCrc() != crc) {
                    System.err.printf("Crc different for %s!\n", entry.getName());
                }
            }
        }
    }

    private static long computeCRC32(InputStream is) throws IOException {
        byte[] buf = new byte[4096];
        CRC32 crc32 = new CRC32();
        int read;
        while ((read = is.read(buf)) != -1) {
            crc32.update(buf, 0, read);
        }
        return crc32.getValue();
    }
}


问:
Extracting the RGB value from a string
How would I extract the RBG value from the following string?:

let string = "

I would like to get extract "rgb(230, 0, 0)" from the background-color value, so I can convert it to a hex string and update some UI.

```<code>let range = string.range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = string.substring(from: startPoint)
//generating error claiming 'cannot convert value of type 'int' to expected argument type 'string.index'.
//paused here to ask S.O b/c I do not think substrings is the best way to do this, maybe there is a library that extracts values from html elements, or regex?
</code>```

答:
```<code>let range = (string as NSString).range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = (string as NSString).substring(from: startPoint)
let deliminator = ";"
let components = subString.components(separatedBy: deliminator)
let rgb = components[0]

print(rgb) -> "rgb(230, 0, 0)"
</code>```

Title: Extracting the RGB value from a string

Body:
How would I extract the RBG value from the following string?:

let string = "

I would like to get extract "rgb(230, 0, 0)" from the background-color value, so I can convert it to a hex string and update some UI.

let range = string.range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = string.substring(from: startPoint)
//generating error claiming 'cannot convert value of type 'int' to expected argument type 'string.index'.
//paused here to ask S.O b/c I do not think substrings is the best way to do this, maybe there is a library that extracts values from html elements, or regex?


问:
How to use Matches() and Pattern correctley
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

```<code>boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);
</code>```

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

答:
To understand the uses of Matcher you should see This link

In this example the Matcher and Pattern objects aren't doing anything because you are using a String method that works with regexp. If you wanted to use the Matcher your if would look something like this

```<code>if(matcher.matches())
    ans=false;
</code>```

Body:
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

Body:
To understand the uses of Matcher you should see This link

In this example the Matcher and Pattern objects aren't doing anything because you are using a String method that works with regexp. If you wanted to use the Matcher your if would look something like this

if(matcher.matches())
    ans=false;


问:
Eclipse keyboard command to add import statement
I am a C# developer who is doing some Android development in Eclipse. One of my favorite keyboard shortcuts in Visual Studio is CTRL + . which brings up the SmartTag menu. This is incredibly useful for adding using statements on the fly.

As an example if I don't have an import statement for System.Xml.Linq but create a variable of type XDocument I can quickly add the appropriate using with the keyboard command.

Is there a similar keyboard command available in Eclipse?

答: You can use Ctrl + Shift + O to "O"rganize Imports (like Crembo mentions).  Another neat trick is to go to Windows > Preferences, search for "Save Actions", and check "Organize Imports".  Now whenever you save (Ctrl + S), Eclipse will automatically run the "organize imports" feature.  I find this quicker, since it's quicker for me to hit Ctrl + S than Ctrl + Shift + O (one-hand shortcut versus two-hand shortcut).


问:
Docker compose v3 specify network to be ingress?
I have docker-compose file for my docker swarm stack.I want my stack services to be deployed on specific network and that network i want to be ingress network so that i can use DNSRR of docker.

```<code>version: "3"
services:
 a:
  image: xyz/a:dev
  ports:
   - "80:80"
   - "443:443"
  networks:
   -my_network
b:
  image: xyz/b:dev
  ports:
  - "5000:5000"
  networks:
   -my_network

networks:
  my_network:
    driver:overlay
    ipam:
     driver: default
     config:
       -subnet: 10.0.1.0/24
</code>```

here, where can i specify that this network should be ingress network? plus how can i specify ip-range same as specified here in cli : here

答:
The ingress network is only for manager/worker nodes.

The routing mesh routes all incoming requests to published ports on available nodes to an active container.
  https://docs.docker.com/engine/swarm/ingress/

What you want is an addition overlay network. All services which are assigned to the same overlay network which is not ingress, can talk to each other over the name you've given them.

E.g.

```<code>docker service create --name A --network dev ...
docker service create --name B --network dev ...
</code>```

Service A can simply do ping B.

Body:
I have docker-compose file for my docker swarm stack.I want my stack services to be deployed on specific network and that network i want to be ingress network so that i can use DNSRR of docker.

version: "3"
services:
 a:
  image: xyz/a:dev
  ports:
   - "80:80"
   - "443:443"
  networks:
   -my_network
b:
  image: xyz/b:dev
  ports:
  - "5000:5000"
  networks:
   -my_network

networks:
  my_network:
    driver:overlay
    ipam:
     driver: default
     config:
       -subnet: 10.0.1.0/24

here, where can i specify that this network should be ingress network? plus how can i specify ip-range same as specified here in cli : here

Body:
The ingress network is only for manager/worker nodes.

The routing mesh routes all incoming requests to published ports on available nodes to an active container.
  https://docs.docker.com/engine/swarm/ingress/

What you want is an addition overlay network. All services which are assigned to the same overlay network which is not ingress, can talk to each other over the name you've given them.

E.g.

docker service create --name A --network dev ...
docker service create --name B --network dev ...

Service A can simply do ping B.


问:
My localStorage is not saving anything
So this is like a ToDo list site, but when I refresh nothing is saved!

Here are the HTML and Javascript:

localStorage.setItem('myInput'); {
  var save = localStorage.getItem("myInput");
}
localStorage.setItem('myInput2'); {
  var save = localStorage.getItem("myInput2");
}
localStorage.setItem('myInput3'); {
  var save = localStorage.getItem("myInput3");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal-content">
  <span class="close">×</span>
  <div id="myDIV" class="header">
    <h2>Add a task</h2>
    <input type="text" id="myInput" placeholder="Write a task...">
    <input type="text" id="myInput2" placeholder="Estimated time...">
    <input type="text" id="myInput3" placeholder="Week...">
    <span onclick="newElement()" class="addBtn" value="save" onClick="save()">Add</span>
  </div>
</div>
</div>

<ul id="tehtavat">
</ul></code>```

I also get this error in the console:

index.html Uncaught TypeError: Failed to execute 'setItem' on
  'Storage': 2 arguments required, but only 1 present.

答:
When you want to save value to localstorage you need to pass a value as second attribute. First one is the key.

```<code>localStorage.setItem('myInput', myValue);
</code>```

Think of localstorage as list of key / value pairs.

Besides, you want to write data to localstorage manually each time your data changes, so let's say on keyup event:

```<code>document.getElementById('myInput').addEventListener('keyup', function(event){
    localStorage.setItem('inputValue', event.target.value);
})
</code>```

And i can imagine that on load, you want to bring this value back;

```<code>var inputValue = localStorage.getItem('inputValue');

if(inputValue) {  //just check if there's value saved
    document.getElementById('myInput').value = inputValue;
}
</code>```

Please take into consideration that i typed code out of my head without testing it, so there are some typos possible. You can as well maybe try to solve typos on your own.

Title: My localStorage is not saving anything

Body:
So this is like a ToDo list site, but when I refresh nothing is saved!

Here are the HTML and Javascript:

localStorage.setItem('myInput'); {
  var save = localStorage.getItem("myInput");
}
localStorage.setItem('myInput2'); {
  var save = localStorage.getItem("myInput2");
}
localStorage.setItem('myInput3'); {
  var save = localStorage.getItem("myInput3");
}

  ×

Add a task

    <input type="text" id="myInput" placeholder="Write a task...">
    <input type="text" id="myInput2" placeholder="Estimated time...">
    <input type="text" id="myInput3" placeholder="Week...">
    Add

I also get this error in the console:

index.html Uncaught TypeError: Failed to execute 'setItem' on
  'Storage': 2 arguments required, but only 1 present.

Body:
When you want to save value to localstorage you need to pass a value as second attribute. First one is the key.

localStorage.setItem('myInput', myValue);

Think of localstorage as list of key / value pairs.

Besides, you want to write data to localstorage manually each time your data changes, so let's say on keyup event:

document.getElementById('myInput').addEventListener('keyup', function(event){
    localStorage.setItem('inputValue', event.target.value);
})

And i can imagine that on load, you want to bring this value back;

var inputValue = localStorage.getItem('inputValue');

if(inputValue) {  //just check if there's value saved
    document.getElementById('myInput').value = inputValue;
}

Please take into consideration that i typed code out of my head without testing it, so there are some typos possible. You can as well maybe try to solve typos on your own.


问:
pycharm packages not displayed in the project interpreter window
I am using pycharm 5.0.4 community edition.
I wanted to install package fuzzywuzzy.
But when i go to project interpreter window and try to install package, it shows me no available packages.
Can it be issue because I am using my work desktop.

Thanksenter image description here

答:
I had a similar problem. I was using the Intel python distribution, and installing packages required write permissions to the folder that intelpython was installed in, which in my case was /opt/intel/intelpython2.

Try adding write permissions to the folder using the following command:

```<code>sudo chown -R <username> </path/to/folder>
</code>```

Then try adding missing packages and/or repositories as seen in this page - https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html.

Body:
I had a similar problem. I was using the Intel python distribution, and installing packages required write permissions to the folder that intelpython was installed in, which in my case was /opt/intel/intelpython2.

Try adding write permissions to the folder using the following command:

sudo chown -R <username> </path/to/folder>

Then try adding missing packages and/or repositories as seen in this page - https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html.


问:
object name dynamic create
i have a single question,

i have this JS.

```<code>Scene.platform = new MenuItem();
Scene.platform.init(...code...);
</code>```

this works fine, but i have N platforms, how i creat dynamic?

i tryed :

```<code>for(i=0....){

Scene.platform+i = new MenuItem();
or
Scene.platform.i = new MenuItem();

}
</code>```

i need the result like that:

```<code>Scene.platform1 = new MenuItem();
Scene.platform2 = new MenuItem();
Scene.platform3 = new MenuItem();
</code>```

its possible? thanks in advance.

答:
For dynamic names you can use [] syntax.

```<code>Scene['platform' + i] = new MenuItem();
</code>```

Example

const Scene = {};

for(let i = 0; i < 3; i++) {
  Scene['platform' + i] = {};
}

console.log(Scene);```
</div>
</div>
</p>

<p>But think about to use array instead of object and push your items into that array. Then you can use indexes to get , for example, first item via [0], which in your object style can be named like <code>platform0</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Scene = { platforms: [] };

for(let i = 0; i < 3; i++) {
  Scene.platforms.push({});
}

console.log(Scene.platforms[0]);</code>```

Title: object name dynamic create

Body:
i have a single question,

i have this JS.

Scene.platform = new MenuItem();
Scene.platform.init(...code...);

this works fine, but i have N platforms, how i creat dynamic?

i tryed :

for(i=0....){

Scene.platform+i = new MenuItem();
or
Scene.platform.i = new MenuItem();

}

i need the result like that:

Scene.platform1 = new MenuItem();
Scene.platform2 = new MenuItem();
Scene.platform3 = new MenuItem();

its possible? thanks in advance.

Body:
For dynamic names you can use [] syntax.

Scene['platform' + i] = new MenuItem();

Example

const Scene = {};

for(let i = 0; i < 3; i++) {
  Scene['platform' + i] = {};
}

console.log(Scene);

But think about to use array instead of object and push your items into that array. Then you can use indexes to get , for example, first item via [0], which in your object style can be named like platform0.

const Scene = { platforms: [] };

for(let i = 0; i < 3; i++) {
  Scene.platforms.push({});
}

console.log(Scene.platforms[0]);


问:
Tensorflow Estimator Predict for Deep Wide Model
Can someone give a clear example on how to call prediction on tf.estimator?

Two things are unclear to me

When the input file doesn't have the label column, how to adjust the input_fn

How to export the predicted results

I am working on deep_wide model.

答:
I will answer myself and hope this can help someone with similar questions

For question 1, yes we need to construct a new input function and most likely it will have different number of columns as your input csv, since we are removing the label column

```<code>def parse_csv(value):
    print('Parsing', data_file)
    columns = tf.decode_csv(value, record_defaults=_PREDICT_COLUMNS_DEFAULTS)
    features = dict(zip(_PREDICT_COLUMNS, columns))

    return features

def predict_input_fn(data_file):
    assert tf.gfile.Exists(data_file), ('%s not found. Please make sure the path is correct.' % data_file)

    dataset = tf.data.TextLineDataset(data_file)
    dataset = dataset.map(parse_csv, num_parallel_calls=5)
    dataset = dataset.batch(1) # this is very important to keep the rank right
    iterator = dataset.make_one_shot_iterator()
    features = iterator.get_next()
    return features
</code>```

Then for question 2, you use the new input_fn to predict the results

```<code>def predict(model):
    start_from_id = 892
    test_csv = []

    results = model.predict(
        input_fn=lambda: predict_input_fn(data_file='test.csv')
    )

    # for result in results:
    #     print 'result: {}'.format(result)
</code>```

Body:
I will answer myself and hope this can help someone with similar questions

For question 1, yes we need to construct a new input function and most likely it will have different number of columns as your input csv, since we are removing the label column

def parse_csv(value):
    print('Parsing', data_file)
    columns = tf.decode_csv(value, record_defaults=_PREDICT_COLUMNS_DEFAULTS)
    features = dict(zip(_PREDICT_COLUMNS, columns))

    return features

def predict_input_fn(data_file):
    assert tf.gfile.Exists(data_file), ('%s not found. Please make sure the path is correct.' % data_file)

    dataset = tf.data.TextLineDataset(data_file)
    dataset = dataset.map(parse_csv, num_parallel_calls=5)
    dataset = dataset.batch(1) # this is very important to keep the rank right
    iterator = dataset.make_one_shot_iterator()
    features = iterator.get_next()
    return features

Then for question 2, you use the new input_fn to predict the results

def predict(model):
    start_from_id = 892
    test_csv = []

    results = model.predict(
        input_fn=lambda: predict_input_fn(data_file='test.csv')
    )

    # for result in results:
    #     print 'result: {}'.format(result)


问:
Symfony Doctrine can't find fixtures to load
I starting with Symfony (3.4) and I have problem with load fixture.

When I execute php bin/console doctrine:fixtures:load then I get message:

```
In LoadDataFixturesDoctrineCommand.php line 95:
  Could not find any fixture services to load.
```

There is my code:

~/src/AppBundle/DataFixtures/ORM/LoadUserData.php

```<code>namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadUserData implements FixtureInterface, ContainerAwareInterface {

    private $container;

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $user = new User();
        $user->setLogin('admin');
        $user->setEmail('admin@admin.admin');
        $encoder = $this->container->get('security.password_encoder');
        $password = $encoder->encodePassword($user, '123qwe');
        $user->setPassword($password);

        $manager->persist();
        $manager->flush();
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}
</code>```

~/app/config/services.yml

```<code>    parameters:

    services:
        _defaults:
            autowire: true
            autoconfigure: true
            public: false

        AppBundle\:
            resource: '../../src/AppBundle/*'
            exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

        AppBundle\Controller\:
            resource: '../../src/AppBundle/Controller'
            public: true
            tags: ['controller.service_arguments']
</code>```

Thanks.

答:
Depending on what version of fixtures you use you should extend/implement different classes.
If the version is >= 3.0 then

```<code>extend Fixture (use Doctrine\Bundle\FixturesBundle\Fixture;)
</code>```

If < 3.0

```<code>implements FixtureInterface, ContainerAwareInterface
</code>```

Body:
I starting with Symfony (3.4) and I have problem with load fixture.

When I execute php bin/console doctrine:fixtures:load then I get message:

In LoadDataFixturesDoctrineCommand.php line 95:
  Could not find any fixture services to load.

There is my code:

~/src/AppBundle/DataFixtures/ORM/LoadUserData.php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadUserData implements FixtureInterface, ContainerAwareInterface {

    private $container;

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $user = new User();
        $user->setLogin('admin');
        $user->setEmail('admin@admin.admin');
        $encoder = $this->container->get('security.password_encoder');
        $password = $encoder->encodePassword($user, '123qwe');
        $user->setPassword($password);

        $manager->persist();
        $manager->flush();
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}

~/app/config/services.yml

    parameters:

    services:
        _defaults:
            autowire: true
            autoconfigure: true
            public: false

        AppBundle\:
            resource: '../../src/AppBundle/*'
            exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

        AppBundle\Controller\:
            resource: '../../src/AppBundle/Controller'
            public: true
            tags: ['controller.service_arguments']

Thanks.

Body:
Depending on what version of fixtures you use you should extend/implement different classes.
If the version is >= 3.0 then

extend Fixture (use Doctrine\Bundle\FixturesBundle\Fixture;)

If < 3.0

implements FixtureInterface, ContainerAwareInterface


问:
R - Change return values of existing function
I am using the approxfun() function to get linear interpolation. I want to write a function which takes the results of approxfun() then shifts and scales it by an amount that I specify. I need to be able to call this new function just like I would call any other function.

Simplified version of my attempt:

```<code>set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}
</code>```

I expect the results to be the same as

```<code>2 * fhat(1) + 3
</code>```

but instead when I run my function

```<code>new_function(fhat, a = 2, b = 3)
</code>```

I get an error message:

*Error in (function(fhat, a, b) a * fhat() + b)() :
  argument "a" is missing, with no default*

答:
You have four problems:

new_fhat isn't passed the values of a and b from the new_function call, and can't see them because you are creating new ones in your function definition. This is actually a bit of a red herring because...

The function you return should only have a single argument - the point at which you want to evaluate it.

You are attempting to evaluate new_fhat immediately.

You are trying to call fhat without an argument.

The solution is:

```<code>new_function = function(fhat, a, b){

  new_fhat <- function(v) a * fhat(v) + b

  return(new_fhat)

}
</code>```

Results:

```<code>fhat(1)
[1] 5.31933
new_function(fhat,a=2,b=3)(1)
[1] 13.63866
2 * fhat(1) + 3
[1] 13.63866
</code>```

Body:
I am using the approxfun() function to get linear interpolation. I want to write a function which takes the results of approxfun() then shifts and scales it by an amount that I specify. I need to be able to call this new function just like I would call any other function.

Simplified version of my attempt:

set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}

I expect the results to be the same as

2 * fhat(1) + 3

but instead when I run my function

new_function(fhat, a = 2, b = 3)

I get an error message:

*Error in (function(fhat, a, b) a * fhat() + b)() :
  argument "a" is missing, with no default*

Body:
You have four problems:

new_fhat isn't passed the values of a and b from the new_function call, and can't see them because you are creating new ones in your function definition. This is actually a bit of a red herring because...

The function you return should only have a single argument - the point at which you want to evaluate it.

You are attempting to evaluate new_fhat immediately.

You are trying to call fhat without an argument.

The solution is:

new_function = function(fhat, a, b){

  new_fhat <- function(v) a * fhat(v) + b

  return(new_fhat)

}

Results:

fhat(1)
[1] 5.31933
new_function(fhat,a=2,b=3)(1)
[1] 13.63866
2 * fhat(1) + 3
[1] 13.63866


问:
Get Warning Message Using rbokeh in R Notebook
Running Ubuntu 17.10, and running R Notebook on RStudio through Anaconda.

When I try to run the simple example from the rbokeh website in a R Notebook :

```<code>p <- figure() %>%
  ly_points(Sepal.Length, Sepal.Width, data = iris,
            color = Species, glyph = Species,
            hover = list(Sepal.Length, Sepal.Width))
</code>```

I get the following warning message:

```<code>In structure(x, class = unique(c("AsIs", oldClass(x)))) :
Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.
</code>```

It seems as if this warning message has been documented here, but I'm still getting this warning. Does anyone have any recommendations on what to do?

答:
https://github.com/bokeh/rbokeh/issues/216

If you follow this link and use "devtools" to install from hafen/rbokeh, you no longer receive the warning message.

Body:
Running Ubuntu 17.10, and running R Notebook on RStudio through Anaconda.

When I try to run the simple example from the rbokeh website in a R Notebook :

p <- figure() %>%
  ly_points(Sepal.Length, Sepal.Width, data = iris,
            color = Species, glyph = Species,
            hover = list(Sepal.Length, Sepal.Width))

I get the following warning message:

In structure(x, class = unique(c("AsIs", oldClass(x)))) :
Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
  Consider 'structure(list(), *)' instead.

It seems as if this warning message has been documented here, but I'm still getting this warning. Does anyone have any recommendations on what to do?


问:
How to call `.update()` method in Sails.js?`
I'm using sails.js v1 and sails-postgresql.

I need execute something like this:

```<code>UPDATE users SET balance -= 'amount' WHERE id = 'id';
</code>```

I need to use .usingConnection(), so I can't use .query().
How to make it?

Also what is best practices for avoiding 'race condition' in sails?

Thanks.

答:
I was looking for:

```<code>sails.sendNativeQuery
</code>```

https://github.com/balderdashy/sails-docs/blob/1.0/reference/waterline/datastores/sendNativeQuery.md

Body:
I'm using sails.js v1 and sails-postgresql.

I need execute something like this:

UPDATE users SET balance -= 'amount' WHERE id = 'id';

I need to use .usingConnection(), so I can't use .query().
How to make it?

Also what is best practices for avoiding 'race condition' in sails?

Thanks.

Body:
I was looking for:

sails.sendNativeQuery

https://github.com/balderdashy/sails-docs/blob/1.0/reference/waterline/datastores/sendNativeQuery.md


问:
python requests @ params
I try to using request.get with '@' in params, but in output I have '%40' How I can decode this dict?

Using Python3

```<code>import requests

payload = {'OPERATION-NAME': 'findItemsByProduct','productId.@type':'ReferenceID'}

req = requests.post(url, params=payload)

print(req.url)
</code>```

The output is - 'url?productId.%40type=ReferenceID'

答:
Use "data" argument instead of params. You should also specify the header, in this case json and then convert the payload dict to json using json.dumps().</p>

```<code>import requests
import json

payload = {'productId.@type':'ReferenceID'}

req = requests.post(url, headers={'Content-Type': 'application/JSON'}, data=json.dumps(payload))

print(req.url)
</code>```

Title: python requests @ params

Body:
I try to using request.get with '@' in params, but in output I have '%40' How I can decode this dict?

Using Python3

import requests

payload = {'OPERATION-NAME': 'findItemsByProduct','productId.@type':'ReferenceID'}

req = requests.post(url, params=payload)

print(req.url)

The output is - 'url?productId.%40type=ReferenceID'

Body:
Use "data" argument instead of params. You should also specify the header, in this case json and then convert the payload dict to json using json.dumps().

import requests
import json

payload = {'productId.@type':'ReferenceID'}

req = requests.post(url, headers={'Content-Type': 'application/JSON'}, data=json.dumps(payload))

print(req.url)


问:
nagios check_disk returns "not accessible: No such file or directory" for mounted paths
My Nagios works with check_disk on "/" but failed for mounted paths.
My command definition looks like this:

```<code>define command{
    command_name    check_local_disk
    command_line    $USER1$/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$
    }
</code>```

And in client.cfg it looks like this:

```<code>define service{
    use                             local-service
    host_name                       10.62.81.166
    service_description             /storage/disk1
    check_command                   check_local_disk!20%!10%!/storage/disk1
    }
</code>```

The /etc/fstab looks like this:

```<code>/dev/sdb /storage/disk1 ext4 rw 0 0
</code>```

I tried pass value like /dev/sdb or /storage/disk1 but error all same - not accessible: No such file or directory

I tried running command in nagios user in remote client and it works fine.

Any possible clues?

Thanks.

答: For the check_disk command to work, the target must both 'exist' AND be 'accessible' by the user running check_disk (perhaps user 'nagios' in your case?).  There is likely a security setting on the mount point that is preventing the Nagios user from running the 'stat' command against that specific mount point.  If this is the case, the easiest solution would be to add the Nagios user to a shared group with the owner of the partition.  The Nagios user would require 'read' access.</p>

Body:
My Nagios works with check_disk on "/" but failed for mounted paths.
My command definition looks like this:

define command{
    command_name    check_local_disk
    command_line    $USER1$/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$
    }

And in client.cfg it looks like this:

define service{
    use                             local-service
    host_name                       10.62.81.166
    service_description             /storage/disk1
    check_command                   check_local_disk!20%!10%!/storage/disk1
    }

The /etc/fstab looks like this:

/dev/sdb /storage/disk1 ext4 rw 0 0

I tried pass value like /dev/sdb or /storage/disk1 but error all same - not accessible: No such file or directory

I tried running command in nagios user in remote client and it works fine.

Any possible clues?

Thanks.


答:
Use an array:

```<code>Scene.platforms = [];
for (var i = 0; i < count; ++i) {
    Scene.platforms.push(new MenuItem());
}
</code>```

Later, to access them, either loop through the array (see my other answer here) or index into it. E.g., if you want the first one:

```<code>Scene.platforms[0].doSomething();
</code>```

Title: object name dynamic create

Body:
Use an array:

Scene.platforms = [];
for (var i = 0; i < count; ++i) {
    Scene.platforms.push(new MenuItem());
}

Later, to access them, either loop through the array (see my other answer here) or index into it. E.g., if you want the first one:

Scene.platforms[0].doSomething();


问:
Keep getting foreign key constraint failed message in My SQL
I tried to insert data into the table Bookratings, but I keep getting this error message. Is this because when I try to insert, it creates duplicates in the Bookratings table, which is not allowed by the PRIMARY key constraint?

MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails

My actual code:

drop database if exists amazon2;

create database if not exists amazon2;

use amazon2;

```<code>create table books(
  ISBN varchar(13),
  Title varchar(255),
  Author varchar(255),
  Year int(10),
  Puplisher varchar(255),
  ImageURL varchar(255),
  Genre varchar(12),
  unitprice decimal(6,2),
  primary key (ISBN)
);

  create table users(
    UserID int(11),
    Country varchar(250),
    Age int(11),
    primary key (UserID)
  );

  create table bookratings(
    UserID int(11) not null,
    ISBN varchar(13) not null,
    Rating int(11),
    primary key (UserID, ISBN),
    foreign key (ISBN) references books (ISBN) on delete cascade on update cascade,
    foreign key (UserID) references users (UserID) on delete cascade on update cascade
   );

   create table orders(
     OrderID int(11),
     UserID int(11) not null,
     Year int(10),
     totalpay decimal(6,2),
     primary key (OrderID),
     foreign key (UserID) references users (UserID)
   );

   create table trans(
     OrderID int(11) not null,
     ISBN varchar(13) not null,
     Quantity int(11),
     primary key (OrderID, ISBN),
     foreign key (OrderID) references orders (OrderID),
     foreign key (ISBN) references books (ISBN)
   );
</code>```

I have to clarify something: Given by the task, I am not allowed to add any other attributes or delete the existing attributes.

答:
Foreign key constraint violation means the table you're trying to update contains references to some other table, and you're somehow breaking that reference.

If I've got a table Movies

```<code>+----------+---------------+
| Movie_ID |  Movie_Name   |
+----------+---------------+
|        1 | Jaws          |
|        2 | Star-Wars     |
|        3 | Jurassic Park |
+----------+---------------+
</code>```

And a table User_Reviews

```<code>+---------+----------+-------+
| User_ID | Movie_ID | Score |
+---------+----------+-------+
|       1 |        1 | 2.5   |
|       2 |        1 | 5     |
|       3 |        2 | 4     |
|       4 |        2 | 3     |
|       5 |        2 | 4.5   |
|       6 |        3 | 5     |
+---------+----------+-------+
</code>```

In the User_Reviews table, Movie_ID is a foreign key.

I can't have a review with Movie_ID = 10, because that movie doesn't exist in the Movies table. If I did try to do that, I'd get a foreign key constraint error.

Body:
I tried to insert data into the table Bookratings, but I keep getting this error message. Is this because when I try to insert, it creates duplicates in the Bookratings table, which is not allowed by the PRIMARY key constraint?

MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails

My actual code:

drop database if exists amazon2;

create database if not exists amazon2;

use amazon2;

create table books(
  ISBN varchar(13),
  Title varchar(255),
  Author varchar(255),
  Year int(10),
  Puplisher varchar(255),
  ImageURL varchar(255),
  Genre varchar(12),
  unitprice decimal(6,2),
  primary key (ISBN)
);

  create table users(
    UserID int(11),
    Country varchar(250),
    Age int(11),
    primary key (UserID)
  );

  create table bookratings(
    UserID int(11) not null,
    ISBN varchar(13) not null,
    Rating int(11),
    primary key (UserID, ISBN),
    foreign key (ISBN) references books (ISBN) on delete cascade on update cascade,
    foreign key (UserID) references users (UserID) on delete cascade on update cascade
   );

   create table orders(
     OrderID int(11),
     UserID int(11) not null,
     Year int(10),
     totalpay decimal(6,2),
     primary key (OrderID),
     foreign key (UserID) references users (UserID)
   );

   create table trans(
     OrderID int(11) not null,
     ISBN varchar(13) not null,
     Quantity int(11),
     primary key (OrderID, ISBN),
     foreign key (OrderID) references orders (OrderID),
     foreign key (ISBN) references books (ISBN)
   );

I have to clarify something: Given by the task, I am not allowed to add any other attributes or delete the existing attributes.

Body:
Foreign key constraint violation means the table you're trying to update contains references to some other table, and you're somehow breaking that reference.

If I've got a table Movies

+----------+---------------+
| Movie_ID |  Movie_Name   |
+----------+---------------+
|        1 | Jaws          |
|        2 | Star-Wars     |
|        3 | Jurassic Park |
+----------+---------------+

And a table User_Reviews

+---------+----------+-------+
| User_ID | Movie_ID | Score |
+---------+----------+-------+
|       1 |        1 | 2.5   |
|       2 |        1 | 5     |
|       3 |        2 | 4     |
|       4 |        2 | 3     |
|       5 |        2 | 4.5   |
|       6 |        3 | 5     |
+---------+----------+-------+

In the User_Reviews table, Movie_ID is a foreign key.

I can't have a review with Movie_ID = 10, because that movie doesn't exist in the Movies table. If I did try to do that, I'd get a foreign key constraint error.


问:
Running a program from a past/future time in nodejs
I am trying to write an automated test for an engine which connects to a license server, one of the things that I want to test is how the engine will react when the license is expired while the engine is running. I am using nodejs to manually start this engine by running some commands on cmd to call the engine start script (ie/startengine.bat or ./startengine.sh), I was wondering if there is a way to alter the time at which the engine is started using nodejs. For example, if the license is set to expire on December 2nd of 2018, is there a way to start the engine with a "fake" time of December 1st 23:59?

I tried using timekeeper node package and when i do:

```<code>var time = new Date(1569902400);
timeKeeper.travel(time);
var today = new Date();
console.log(today.getDay());
</code>```

I seem to get the date that I want but when I start my engine, it doesn't seem to be using this time... are there anything that I am missing or is there another way of doing this?

答: Cause the 19th January 1970 was a Monday. And today is Monday too... ;)</p>

Body:
I am trying to write an automated test for an engine which connects to a license server, one of the things that I want to test is how the engine will react when the license is expired while the engine is running. I am using nodejs to manually start this engine by running some commands on cmd to call the engine start script (ie/startengine.bat or ./startengine.sh), I was wondering if there is a way to alter the time at which the engine is started using nodejs. For example, if the license is set to expire on December 2nd of 2018, is there a way to start the engine with a "fake" time of December 1st 23:59?

I tried using timekeeper node package and when i do:

var time = new Date(1569902400);
timeKeeper.travel(time);
var today = new Date();
console.log(today.getDay());

I seem to get the date that I want but when I start my engine, it doesn't seem to be using this time... are there anything that I am missing or is there another way of doing this?


问:
using an index within jQuery each method
I have the following loop using the jQuery each method. I'm trying to leverage the index of the loop to ensure checkboxes and labels in my markup have the correct dynamic content. On each pass through, I'm appending the index to the class name then assigning a value and text content to the appropriate elements, based on the new modified class name. Is there a simpler or cleaner way to go about this? 'Managers' in this case contains text and value properties for the items I'm iterating through.

```<code>$(Managers).each(function (index) {
    $('.chk-hr').attr('class', 'chk-hr-' + index);
    $('.chk-hr-' + index).attr("value", this.Text);
    $('.lbl-hr').attr('class', 'lbl-hr-' + index);
    $('.lbl-hr-' + index).text(this.Text);
});
</code>```

Desired output:

```<code><input class="chk-hr-0" value="Bob">
<span class="lbl-hr-0">Bob</span>
<input class="chk-hr-1" value="John">
<span class="lbl-hr-1">John</span>
</code>```

答:
As suggested by @ClaytonLeis, <code>.eq</code> helped me simplify this loop:    </p>

```<code>$(Managers).each(function (index) {
    $('.chk-hr').eq(index).attr("value", this.Text);
    $('.lbl-hr').eq(index).text(this.Text);
});
</code>```

Body:
I have the following loop using the jQuery each method. I'm trying to leverage the index of the loop to ensure checkboxes and labels in my markup have the correct dynamic content. On each pass through, I'm appending the index to the class name then assigning a value and text content to the appropriate elements, based on the new modified class name. Is there a simpler or cleaner way to go about this? 'Managers' in this case contains text and value properties for the items I'm iterating through.

$(Managers).each(function (index) {
    $('.chk-hr').attr('class', 'chk-hr-' + index);
    $('.chk-hr-' + index).attr("value", this.Text);
    $('.lbl-hr').attr('class', 'lbl-hr-' + index);
    $('.lbl-hr-' + index).text(this.Text);
});

Desired output:

<input class="chk-hr-0" value="Bob">
Bob
<input class="chk-hr-1" value="John">
John

Body:
As suggested by @ClaytonLeis, .eq helped me simplify this loop:

$(Managers).each(function (index) {
    $('.chk-hr').eq(index).attr("value", this.Text);
    $('.lbl-hr').eq(index).text(this.Text);
});


问:
Using training data and testing data in a shared task
I am working on this shared task http://alt.qcri.org/semeval2017/task4/index.php?id=data-and-tools

which is just a twitter sentiment analysis. Since i am pretty new to machine learning, I am not quite sure how to use both training data and testing data.

So the shared task provides two same sets of twitter tweets one without the result (train) and one with the result.

I current understandings of using these kinds of data in machine learning are as follows:

training set: we are supposed to split this into training and testing portions (90% training and 10% testing maybe?)

But the existing of a separate test data kind of confuses.

Are we supposed to use the result that we got in the test using the 10% portion of the 'training set' and compare that to the actual result 'testing set' ?

Can someone correct my understanding?

答:
When training a machine learning model, you are feeding your algorithm with the dataset called training set, which in this stage, you are telling the algorithm what is the ground truth of each sample you put into the algorithm, that way, the algorithm learns from each sample you are feeding to it. the training set is usually 80% of the whole dataset, the other 20% of the dataset is the testing set, which in this case, you know what is the ground truth of each sample, but you let your algorithm predict what it think the truth is to each sample you let it predict. All those prediction over the testing set are based on what the algorithm have learned from the training set you fed it before.
After you make all the predictions over your testing set you can then check how accurate your model is based on the ground truth in compare to the prediction the model have made.


问:
JQuery UI Dialgo modal's title html tags is not rendered
I am currently adding modal to my application. When modal is displayed it also shows the html tags inside modal title.

As you see dialog title is not rendered and it shows html tags. Here it is dialog html

```<code><div id="dialog_simple" title="Dialog Simple Title">
  <p>
   Dialog part is woring just fine.
  </p>

</div>
</code>```

And here related javascript to open modal

```<code>$('#dialog_link').click(function() {
        $('#dialog_simple').dialog('open');
        return false;
  });

 $('#dialog_simple').dialog({
          autoOpen : false,
          width : 600,
          resizable : false,
          modal : true,
          title : "<div class='widget-header'><h4><i class='fa fa-warning'></i> Empty the recycle bin?</h4></div>",
          buttons : [{
            html : "<i class='fa fa-trash-o'></i>  Delete all items",
            "class" : "btn btn-danger",
            click : function() {
              $(this).dialog("close");
            }
          }, {
            html : "<i class='fa fa-times'></i>  Cancel",
            "class" : "btn btn-default",
            click : function() {
              $(this).dialog("close");
            }
          }]
        });

        })
</code>```

Am I missing something? Thanks in advance

答:
Looks like this is not related to Bootstrap.
From what I can see you are using jQuery UI Dialog (http://jqueryui.com/dialog/), right?

The title property only accepts a string but you can overwrite the default behaviour as shown here: https://stackoverflow.com/a/14488776/3215856

Body:
I am currently adding modal to my application. When modal is displayed it also shows the html tags inside modal title.

As you see dialog title is not rendered and it shows html tags. Here it is dialog html

   Dialog part is woring just fine.

And here related javascript to open modal

$('#dialog_link').click(function() {
        $('#dialog_simple').dialog('open');
        return false;
  });

 $('#dialog_simple').dialog({
          autoOpen : false,
          width : 600,
          resizable : false,
          modal : true,
          title : "

 Empty the recycle bin?

",
          buttons : [{
            html : "  Delete all items",
            "class" : "btn btn-danger",
            click : function() {
              $(this).dialog("close");
            }
          }, {
            html : "  Cancel",
            "class" : "btn btn-default",
            click : function() {
              $(this).dialog("close");
            }
          }]
        });

        })

Am I missing something? Thanks in advance


问:
get the count of columns contains a string in pandas
I have two dataframes df1 and df2.

df1:

```<code>PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12
</code>```

df2:

```<code>PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
</code>```

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

答:
You can use map

```<code>df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())
</code>```

df1:

```<code>    PartNumber  count_of_colors
0   0000D3447E  14
1   0000D3447E  14
2   0000D3447E  14
3   0000D3447E  14
4   0000D3447E  14
5   0000D3447E  14
6   0000D3447E  14
7   0000F2892E  7
8   0000F2892E  7
9   0000F2892E  7
10  0000F2892E  7
11  0000F2892E  7
12  0000F2892E  7
13  0000F2892E  7
</code>```

EDIT: Use str.extract to extract the exact match in df2 and then use same solution

```<code>pat = '({})'.format('|'.join(df1['PartNumber'].unique()))

df2['PartMatch'] = df2['PartNumber'].str.extract(pat, expand = False)

df1['count_of_colors'] = df1['PartNumber'].map(df2['PartMatch'].value_counts())
</code>```

You get the same output and its not hard-coded for the number of characters

Body:
I have two dataframes df1 and df2.

df1:

PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12

df2:

PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

Body:
You can use map

df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

df1:

    PartNumber  count_of_colors
0   0000D3447E  14
1   0000D3447E  14
2   0000D3447E  14
3   0000D3447E  14
4   0000D3447E  14
5   0000D3447E  14
6   0000D3447E  14
7   0000F2892E  7
8   0000F2892E  7
9   0000F2892E  7
10  0000F2892E  7
11  0000F2892E  7
12  0000F2892E  7
13  0000F2892E  7

EDIT: Use str.extract to extract the exact match in df2 and then use same solution

pat = '({})'.format('|'.join(df1['PartNumber'].unique()))

df2['PartMatch'] = df2['PartNumber'].str.extract(pat, expand = False)

df1['count_of_colors'] = df1['PartNumber'].map(df2['PartMatch'].value_counts())

You get the same output and its not hard-coded for the number of characters


问:
React Semantic UI - mobile view marginRight
I use react semantic ui for a little web app with the heroku react create app buildpack.

For some reason I always get a margin on the right of a fluid container. Chrome's inspector does not see the margin on the body, page or any other element.

Please see the pictures attached.

How do I get rid of this?

This is my code:

```<code>import React from 'react';
import MainMenu from '../../components/menu';
import * from '../../components/search/searchComponents';
import {Button, Container, Image, Item, Label, Responsive, Segment} from 'semantic-ui-react';

/*START TESTDATA*/
const data= [
]
/*END TESTDATA*/

export default class Search extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            searchType: undefined,
            searchResults: [],
            showSearchResultDetails: false,
            mainSearchStyleHeight: 'calc(100vh - 40px)',
            mainSearchStylePTop: 'calc(33vh - 40px)',
            mainSearchStyleTransition: undefined,
        };
    }

    searchButtonHandleOnClick(){
        this.setState({
            mainSearchStyleHeight: '100%',
            mainSearchStylePTop: '2rem',
            mainSearchStylePBottom: '2rem',
            mainSearchStyleTransition: 'height: 1s ease-in',
            searchResults: dishes
        })
    }
    handleSearchResultOnClick(item){
        this.setState({showSearchResultDetails: true})
    }
    render() {
        /*TODO: add css transition here*/
        var mainSearchStyle = {
            height: this.state.mainSearchStyleHeight,
            paddingTop: this.state.mainSearchStylePTop,
            paddingBottom: this.state.mainSearchStylePBottom,
            transition: this.state.mainSearchStyleTransition
        }
        const searchBtn = <Button basic icon="search" content="Suchen" onClick={this.searchButtonHandleOnClick.bind(this)}/>
        return (
            <div>
                <MainMenu/>
                <Container fluid id="mainSearch" style={mainSearchStyle}>
                    <Container>
                        <Responsive as={Segment} minWidth={768} raised padded="very">
                            <SearchByAttr/>
                            <div className="txt-center mt-2">
                                {searchBtn}
                            </div>
                        </Responsive>
                        <Responsive maxWidth={767} className="pt-3 pb-3">
                            <SearchByAttr/>
                            <div className="txt-center mt-2">
                                {searchBtn}
                            </div>
                        </Responsive>
                    </Container>
                </Container>

                <Container id="mainSearchResults" className="p-1">
                    {/*TODO: move this to search components*/}
                    <Item.Group divided>
                        {this.state.searchResults.length > 0 && this.state.searchResults.map(item=>(
                            <Item key={item.name}>
                                <Image
                                    size="small"
                                    src='http://via.placeholder.com/300x250'
                                    label={{ color: 'blue', content: '4,90 Euro', icon: 'spoon', ribbon: true }}
                                />
                                <Item.Content>
                                    <Item.Header as='a' onClick={this.handleSearchResultOnClick.bind(this, item)}>
                                        {item.name}
                                        </Item.Header>
                                    <Item.Meta>
                                        <span className='cinema'>
                                            Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
                                        </span>
                                    </Item.Meta>
                                    <Item.Description>
                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
                                        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
                                        sed diam voluptua.
                                    </Item.Description>
                                    <Item.Extra>
                                        <Label content='vegan' />
                                        <Label content='laktosefrei' />
                                        <Label content='low carb' />
                                    </Item.Extra>
                                </Item.Content>
                            </Item>
                        ))}
                    </Item.Group>

                </Container>
                <SearchResultDetails
                    open={this.state.showSearchResultDetails}
                    onClose={()=>this.setState({showSearchResultDetails: false})}
                />
            </div>
        );
    }
};
</code>```

答:
Just guessing. Looks like it is not about the Responsive container. The whole page is off to the left, including menu. So the problem might be outside of this Component.

Try just render a Hello to see.

```<code>render() {
    return <div>Hello</div>
}
</code>```

Body:
I use react semantic ui for a little web app with the heroku react create app buildpack.

For some reason I always get a margin on the right of a fluid container. Chrome's inspector does not see the margin on the body, page or any other element.

Please see the pictures attached.

How do I get rid of this?

This is my code:

import React from 'react';
import MainMenu from '../../components/menu';
import * from '../../components/search/searchComponents';
import {Button, Container, Image, Item, Label, Responsive, Segment} from 'semantic-ui-react';

/*START TESTDATA*/
const data= [
]
/*END TESTDATA*/

export default class Search extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            searchType: undefined,
            searchResults: [],
            showSearchResultDetails: false,
            mainSearchStyleHeight: 'calc(100vh - 40px)',
            mainSearchStylePTop: 'calc(33vh - 40px)',
            mainSearchStyleTransition: undefined,
        };
    }

    searchButtonHandleOnClick(){
        this.setState({
            mainSearchStyleHeight: '100%',
            mainSearchStylePTop: '2rem',
            mainSearchStylePBottom: '2rem',
            mainSearchStyleTransition: 'height: 1s ease-in',
            searchResults: dishes
        })
    }
    handleSearchResultOnClick(item){
        this.setState({showSearchResultDetails: true})
    }
    render() {
        /*TODO: add css transition here*/
        var mainSearchStyle = {
            height: this.state.mainSearchStyleHeight,
            paddingTop: this.state.mainSearchStylePTop,
            paddingBottom: this.state.mainSearchStylePBottom,
            transition: this.state.mainSearchStyleTransition
        }
        const searchBtn = <Button basic icon="search" content="Suchen" onClick={this.searchButtonHandleOnClick.bind(this)}/>
        return (

                <MainMenu/>
                <Container fluid id="mainSearch" style={mainSearchStyle}>
                    <Container>
                        <Responsive as={Segment} minWidth={768} raised padded="very">
                            <SearchByAttr/>

                                {searchBtn}

                        </Responsive>
                        <Responsive maxWidth={767} className="pt-3 pb-3">
                            <SearchByAttr/>

                                {searchBtn}

                        </Responsive>
                    </Container>
                </Container>

                <Container id="mainSearchResults" className="p-1">
                    {/*TODO: move this to search components*/}
                    <Item.Group divided>
                        {this.state.searchResults.length > 0 && this.state.searchResults.map(item=>(
                            <Item key={item.name}>
                                <Image
                                    size="small"
                                    src='http://via.placeholder.com/300x250'
                                    label={{ color: 'blue', content: '4,90 Euro', icon: 'spoon', ribbon: true }}
                                />
                                <Item.Content>
                                    <Item.Header as='a' onClick={this.handleSearchResultOnClick.bind(this, item)}>
                                        {item.name}
                                        </Item.Header>
                                    <Item.Meta>

                                            Lorem ipsum dolor sit amet, consetetur sadipscing elitr,

                                    </Item.Meta>
                                    <Item.Description>
                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
                                        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
                                        sed diam voluptua.
                                    </Item.Description>
                                    <Item.Extra>

                                    </Item.Extra>
                                </Item.Content>
                            </Item>
                        ))}
                    </Item.Group>

                </Container>
                <SearchResultDetails
                    open={this.state.showSearchResultDetails}
                    onClose={()=>this.setState({showSearchResultDetails: false})}
                />

        );
    }
};

Body:
Just guessing. Looks like it is not about the Responsive container. The whole page is off to the left, including menu. So the problem might be outside of this Component.

Try just render a Hello to see.

render() {
    return <div>Hello</div>
}