问:
calculates highest count words across lines error in ruby coursera
it's almost 2 weeks now I can't remove this from my head. I'm a newbie in ruby and I'm stuck with this last bit of Ruby on Rails an introduction course on coursera. It'll certainly be easy to figure out what's wrong here but I need help to finish this course in time this time around.

#Implement all parts of this assignment within (this) module2_assignment2.rb file

#Implement a class called LineAnalyzer.
class LineAnalyzer
  #Implement the following read-only attributes in the LineAnalyzer class.
  #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated)
  #* highest_wf_words - an array of words with the maximum number of occurrences (calculated)
  #* content          - the string analyzed (provided)
  #* line_number      - the line number analyzed (provided)

  #Add the following methods in the LineAnalyzer class.
  #* initialize() - taking a line of text (content) and a line number
  #* calculate_word_frequency() - calculates result

  #Implement the initialize() method to:
  #* take in a line of text and line number
  #* initialize the content and line_number attributes
  #* call the calculate_word_frequency() method.

  #Implement the calculate_word_frequency() method to:
  #* calculate the maximum number of times a single word appears within
  #  provided content and store that in the highest_wf_count attribute.
  #* identify the words that were used the maximum number of times and
  #  store that in the highest_wf_words attribute.

    attr_accessor :highest_wf_count, :highest_wf_words, :content, :line_number

    def initialize(content, line)
    @content = content
    @line_number = line
    @highest_wf_count=0
    @highest_wf_words = []
    calculate_word_frequency()
  end

  def calculate_word_frequency()
    @highest_wf_words = Hash.new
    words = @content.split
    words.each { |w|
      if @highest_wf_words.has_key?(w)
        @highest_wf_words[w] += 1
      else
        @highest_wf_words[w] = 1
      end
    }
    @highest_wf_words.sort_by { |word, count| count }
    @highest_wf_words.each do |key, value|
      if value > @highest_wf_count
        @highest_wf_count = value
      end
    end
  end

  def highest_wf_count= (number)
    @highest_wf_count = number
  end

end

#  Implement a class called Solution.
class Solution

  # Implement the following read-only attributes in the Solution class.
  #* analyzers - an array of LineAnalyzer objects for each line in the file
  #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array.
  #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute
  #  equal to the highest_count_across_lines determined previously.

  # Implement the following methods in the Solution class.
  #* analyze_file() - processes 'test.txt' into an array of LineAnalyzers and stores them in analyzers.
  #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and
  #  highest_count_words_across_lines attribute values
  #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in
  #  highest_count_words_across_lines in the specified format

  # Implement the analyze_file() method() to:
  #* Read the 'test.txt' file in lines
  #* Create an array of LineAnalyzers for each line in the file

  # Implement the calculate_line_with_highest_frequency() method to:
  #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array
  #  and stores this result in the highest_count_across_lines attribute.
  #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines
  #  attribute value determined previously and stores them in highest_count_words_across_lines.

  #Implement the print_highest_word_frequency_across_lines() method to
  #* print the values of objects in highest_count_words_across_lines in the specified format

  attr_reader  :analyzers, :highest_count_across_lines, :highest_count_words_across_lines

  def initialize
    @highest_count_across_lines = nil
    @highest_count_words_across_lines = nil
    @analyzers = []
  end

  def analyze_file()
    File.foreach('test.txt') do |content, line|
      LineAnalyzer = LineAnalyzer.new(content, line)
      @analyzers << LineAnalyzer
    end
  end

  def calculate_line_with_highest_frequency()
    @highest_count_across_lines = 0
    @highest_count_words_across_lines = []
    @analyzers.each do |analyzers|
      if analyzers.highest_wf_words > @highest_count_across_lines
        @highest_count_across_lines = analyzers.highest_wf_count
      end
      analyzers.highest_wf_words.each do |key, value|
       if analyzers.highest_count_words_across_lines < value
          @highest_count_words_across_lines << key
       end
      end
    end
  end

  def print_highest_word_frequency_across_lines()
    @highest_count_words_across_lines = Array.new
    puts "The following words have the highest word frequency per line:"
  end
end```
</div>
</div>
</p>

<p>I keep on having 1 fail out of 19 on rspec like this:</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-html lang-html prettyprint-override"><code>LineAnalyzer
  has accessor for highest_wf_count
  has accessor for highest_wf_words
  has accessor for content
  has accessor for line_number
  has method calculate_word_frequency
  calls calculate_word_frequency when created
  attributes and values
    has attributes content and line_number
    content attribute should have value "test"
    line_number attribute should have value 1
  #calculate_word_frequency
    highest_wf_count value is 3
    highest_wf_words will include "really" and "you"
    content attribute will have value "This is a really really really cool cool you you you"
    line_number attribute will have value 2

Solution
  should respond to #analyze_file
  should respond to #calculate_line_with_highest_frequency
  should respond to #print_highest_word_frequency_across_lines
  #analyze_file
    creates 3 line analyzers
  #calculate_line_with_highest_frequency
    calculates highest count across lines to be 4
    calculates highest count words across lines to be will, it, really (FAILED - 1)

Failures:

  1) Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really
     Failure/Error: words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten

     NoMethodError:
       undefined method `highest_wf_words' for "This":String
     # ./spec/solution_spec.rb:38:in `map'
     # ./spec/solution_spec.rb:38:in `block (3 levels) in <top (required)>'

Finished in 0.10817 seconds (files took 0.37345 seconds to load)
19 examples, 1 failure

Failed examples:

rspec ./spec/solution_spec.rb:31 # Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really</code>```

And this is the solution_spec file.
Where am I going astray? Please help, it ia a desperate call!

require_relative "../module2_assignment"
require 'rspec'

describe Solution do
  subject(:solution) { Solution.new }

  it { is_expected.to respond_to(:analyze_file) }
  it { is_expected.to respond_to(:calculate_line_with_highest_frequency) }
  it { is_expected.to respond_to(:print_highest_word_frequency_across_lines) }

  context "#analyze_file" do
    it "creates 3 line analyzers" do
      expect(solution.analyzers.length).to eq 0
      solution.analyze_file
      expect(solution.analyzers.length).to eq 3
    end
  end

  context "#calculate_line_with_highest_frequency" do

    it "calculates highest count across lines to be 4" do
      solution.analyze_file

      expect(solution.highest_count_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      expect(solution.highest_count_across_lines).to be 4
    end
    it "calculates highest count words across lines to be will, it, really" do
      solution.analyze_file

      expect(solution.highest_count_words_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
      expect(words_found).to match_array ["will", "it", "really"]
    end
  end

end```

答:
```<code>  words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
</code>```

Here highest_count_words_across_lines returns array of strings, you are calling the method highest_wf_words in each of those strings. But the method is actually defined in the class LineAnalyzer

Hope this helps

Body:
it's almost 2 weeks now I can't remove this from my head. I'm a newbie in ruby and I'm stuck with this last bit of Ruby on Rails an introduction course on coursera. It'll certainly be easy to figure out what's wrong here but I need help to finish this course in time this time around.

#Implement all parts of this assignment within (this) module2_assignment2.rb file

#Implement a class called LineAnalyzer.
class LineAnalyzer
  #Implement the following read-only attributes in the LineAnalyzer class.
  #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated)
  #* highest_wf_words - an array of words with the maximum number of occurrences (calculated)
  #* content          - the string analyzed (provided)
  #* line_number      - the line number analyzed (provided)

  #Add the following methods in the LineAnalyzer class.
  #* initialize() - taking a line of text (content) and a line number
  #* calculate_word_frequency() - calculates result

  #Implement the initialize() method to:
  #* take in a line of text and line number
  #* initialize the content and line_number attributes
  #* call the calculate_word_frequency() method.

  #Implement the calculate_word_frequency() method to:
  #* calculate the maximum number of times a single word appears within
  #  provided content and store that in the highest_wf_count attribute.
  #* identify the words that were used the maximum number of times and
  #  store that in the highest_wf_words attribute.

    attr_accessor :highest_wf_count, :highest_wf_words, :content, :line_number

    def initialize(content, line)
    @content = content
    @line_number = line
    @highest_wf_count=0
    @highest_wf_words = []
    calculate_word_frequency()
  end

  def calculate_word_frequency()
    @highest_wf_words = Hash.new
    words = @content.split
    words.each { |w|
      if @highest_wf_words.has_key?(w)
        @highest_wf_words[w] += 1
      else
        @highest_wf_words[w] = 1
      end
    }
    @highest_wf_words.sort_by { |word, count| count }
    @highest_wf_words.each do |key, value|
      if value > @highest_wf_count
        @highest_wf_count = value
      end
    end
  end

  def highest_wf_count= (number)
    @highest_wf_count = number
  end

end

#  Implement a class called Solution.
class Solution

  # Implement the following read-only attributes in the Solution class.
  #* analyzers - an array of LineAnalyzer objects for each line in the file
  #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array.
  #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute
  #  equal to the highest_count_across_lines determined previously.

  # Implement the following methods in the Solution class.
  #* analyze_file() - processes 'test.txt' into an array of LineAnalyzers and stores them in analyzers.
  #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and
  #  highest_count_words_across_lines attribute values
  #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in
  #  highest_count_words_across_lines in the specified format

  # Implement the analyze_file() method() to:
  #* Read the 'test.txt' file in lines
  #* Create an array of LineAnalyzers for each line in the file

  # Implement the calculate_line_with_highest_frequency() method to:
  #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array
  #  and stores this result in the highest_count_across_lines attribute.
  #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines
  #  attribute value determined previously and stores them in highest_count_words_across_lines.

  #Implement the print_highest_word_frequency_across_lines() method to
  #* print the values of objects in highest_count_words_across_lines in the specified format

  attr_reader  :analyzers, :highest_count_across_lines, :highest_count_words_across_lines

  def initialize
    @highest_count_across_lines = nil
    @highest_count_words_across_lines = nil
    @analyzers = []
  end

  def analyze_file()
    File.foreach('test.txt') do |content, line|
      LineAnalyzer = LineAnalyzer.new(content, line)
      @analyzers << LineAnalyzer
    end
  end

  def calculate_line_with_highest_frequency()
    @highest_count_across_lines = 0
    @highest_count_words_across_lines = []
    @analyzers.each do |analyzers|
      if analyzers.highest_wf_words > @highest_count_across_lines
        @highest_count_across_lines = analyzers.highest_wf_count
      end
      analyzers.highest_wf_words.each do |key, value|
       if analyzers.highest_count_words_across_lines < value
          @highest_count_words_across_lines << key
       end
      end
    end
  end

  def print_highest_word_frequency_across_lines()
    @highest_count_words_across_lines = Array.new
    puts "The following words have the highest word frequency per line:"
  end
end

I keep on having 1 fail out of 19 on rspec like this:

LineAnalyzer
  has accessor for highest_wf_count
  has accessor for highest_wf_words
  has accessor for content
  has accessor for line_number
  has method calculate_word_frequency
  calls calculate_word_frequency when created
  attributes and values
    has attributes content and line_number
    content attribute should have value "test"
    line_number attribute should have value 1
  #calculate_word_frequency
    highest_wf_count value is 3
    highest_wf_words will include "really" and "you"
    content attribute will have value "This is a really really really cool cool you you you"
    line_number attribute will have value 2

Solution
  should respond to #analyze_file
  should respond to #calculate_line_with_highest_frequency
  should respond to #print_highest_word_frequency_across_lines
  #analyze_file
    creates 3 line analyzers
  #calculate_line_with_highest_frequency
    calculates highest count across lines to be 4
    calculates highest count words across lines to be will, it, really (FAILED - 1)

Failures:

  1) Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really
     Failure/Error: words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten

     NoMethodError:
       undefined method `highest_wf_words' for "This":String
     # ./spec/solution_spec.rb:38:in `map'
     # ./spec/solution_spec.rb:38:in `block (3 levels) in <top (required)>'

Finished in 0.10817 seconds (files took 0.37345 seconds to load)
19 examples, 1 failure

Failed examples:

rspec ./spec/solution_spec.rb:31 # Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really

And this is the solution_spec file.
Where am I going astray? Please help, it ia a desperate call!

require_relative "../module2_assignment"
require 'rspec'

describe Solution do
  subject(:solution) { Solution.new }

  it { is_expected.to respond_to(:analyze_file) }
  it { is_expected.to respond_to(:calculate_line_with_highest_frequency) }
  it { is_expected.to respond_to(:print_highest_word_frequency_across_lines) }

  context "#analyze_file" do
    it "creates 3 line analyzers" do
      expect(solution.analyzers.length).to eq 0
      solution.analyze_file
      expect(solution.analyzers.length).to eq 3
    end
  end

  context "#calculate_line_with_highest_frequency" do

    it "calculates highest count across lines to be 4" do
      solution.analyze_file

      expect(solution.highest_count_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      expect(solution.highest_count_across_lines).to be 4
    end
    it "calculates highest count words across lines to be will, it, really" do
      solution.analyze_file

      expect(solution.highest_count_words_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
      expect(words_found).to match_array ["will", "it", "really"]
    end
  end

end

Body:
  words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten

Here highest_count_words_across_lines returns array of strings, you are calling the method highest_wf_words in each of those strings. But the method is actually defined in the class LineAnalyzer

Hope this helps


来源: stackexchange

问:
Using scandir() with Magento
For the home page of my Magento store, I am using a basic gallery script which scans a predefined directory using scandir() and outputs each filename to be displayed in the gallery.

Everything works ok on my local machine, but the script seems to ignore the scandir() and just proceeds as normal without any errors or warnings. If I replace the scandir() and input the filenames directly, the gallery script works fine.

What is going wrong here?

答:
Hard to tell without seeing your code in context, but my guess if scandir is returning an empty array, probably because you're not passing it what you think you're passing it.  Add some debugging to your calls to scandir

```<code>$path;
var_dump($path);

$results = scandir($path);
var_dump($results);
</code>```

and you should have a better idea of whats going on.

ContentLicense: CC BY-SA 2.5

Title: Using scandir() with Magento

Body:
Hard to tell without seeing your code in context, but my guess if scandir is returning an empty array, probably because you're not passing it what you think you're passing it.  Add some debugging to your calls to scandir

$path;
var_dump($path);

$results = scandir($path);
var_dump($results);

and you should have a better idea of whats going on.


问:
How to copy a (ICU4C) Unicode string to another Unicode string character by character?
I'm trying to use ICU's StringCharacterIterator to copy (and possibly alter) characters from a source string to a destination string. However, I am having unexpected results and am unsure why.

I would expect the final line of output of this program to be dog but instead I get og∩┐┐

```<code>#include <iostream>
#include <icu4c/unicode/schriter.h>

int main()
{
    UnicodeString dog = UnicodeString::fromUTF8("dog");
    StringCharacterIterator chars(dog);

    UnicodeString copy;
    while(chars.hasNext())
        copy.append(chars.next32());

    for(int i=0; i<copy.countChar32(); i++)
    {
        int32_t charNumber = copy.char32At(i);
        std::cout << charNumber << "\n";
    }

    std::string stdString;
    copy.toUTF8String(stdString);
    std::cout << stdString;
}
</code>```

Program Output

```<code>111
103
65535
og∩┐┐
</code>```

Unicode table

111 - latin small letter o

103 - latin small letter g

答:
You have two problems:

StringCharacterIterator::hasNext returns false only when the iterator is beyond the end of the string.

StringCharacterIterator::next32 advances the current position of the iterator and returns the new code point.  It is analogous to *(++it) for a raw pointer or standard library style iterator.

Taken together, this means you're skipping the first character of your string and reading an extra character beyond the end.

You can use next32PostInc, which behaves like *(it++) for a raw pointer or standard library iterator, instead of next32:

```<code>while(chars.hasNext())
    copy.append(chars.next32PostInc());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use ICU's StringCharacterIterator to copy (and possibly alter) characters from a source string to a destination string. However, I am having unexpected results and am unsure why.

I would expect the final line of output of this program to be dog but instead I get og∩┐┐

#include <iostream>
#include <icu4c/unicode/schriter.h>

int main()
{
    UnicodeString dog = UnicodeString::fromUTF8("dog");
    StringCharacterIterator chars(dog);

    UnicodeString copy;
    while(chars.hasNext())
        copy.append(chars.next32());

    for(int i=0; i<copy.countChar32(); i++)
    {
        int32_t charNumber = copy.char32At(i);
        std::cout << charNumber << "\n";
    }

    std::string stdString;
    copy.toUTF8String(stdString);
    std::cout << stdString;
}

Program Output

111
103
65535
og∩┐┐

Unicode table

111 - latin small letter o

103 - latin small letter g

Body:
You have two problems:

StringCharacterIterator::hasNext returns false only when the iterator is beyond the end of the string.

StringCharacterIterator::next32 advances the current position of the iterator and returns the new code point.  It is analogous to *(++it) for a raw pointer or standard library style iterator.

Taken together, this means you're skipping the first character of your string and reading an extra character beyond the end.

You can use next32PostInc, which behaves like *(it++) for a raw pointer or standard library iterator, instead of next32:

while(chars.hasNext())
    copy.append(chars.next32PostInc());


问:
How to remove a character in the dataframe using the stringi package?
I currently have a dataframe of stock KPIs and I would like to remove the "$" character from the data. However, I can only use one line of code in addition to the mandatory usage of the stringi package. Looking at the documentation, the "stri_replace_all_fixed" was the function that stood out to me, but upon running that function, my data frame lost its formatting. I tried combining both the lapply and the stri_replace_all_fixed functions to no avail. Pointers on how to address this problem would be much appreciated.

答:
```<code># Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    mutate(value = sample(1:10, 50, replace = TRUE) %>% paste("$"))

# scrub a dub (using dplyr)
dta %>% mutate_all(funs(stri_replace_all_fixed(., "$", "")))
</code>```

and it is one of the faster approaches, too: replacement drag races

Body:
# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    mutate(value = sample(1:10, 50, replace = TRUE) %>% paste("$"))

# scrub a dub (using dplyr)
dta %>% mutate_all(funs(stri_replace_all_fixed(., "$", "")))

and it is one of the faster approaches, too: replacement drag races


问:
List only devices shown in 'Devices and Printers' panel
I am writing an application in C# that will run on a users PC and I want to list only the devices that are shown in the Windows "Devices and Printers" control panel, things like monitors, keyboard, mouse, speakers etc.

I can use WMI to extract a list of all devices, but is there a way to only extract only those that are shown in that part of control panel rather than the full list?

I have searched online and found nothing relating to this and I can't even find what is the criteria for a device to appear in that list.

Is it possible to access the list of those devices that are shown in that list or, if not, is there a filter that can be applied to the full list that will only show those devices?

thanks in advance

答:
I do it with p/invoke and COM interop by enumerating the shell items in Microsoft.DevicesAndPrinters and filtering by making sure that PKEY_Devices_CategoryIds contains an item starting with PrintFax.

There's no way to boil the necessary interop definitions down to fit in an answer, but this is the logic I use to enumerate the display name, the DEVMODE name, and images of any size:

```<code>public sealed class PrinterInfo
{
    public string IdName { get; }
    public string DisplayName { get; }
    public Bitmap Image { get; }

    private PrinterInfo(string idName, string displayName, Bitmap image)
    {
        IdName = idName;
        DisplayName = displayName;
        Image = image;
    }

    public static IReadOnlyList<PrinterInfo> GetInstalledPrinterNamesAndImages(Size imageSize)
    {
        var r = new List<PrinterInfo>();

        using (var folderIdList = CreateDevicesAndPrintersIDL())
        {
            var folder = GetShellFolder(folderIdList);
            var enumerator = folder.EnumObjects(IntPtr.Zero, SHCONTF.NONFOLDERS);

            for (;;)
            {
                // If you request more than are left, actualCount is 0, so we'll do one at a time.
                var next = enumerator.Next(1, out var relativeIdList, out var actualCount);
                next.ThrowIfError();
                if (next == HResult.False || actualCount != 1) break; // printerChild is junk

                using (relativeIdList)
                using (var absoluteIdList = ILCombine(folderIdList, relativeIdList))
                {
                    var shellItem = GetShellItem(absoluteIdList);
                    var idName = GetPrinterFriendlyNameIfPrinter(shellItem);
                    if (idName != null)
                        r.Add(new PrinterInfo(idName, GetDisplayName(shellItem), GetImage(shellItem, imageSize)));
                }
            }
        }

        return r;
    }

    private static ItemIdListSafeHandle CreateDevicesAndPrintersIDL()
    {
        SHGetKnownFolderIDList(FOLDERID.ControlPanelFolder, KF_FLAG.DEFAULT, IntPtr.Zero, out var controlPanelIdList).ThrowIfError();
        using (controlPanelIdList)
        {
            GetShellFolder(controlPanelIdList).ParseDisplayName(IntPtr.Zero, null, "::{A8A91A66-3A7D-4424-8D24-04E180695C7A}", IntPtr.Zero, out var childDevicesAndPriversIdList, IntPtr.Zero);
            using (childDevicesAndPriversIdList)
                return ILCombine(controlPanelIdList, childDevicesAndPriversIdList);
        }
    }

    private static string GetPrinterFriendlyNameIfPrinter(IShellItem2 shellItem)
    {
        // Devices_PrimaryCategory returns "Printers" for printers and faxes on Windows 10 but "Printers and faxes" on Windows 7.
        using (var categoryIds = new PropVariantSafeHandle())
        {
            shellItem.GetProperty(PKEY.Devices_CategoryIds, categoryIds).ThrowIfError();
            if (!categoryIds.ToStringVector().Any(id => id.StartsWith("PrintFax", StringComparison.OrdinalIgnoreCase)))
                return null;
        }

        // The canonical or "friendly name" needed to match the devmode
        // https://blogs.msdn.microsoft.com/asklar/2009/10/21/getting-the-printer-friendly-name-from-the-device-center-shell-folder/
        // PKEY_Devices_InterfacePaths doesn't seem to ever be found, but PKEY_Devices_FriendlyName works so...
        shellItem.GetString(PKEY.Devices_FriendlyName, out var friendlyName).ThrowIfError();
        return friendlyName.ReadAndFree();
    }

    private static string GetDisplayName(IShellItem2 shellItem)
    {
        return shellItem.GetDisplayName(SIGDN.NORMALDISPLAY).ReadAndFree();
    }

    private static Bitmap GetImage(IShellItem2 shellItem, Size imageSize)
    {
        return ((IShellItemImageFactory)shellItem).GetImage(new POINT(imageSize.Width, imageSize.Height), SIIGBF.SIIGBF_BIGGERSIZEOK)
            .CopyAndFree(); // Bitmap.FromHbitmap is useless with alpha, so make a copy
    }

    private static IShellFolder GetShellFolder(ItemIdListSafeHandle itemIdList)
    {
        SHBindToObject(IntPtr.Zero, itemIdList, null, typeof(IShellFolder).GUID, out var objShellFolder).ThrowIfError();
        return (IShellFolder)objShellFolder;
    }

    private static IShellItem2 GetShellItem(ItemIdListSafeHandle itemIdList)
    {
        SHCreateItemFromIDList(itemIdList, typeof(IShellItem2).GUID, out var objShellItem).ThrowIfError();
        return (IShellItem2)objShellItem;
    }
}
</code>```

(C# 7)

Here's a full demo you can compile: https://github.com/jnm2/example-devices-and-printers/tree/master/src

For a C# 6 version which doesn't require ValueTuple, see https://github.com/jnm2/example-devices-and-printers/tree/master/src-csharp6.

I'm happy to answer any questions.

Body:
I do it with p/invoke and COM interop by enumerating the shell items in Microsoft.DevicesAndPrinters and filtering by making sure that PKEY_Devices_CategoryIds contains an item starting with PrintFax.

There's no way to boil the necessary interop definitions down to fit in an answer, but this is the logic I use to enumerate the display name, the DEVMODE name, and images of any size:

public sealed class PrinterInfo
{
    public string IdName { get; }
    public string DisplayName { get; }
    public Bitmap Image { get; }

    private PrinterInfo(string idName, string displayName, Bitmap image)
    {
        IdName = idName;
        DisplayName = displayName;
        Image = image;
    }

    public static IReadOnlyList<PrinterInfo> GetInstalledPrinterNamesAndImages(Size imageSize)
    {
        var r = new List<PrinterInfo>();

        using (var folderIdList = CreateDevicesAndPrintersIDL())
        {
            var folder = GetShellFolder(folderIdList);
            var enumerator = folder.EnumObjects(IntPtr.Zero, SHCONTF.NONFOLDERS);

            for (;;)
            {
                // If you request more than are left, actualCount is 0, so we'll do one at a time.
                var next = enumerator.Next(1, out var relativeIdList, out var actualCount);
                next.ThrowIfError();
                if (next == HResult.False || actualCount != 1) break; // printerChild is junk

                using (relativeIdList)
                using (var absoluteIdList = ILCombine(folderIdList, relativeIdList))
                {
                    var shellItem = GetShellItem(absoluteIdList);
                    var idName = GetPrinterFriendlyNameIfPrinter(shellItem);
                    if (idName != null)
                        r.Add(new PrinterInfo(idName, GetDisplayName(shellItem), GetImage(shellItem, imageSize)));
                }
            }
        }

        return r;
    }

    private static ItemIdListSafeHandle CreateDevicesAndPrintersIDL()
    {
        SHGetKnownFolderIDList(FOLDERID.ControlPanelFolder, KF_FLAG.DEFAULT, IntPtr.Zero, out var controlPanelIdList).ThrowIfError();
        using (controlPanelIdList)
        {
            GetShellFolder(controlPanelIdList).ParseDisplayName(IntPtr.Zero, null, "::{A8A91A66-3A7D-4424-8D24-04E180695C7A}", IntPtr.Zero, out var childDevicesAndPriversIdList, IntPtr.Zero);
            using (childDevicesAndPriversIdList)
                return ILCombine(controlPanelIdList, childDevicesAndPriversIdList);
        }
    }

    private static string GetPrinterFriendlyNameIfPrinter(IShellItem2 shellItem)
    {
        // Devices_PrimaryCategory returns "Printers" for printers and faxes on Windows 10 but "Printers and faxes" on Windows 7.
        using (var categoryIds = new PropVariantSafeHandle())
        {
            shellItem.GetProperty(PKEY.Devices_CategoryIds, categoryIds).ThrowIfError();
            if (!categoryIds.ToStringVector().Any(id => id.StartsWith("PrintFax", StringComparison.OrdinalIgnoreCase)))
                return null;
        }

        // The canonical or "friendly name" needed to match the devmode
        // https://blogs.msdn.microsoft.com/asklar/2009/10/21/getting-the-printer-friendly-name-from-the-device-center-shell-folder/
        // PKEY_Devices_InterfacePaths doesn't seem to ever be found, but PKEY_Devices_FriendlyName works so...
        shellItem.GetString(PKEY.Devices_FriendlyName, out var friendlyName).ThrowIfError();
        return friendlyName.ReadAndFree();
    }

    private static string GetDisplayName(IShellItem2 shellItem)
    {
        return shellItem.GetDisplayName(SIGDN.NORMALDISPLAY).ReadAndFree();
    }

    private static Bitmap GetImage(IShellItem2 shellItem, Size imageSize)
    {
        return ((IShellItemImageFactory)shellItem).GetImage(new POINT(imageSize.Width, imageSize.Height), SIIGBF.SIIGBF_BIGGERSIZEOK)
            .CopyAndFree(); // Bitmap.FromHbitmap is useless with alpha, so make a copy
    }

    private static IShellFolder GetShellFolder(ItemIdListSafeHandle itemIdList)
    {
        SHBindToObject(IntPtr.Zero, itemIdList, null, typeof(IShellFolder).GUID, out var objShellFolder).ThrowIfError();
        return (IShellFolder)objShellFolder;
    }

    private static IShellItem2 GetShellItem(ItemIdListSafeHandle itemIdList)
    {
        SHCreateItemFromIDList(itemIdList, typeof(IShellItem2).GUID, out var objShellItem).ThrowIfError();
        return (IShellItem2)objShellItem;
    }
}

(C# 7)

Here's a full demo you can compile: https://github.com/jnm2/example-devices-and-printers/tree/master/src

For a C# 6 version which doesn't require ValueTuple, see https://github.com/jnm2/example-devices-and-printers/tree/master/src-csharp6.

I'm happy to answer any questions.


问:
Select elements in such a way that most of the elements are in the beginning of a list
I have a list of values and I want to select n values in such a way that most of the elements come from the beginning of the list and diminish as it goes further in the list (as shown in the link below).

```<code>np.random.seed(0)
a = pd.Series(range(100))
np.random.shuffle(a)
a.values

array([26, 86,  2, 55, 75, 93, 16, 73, 54, 95, 53, 92, 78, 13,  7, 30, 22,
       24, 33,  8, 43, 62,  3, 71, 45, 48,  6, 99, 82, 76, 60, 80, 90, 68,
       51, 27, 18, 56, 63, 74,  1, 61, 42, 41,  4, 15, 17, 40, 38,  5, 91,
       59,  0, 34, 28, 50, 11, 35, 23, 52, 10, 31, 66, 57, 79, 85, 32, 84,
       14, 89, 19, 29, 49, 97, 98, 69, 20, 94, 72, 77, 25, 37, 81, 46, 39,
       65, 58, 12, 88, 70, 87, 36, 21, 83,  9, 96, 67, 64, 47, 44])
</code>```

what is the good way to select those numbers?

http://www.bydatabedriven.com/wp-content/uploads/2012/12/Screen-Shot-2012-12-03-at-8.12.36-PM.png

As an example if n = 10, then the returned values may be (more numbers picked from the begining of the list as compared to those values which are to the end of the list) :

26, 2, 16, 92, 8, 45, 61, 99, 94 39

答:
You can use np.random.choice and pass appropriately-shaped weights, either directly or using pd.Series.sample since you're using pandas.  For example:

```<code>In [59]: s = pd.Series(range(100))

In [60]: chosen = s.sample(10**6, replace=True, weights=1.0/(1+np.arange(len(s)))) #typecast the weight to float

In [61]: chosen.hist(bins=50).get_figure().savefig("out.png")
</code>```

gives me

You can tweak the weights function to your heart's content.  Here I used basically 1/i, so that the 4th element is 4 times less likely to be selected than the first.  You could take that expression to some power, with **2 making the 4th element 16 times less likely to be selected, or **0.5 making the 4th element half as likely to be selected as the first.  Entirely up to you to find a behaviour you're happy with.

Also note that here I'm using replace=True, because I wanted to select a large number of values to make the plot look better.  If you don't want the same element to be selected twice, use replace=False.

Body:
I have a list of values and I want to select n values in such a way that most of the elements come from the beginning of the list and diminish as it goes further in the list (as shown in the link below).

np.random.seed(0)
a = pd.Series(range(100))
np.random.shuffle(a)
a.values

array([26, 86,  2, 55, 75, 93, 16, 73, 54, 95, 53, 92, 78, 13,  7, 30, 22,
       24, 33,  8, 43, 62,  3, 71, 45, 48,  6, 99, 82, 76, 60, 80, 90, 68,
       51, 27, 18, 56, 63, 74,  1, 61, 42, 41,  4, 15, 17, 40, 38,  5, 91,
       59,  0, 34, 28, 50, 11, 35, 23, 52, 10, 31, 66, 57, 79, 85, 32, 84,
       14, 89, 19, 29, 49, 97, 98, 69, 20, 94, 72, 77, 25, 37, 81, 46, 39,
       65, 58, 12, 88, 70, 87, 36, 21, 83,  9, 96, 67, 64, 47, 44])

what is the good way to select those numbers?

http://www.bydatabedriven.com/wp-content/uploads/2012/12/Screen-Shot-2012-12-03-at-8.12.36-PM.png

As an example if n = 10, then the returned values may be (more numbers picked from the begining of the list as compared to those values which are to the end of the list) :

26, 2, 16, 92, 8, 45, 61, 99, 94 39

Body:
You can use np.random.choice and pass appropriately-shaped weights, either directly or using pd.Series.sample since you're using pandas.  For example:

In [59]: s = pd.Series(range(100))

In [60]: chosen = s.sample(10**6, replace=True, weights=1.0/(1+np.arange(len(s)))) #typecast the weight to float

In [61]: chosen.hist(bins=50).get_figure().savefig("out.png")

gives me

You can tweak the weights function to your heart's content.  Here I used basically 1/i, so that the 4th element is 4 times less likely to be selected than the first.  You could take that expression to some power, with **2 making the 4th element 16 times less likely to be selected, or **0.5 making the 4th element half as likely to be selected as the first.  Entirely up to you to find a behaviour you're happy with.

Also note that here I'm using replace=True, because I wanted to select a large number of values to make the plot look better.  If you don't want the same element to be selected twice, use replace=False.


问:
How to retrieve data in a trigger from the header table that was already deleted
I have a situation where I have a Header and a Detail table. The Detail table has a foreign key relationship to the Header table with Cascade delete.

When the detail records are deleted I need to update other tables using a trigger. The problem I am having is that I need to pull some information from the Header table as well as the Detail table for the deleted records. If I delete the Detail records and then the Header record the trigger appears to run fine. However, if I delete the Header record, which in turn deletes the Detail records due to the cascading delete, then when the trigger executes the Header record is already deleted and I can't access the information I need from it.

I am rather new to triggers, so I'm wondering if there is something I just don't know and how I accomplish this.

Here is my code:

```<code>ALTER TRIGGER [Detail_Delete]
   ON [Detail]
   AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- Here is where the problem lies.
 -- No records are found here because the Header record isn't found.
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, h.UserID
 FROM deleted d
 JOIN Header h ON h.HeaderID = d.HeaderID

 EXECUTE sp_UpdateSummary
  @Table = @Table
END
</code>```

答: If the Header record is deleted first, you have no access to it when the Detail-Record trigger runs as the Header records are already deleted.

Body:
I have a situation where I have a Header and a Detail table. The Detail table has a foreign key relationship to the Header table with Cascade delete.

When the detail records are deleted I need to update other tables using a trigger. The problem I am having is that I need to pull some information from the Header table as well as the Detail table for the deleted records. If I delete the Detail records and then the Header record the trigger appears to run fine. However, if I delete the Header record, which in turn deletes the Detail records due to the cascading delete, then when the trigger executes the Header record is already deleted and I can't access the information I need from it.

I am rather new to triggers, so I'm wondering if there is something I just don't know and how I accomplish this.

Here is my code:

ALTER TRIGGER [Detail_Delete]
   ON [Detail]
   AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- Here is where the problem lies.
 -- No records are found here because the Header record isn't found.
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, h.UserID
 FROM deleted d
 JOIN Header h ON h.HeaderID = d.HeaderID

 EXECUTE sp_UpdateSummary
  @Table = @Table
END


问:
Selecting one row based on the values in a group
Novice SQL coder here. My data looks like this:

```<code>Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported
</code>```

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

```<code>Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported
</code>```

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

答:
Something like

```<code>Select
   t.[case],
   case when existSupported.case is not null then “Supported” else “Not Supported”
 From table1 t
    Left join (select distinct [case] from table1 where result = ‘Supported’) existsSupported
  on t.case = existsSupported.case
</code>```

Should get you there

Body:
Novice SQL coder here. My data looks like this:

Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

Body:
Something like

Select
   t.[case],
   case when existSupported.case is not null then “Supported” else “Not Supported”
 From table1 t
    Left join (select distinct [case] from table1 where result = ‘Supported’) existsSupported
  on t.case = existsSupported.case

Should get you there


问:
pycharm debug console unreadable because of teamcity
Since a few days my pycharm debug console is systematically polluted by teamcity infos, e.g. when i want to print out a variable value, the following will be displayed:

```<code>>>> df
##teamcity[testStdOut timestamp='2017-11-02T15:55:00.670' flowId='test_pricing_36_weight_provider.TestPricing36WeightProvider.test_add_weights' locati...
</code>```

Any hint how to deactivate this teamcity thing ?

答:
Any chance you've installed a teamcity test runner or debugger of some kind in your pip requirements? The ##teamcity bit is a service message used to report output to a TeamCity build log.

Check this for more info about TC service messages: https://confluence.jetbrains.com/display/TCD9/Build+Script+Interaction+with+TeamCity

Body:
Since a few days my pycharm debug console is systematically polluted by teamcity infos, e.g. when i want to print out a variable value, the following will be displayed:

>>> df
##teamcity[testStdOut timestamp='2017-11-02T15:55:00.670' flowId='test_pricing_36_weight_provider.TestPricing36WeightProvider.test_add_weights' locati...

Any hint how to deactivate this teamcity thing ?


问:
ConflictingBeanDefinitionException after refactoring Intellij
I am encountering a ConflictingBeanDefiitionException saying org.company.app.core.controller.web.EquipmentController conflicts with org.company.app.core.controller.EquipmentController. The only problem is there is no org.company.app.core.controller.EquipmentController. It used to be there, I moved it to the package org.company.app.core.controller.web.

I don't understand why this is happening. Is this a weird Intellij thing or what?

```<code>Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'equipmentController' for bean class [org.company.app.core.controller.web.EquipmentController] conflicts with existing, non-compatible bean definition of same name and class [org.company.app.core.controller.EquipmentController]
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:320)
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:259)
    at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:140)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:262)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:226)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:480)
    ... 59 more
</code>```

答:
```<code>mvn clean package
</code>```

Worked for me  . It attempts to clean the files and directories generated by Maven during its old build.

Body:
I am encountering a ConflictingBeanDefiitionException saying org.company.app.core.controller.web.EquipmentController conflicts with org.company.app.core.controller.EquipmentController. The only problem is there is no org.company.app.core.controller.EquipmentController. It used to be there, I moved it to the package org.company.app.core.controller.web.

I don't understand why this is happening. Is this a weird Intellij thing or what?

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'equipmentController' for bean class [org.company.app.core.controller.web.EquipmentController] conflicts with existing, non-compatible bean definition of same name and class [org.company.app.core.controller.EquipmentController]
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:320)
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:259)
    at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:140)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:262)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:226)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:480)
    ... 59 more

Body:
mvn clean package

Worked for me  . It attempts to clean the files and directories generated by Maven during its old build.


问:
Changing game engine after releasing an ios gaming app
I have been developing my gaming app using game salad engine, after releasing my app i decided to change to unity for several reasons, is it possible to change the game build after releasing with a totally new build using a new engine?
and does this affect Non-Consumable in app purchases that people already did?

答:
You certainly can. just rebuild the game in unity, and I mean create it again.

For non-consumables iaps, you will have to make a Restore Purchases button, which is easy in Unity.

This is a tutorial for IAPs on Unity.


问:
How to add all strings in a file to a set?
Hello all (this is for python 2.7.12)

I'm trying to use a file that has 300,000 or so words in it, one per line, and add them all to a set inside my __init__ method for my class. This is what I have so far.

I am not able to use the function it is returning errors for when I use anything but a string as a parameter. What am I doing wrong?

I want the set to have nothing but each word such as 'cat', 'car', 'dog', etc. inside of the set.

```<code>    def __init__(self,words):  # accepts a file of strings and puts them into a list
        self.language = set()
        for w in words:
            words.open()
            w.strip('\n')
            self.language.add(w)
        print self.language
</code>```

答:
If you have a file called data.txt you can read in the file into a list of words, strip out the new-line character and create a set from the list:

```<code>with open('data.txt') as f:
    raw = f.readlines()
words = [i.strip() for i in raw]
wordSet = set(words)
</code>```

If you want to make a class you could define it as something like:

```<code>class listOfWords(object):
    """docstring for listOfWords."""
    def __init__(self, wordFile):
        self.wordFile = wordFile
        self.wordSet = self.readfile()

    def readfile(self):
        with open(self.wordFile) as f:
            wordSet = {line.rstrip() for line in f}
        return wordSet
</code>```

Then create an object with:

```<code>wordObject = listOfWords('data.txt')
</code>```

When you want to access the set of words you would call:

```<code>wordObject.wordSet
</code>```

Body:
Hello all (this is for python 2.7.12)

I'm trying to use a file that has 300,000 or so words in it, one per line, and add them all to a set inside my __init__ method for my class. This is what I have so far.

I am not able to use the function it is returning errors for when I use anything but a string as a parameter. What am I doing wrong?

I want the set to have nothing but each word such as 'cat', 'car', 'dog', etc. inside of the set.

    def __init__(self,words):  # accepts a file of strings and puts them into a list
        self.language = set()
        for w in words:
            words.open()
            w.strip('\n')
            self.language.add(w)
        print self.language

Body:
If you have a file called data.txt you can read in the file into a list of words, strip out the new-line character and create a set from the list:

with open('data.txt') as f:
    raw = f.readlines()
words = [i.strip() for i in raw]
wordSet = set(words)

If you want to make a class you could define it as something like:

class listOfWords(object):
    """docstring for listOfWords."""
    def __init__(self, wordFile):
        self.wordFile = wordFile
        self.wordSet = self.readfile()

    def readfile(self):
        with open(self.wordFile) as f:
            wordSet = {line.rstrip() for line in f}
        return wordSet

Then create an object with:

wordObject = listOfWords('data.txt')

When you want to access the set of words you would call:

wordObject.wordSet


问:
Keyframe Animation not working on iPhone
So I have an animation I'm trying to play on my website: http://eayusi.design

It doesn't seem to be working on my iPhone, regardless of whatever browser I use.  I've added the -webkit- before the animation as suggested by other answers but that doesn't seem to be working. I would appreciate any help I can get guys. I am currently using an iPhone 6 on the latest iOS.

```<code>  html
  {
    font-size: 62.5%;
  }

  body
  {
    margin: 0;
    padding: 0;
    font-size: 1.6rem;
    background: black;
    text-align: center;
    letter-spacing: 20px;
    font-family: 'Raleway', sans-serif;
    font-weight: 900;
  }

  .glitch
  {
    position:relative;
    top: 40%;
    color: white;
  }

  .glitch:before, .glitch:after{
    content: 'Coming soon';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:black;
  }

  .glitch:before{
    left: 4px;
    text-shadow: 2px 0 #00ffea;
    animation: effect 3s infinite linear;
    -webkit-animation: effect 3s infinite linear;
    clip: rect(45px, 9999px, 38px, 0);
  }

  .glitch:after{
    left: -2px;
    text-shadow: -2px 0 tomato;
    animation: effect 2s infinite linear;
    -webkit-animation: effect 2s infinite linear;
  }

  @keyframes effect {
      0% {
        clip: rect(42px, 9999px, 44px, 0);
      }
      5% {
        clip: rect(12px, 9999px, 59px, 0);
      }
      10% {
        clip: rect(48px, 9999px, 29px, 0);
      }
      15.0% {
        clip: rect(42px, 9999px, 73px, 0);
      }
      20% {
        clip: rect(63px, 9999px, 27px, 0);
      }
      25% {
        clip: rect(34px, 9999px, 55px, 0);
      }
      30.0% {
        clip: rect(86px, 9999px, 73px, 0);
      }
      35% {
        clip: rect(20px, 9999px, 20px, 0);
      }
      40% {
        clip: rect(26px, 9999px, 60px, 0);
      }
      45% {
        clip: rect(25px, 9999px, 66px, 0);
      }
      50% {
        clip: rect(57px, 9999px, 98px, 0);
      }
      55.0% {
        clip: rect(5px, 9999px, 46px, 0);
      }
      60.0% {
        clip: rect(82px, 9999px, 31px, 0);
      }
      65% {
        clip: rect(54px, 9999px, 27px, 0);
      }
      70% {
        clip: rect(28px, 9999px, 99px, 0);
      }
      75% {
        clip: rect(45px, 9999px, 69px, 0);
      }
      80% {
        clip: rect(23px, 9999px, 85px, 0);
      }
      85.0% {
        clip: rect(54px, 9999px, 84px, 0);
      }
      90% {
        clip: rect(45px, 9999px, 47px, 0);
      }
      95% {
        clip: rect(37px, 9999px, 20px, 0);
      }
      100% {
        clip: rect(4px, 9999px, 91px, 0);
      }
    }

    @-webkit-keyframes effect {
        0% {
          clip: rect(42px, 9999px, 44px, 0);
        }
        5% {
          clip: rect(12px, 9999px, 59px, 0);
        }
        10% {
          clip: rect(48px, 9999px, 29px, 0);
        }
        15.0% {
          clip: rect(42px, 9999px, 73px, 0);
        }
        20% {
          clip: rect(63px, 9999px, 27px, 0);
        }
        25% {
          clip: rect(34px, 9999px, 55px, 0);
        }
        30.0% {
          clip: rect(86px, 9999px, 73px, 0);
        }
        35% {
          clip: rect(20px, 9999px, 20px, 0);
        }
        40% {
          clip: rect(26px, 9999px, 60px, 0);
        }
        45% {
          clip: rect(25px, 9999px, 66px, 0);
        }
        50% {
          clip: rect(57px, 9999px, 98px, 0);
        }
        55.0% {
          clip: rect(5px, 9999px, 46px, 0);
        }
        60.0% {
          clip: rect(82px, 9999px, 31px, 0);
        }
        65% {
          clip: rect(54px, 9999px, 27px, 0);
        }
        70% {
          clip: rect(28px, 9999px, 99px, 0);
        }
        75% {
          clip: rect(45px, 9999px, 69px, 0);
        }
        80% {
          clip: rect(23px, 9999px, 85px, 0);
        }
        85.0% {
          clip: rect(54px, 9999px, 84px, 0);
        }
        90% {
          clip: rect(45px, 9999px, 47px, 0);
        }
        95% {
          clip: rect(37px, 9999px, 20px, 0);
        }
        100% {
          clip: rect(4px, 9999px, 91px, 0);
        }
      }
  </style>
</head>
<body>
  <h1 class="glitch">Coming soon</h1>
</body>
</html>
</code>```

答:
I was able to get it working on mobile by including:

```<code>.glitch:before, .glitch:after {
    clip: rect(0,0,0,0);
}
</code>```

Here is a Codepen that demonstrates it working on mobile. I made a couple other changes that are still in the Codepen, but this was the change that made it work correctly.

I was tinkering with your code based on another post from CSS-Tricks where they got it working through SASS. To be completely honest, I'm not sure why it works since I don't have a ton of experience with clipping or masks, but it does.

Edit: Also note that the clip property has been depreciated. So it may be worth finding a replacement implementation that uses clip-path on elements inside of SVGs. I'll see if I can get an example created when I find some extra free time.

Body:
So I have an animation I'm trying to play on my website: http://eayusi.design

It doesn't seem to be working on my iPhone, regardless of whatever browser I use.  I've added the -webkit- before the animation as suggested by other answers but that doesn't seem to be working. I would appreciate any help I can get guys. I am currently using an iPhone 6 on the latest iOS.

  html
  {
    font-size: 62.5%;
  }

  body
  {
    margin: 0;
    padding: 0;
    font-size: 1.6rem;
    background: black;
    text-align: center;
    letter-spacing: 20px;
    font-family: 'Raleway', sans-serif;
    font-weight: 900;
  }

  .glitch
  {
    position:relative;
    top: 40%;
    color: white;
  }

  .glitch:before, .glitch:after{
    content: 'Coming soon';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:black;
  }

  .glitch:before{
    left: 4px;
    text-shadow: 2px 0 #00ffea;
    animation: effect 3s infinite linear;
    -webkit-animation: effect 3s infinite linear;
    clip: rect(45px, 9999px, 38px, 0);
  }

  .glitch:after{
    left: -2px;
    text-shadow: -2px 0 tomato;
    animation: effect 2s infinite linear;
    -webkit-animation: effect 2s infinite linear;
  }

  @keyframes effect {
      0% {
        clip: rect(42px, 9999px, 44px, 0);
      }
      5% {
        clip: rect(12px, 9999px, 59px, 0);
      }
      10% {
        clip: rect(48px, 9999px, 29px, 0);
      }
      15.0% {
        clip: rect(42px, 9999px, 73px, 0);
      }
      20% {
        clip: rect(63px, 9999px, 27px, 0);
      }
      25% {
        clip: rect(34px, 9999px, 55px, 0);
      }
      30.0% {
        clip: rect(86px, 9999px, 73px, 0);
      }
      35% {
        clip: rect(20px, 9999px, 20px, 0);
      }
      40% {
        clip: rect(26px, 9999px, 60px, 0);
      }
      45% {
        clip: rect(25px, 9999px, 66px, 0);
      }
      50% {
        clip: rect(57px, 9999px, 98px, 0);
      }
      55.0% {
        clip: rect(5px, 9999px, 46px, 0);
      }
      60.0% {
        clip: rect(82px, 9999px, 31px, 0);
      }
      65% {
        clip: rect(54px, 9999px, 27px, 0);
      }
      70% {
        clip: rect(28px, 9999px, 99px, 0);
      }
      75% {
        clip: rect(45px, 9999px, 69px, 0);
      }
      80% {
        clip: rect(23px, 9999px, 85px, 0);
      }
      85.0% {
        clip: rect(54px, 9999px, 84px, 0);
      }
      90% {
        clip: rect(45px, 9999px, 47px, 0);
      }
      95% {
        clip: rect(37px, 9999px, 20px, 0);
      }
      100% {
        clip: rect(4px, 9999px, 91px, 0);
      }
    }

    @-webkit-keyframes effect {
        0% {
          clip: rect(42px, 9999px, 44px, 0);
        }
        5% {
          clip: rect(12px, 9999px, 59px, 0);
        }
        10% {
          clip: rect(48px, 9999px, 29px, 0);
        }
        15.0% {
          clip: rect(42px, 9999px, 73px, 0);
        }
        20% {
          clip: rect(63px, 9999px, 27px, 0);
        }
        25% {
          clip: rect(34px, 9999px, 55px, 0);
        }
        30.0% {
          clip: rect(86px, 9999px, 73px, 0);
        }
        35% {
          clip: rect(20px, 9999px, 20px, 0);
        }
        40% {
          clip: rect(26px, 9999px, 60px, 0);
        }
        45% {
          clip: rect(25px, 9999px, 66px, 0);
        }
        50% {
          clip: rect(57px, 9999px, 98px, 0);
        }
        55.0% {
          clip: rect(5px, 9999px, 46px, 0);
        }
        60.0% {
          clip: rect(82px, 9999px, 31px, 0);
        }
        65% {
          clip: rect(54px, 9999px, 27px, 0);
        }
        70% {
          clip: rect(28px, 9999px, 99px, 0);
        }
        75% {
          clip: rect(45px, 9999px, 69px, 0);
        }
        80% {
          clip: rect(23px, 9999px, 85px, 0);
        }
        85.0% {
          clip: rect(54px, 9999px, 84px, 0);
        }
        90% {
          clip: rect(45px, 9999px, 47px, 0);
        }
        95% {
          clip: rect(37px, 9999px, 20px, 0);
        }
        100% {
          clip: rect(4px, 9999px, 91px, 0);
        }
      }
  </style>

Coming soon

Body:
I was able to get it working on mobile by including:

.glitch:before, .glitch:after {
    clip: rect(0,0,0,0);
}

Here is a Codepen that demonstrates it working on mobile. I made a couple other changes that are still in the Codepen, but this was the change that made it work correctly.

I was tinkering with your code based on another post from CSS-Tricks where they got it working through SASS. To be completely honest, I'm not sure why it works since I don't have a ton of experience with clipping or masks, but it does.

Edit: Also note that the clip property has been depreciated. So it may be worth finding a replacement implementation that uses clip-path on elements inside of SVGs. I'll see if I can get an example created when I find some extra free time.


问:
Accessing Python instance variables with __dict__- Is it wrong?
If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys().  I want to use this attribute to print out all instance variables of an object.  I am hesitant to do this because __dict__ is a "secret" attribute, and I do not understand what this footnote means.

So is it wrong to use myObject.__dict__?

答: That footnote is in reference to the __dict__ attribute of a module. The __dict__ attribute of an object carries no such warning (documentation).


问:
how to translate list from a file?
```<code>fo=open("sample.txt","r")
item=fo.readlines()
fo.close()

replacements = (('4','A'),('8','b'),('3','e'),('5','s'),('7','t'),('@','a'),('3','e'),('0','o'))
new_string = item
for new, old in replacements:
new_string = new_string.replace(new, old)

print ( new_string)
</code>```

I have written the following code but does not read my list. My goal is translate the list.

答:
Use str.translate() to use a translation table for faster translation.  Here is an example:

```<code>with open("sample.txt","r") as fo:
    lines = fo.readlines()

replacements = {'4':'A', '8':'b', '3':'e', '5':'s', '7':'t', '@':'a', '3':'e', '0':'o'}
trans_table = str.maketrans(replacements)
for line in lines:
    print(line, end="")
    new_line = line.translate(trans_table)
    print(new_line)
</code>```

OUTPUT:

```<code>h3llo 70 y0u
hello to you

4 8377er w0rld 70d@y
A better world today
</code>```

Title: how to translate list from a file?

Body:
fo=open("sample.txt","r")
item=fo.readlines()
fo.close()

replacements = (('4','A'),('8','b'),('3','e'),('5','s'),('7','t'),('@','a'),('3','e'),('0','o'))
new_string = item
for new, old in replacements:
new_string = new_string.replace(new, old)

print ( new_string)

I have written the following code but does not read my list. My goal is translate the list.

Body:
Use str.translate() to use a translation table for faster translation.  Here is an example:

with open("sample.txt","r") as fo:
    lines = fo.readlines()

replacements = {'4':'A', '8':'b', '3':'e', '5':'s', '7':'t', '@':'a', '3':'e', '0':'o'}
trans_table = str.maketrans(replacements)
for line in lines:
    print(line, end="")
    new_line = line.translate(trans_table)
    print(new_line)

OUTPUT:

h3llo 70 y0u
hello to you

4 8377er w0rld 70d@y
A better world today


问:
Linker command failed with exit code 1 - duplicate symbol __TMRbBp
Since I've updated to Xcode 8.1 I can't archive and also not run in Release mode (in debug mode its working). The error is that there are several "duplicate symbols for architecture arm64" and all are "duplicate symbol __TMRbBp". Whats that?</p>

答:
Don't double click Project.xcodeproj to start your xcode project.  Instead, close your project and open the xcworkspace.

```<code>File -> Close Workspace

File -> Open -> Search your project folder for Project.xcworkspace
</code>```

All my errors are gone.

ContentLicense: CC BY-SA 4.0

Body:
Don't double click Project.xcodeproj to start your xcode project.  Instead, close your project and open the xcworkspace.

File -> Close Workspace

File -> Open -> Search your project folder for Project.xcworkspace

All my errors are gone.


问:
Automatically adjust the phone number format in a form
I want to make a form element for entering phone number where it automatically adjusts the phone number format.

I didn't like the idea to put an external link showing the actual form.
So, here is my effort for animation from words.

The end result I want is this format.

```<code>(519) 111-1111
</code>```

First three area code, followed by a space, region code three number, and a dash and a four number

So, once the user starts typing the first number, it automatically becomes like

```<code>(5
</code>```

When three number

```<code>(519
</code>```

As soon as the fourth number

```<code>(519) 1
</code>```

Space and a completed bracket

As soon three number more, automatic dash

```<code>(519) 111-1
</code>```

And last three numbers

```<code>(519) 111-1111
</code>```

Just like that.

I am a newbie, and I have NO idea, how to do this, I am pretty sure we need jquery and javascript stuff here.

Any tips / suggestions / help would be really appreciated.

答:
You mentioned jQuery, you can have a look at https://igorescobar.github.io/jQuery-Mask-Plugin/

They have one example that does exactly what you are asking for ("US Telephone")

Body:
I want to make a form element for entering phone number where it automatically adjusts the phone number format.

I didn't like the idea to put an external link showing the actual form.
So, here is my effort for animation from words.

The end result I want is this format.

(519) 111-1111

First three area code, followed by a space, region code three number, and a dash and a four number

So, once the user starts typing the first number, it automatically becomes like

(5

When three number

(519

As soon as the fourth number

(519) 1

Space and a completed bracket

As soon three number more, automatic dash

(519) 111-1

And last three numbers

(519) 111-1111

Just like that.

I am a newbie, and I have NO idea, how to do this, I am pretty sure we need jquery and javascript stuff here.

Any tips / suggestions / help would be really appreciated.


问:
Swift Triggering Segue upon special if else conditions
I've followed documentation briefly and this is what I have so far:

ViewController.swift

```<code> let x = "Registered!";
 let y =  jsonData.value(forKey: "results") as! String?;
 let isEqual = (x == y)
 print(isEqual) // Gives me true or false works as expected
 if(isEqual==true){
  self.performSegue(withIdentifier:"Test", sender: self);

}
</code>```

I'm trying to see if a condition is true; then execute the Segue.

I've created Segue in my storyboard like this.

I have two View Controller.

First View and Second View.
I then pressed cntrl and dragged the button from first view to second view creating a Segue.
I then gave my Segue a unique identifier "Test"

However; I want to only execute the new view only if the statement is true or else void it and throw an error message; however my segue seems to be working; it redirects to my second page weather the condition is true or not.

I also made sure; that my second view has a class and it's been set-up properly. No idea; why it keeps redirecting user to another view regardless of the statement. What could I have possibly done wrong?

答: The thing is that your segue is from Button to ViewController. You should drag and drop the segue with same identifier from ViewController to ViewController. Not from Button to ViewController  </p>

Body:
I've followed documentation briefly and this is what I have so far:

ViewController.swift

 let x = "Registered!";
 let y =  jsonData.value(forKey: "results") as! String?;
 let isEqual = (x == y)
 print(isEqual) // Gives me true or false works as expected
 if(isEqual==true){
  self.performSegue(withIdentifier:"Test", sender: self);

}

I'm trying to see if a condition is true; then execute the Segue.

I've created Segue in my storyboard like this.

I have two View Controller.

First View and Second View.
I then pressed cntrl and dragged the button from first view to second view creating a Segue.
I then gave my Segue a unique identifier "Test"

However; I want to only execute the new view only if the statement is true or else void it and throw an error message; however my segue seems to be working; it redirects to my second page weather the condition is true or not.

I also made sure; that my second view has a class and it's been set-up properly. No idea; why it keeps redirecting user to another view regardless of the statement. What could I have possibly done wrong?


问:
How to replace two user id columns with names?
I have a table with two columns.

created_by | assigned_to

One is the person who create a "to do card", the other column is the person who is assigned to do it.

The columns are filled with id, for example; (1,2,3).

My question is how can i replace this id with the names that are saved in another table.

by far this is what i got.

```<code>SELECT tickets.*, users.Name, users.LastName
FROM tickets
LEFT JOIN users ON tickets.assigned_to = users.uid
AND tickets.id_usuario = users.uid
</code>```

but when i try to print the name of the persona

Created by: <?= query['Name']; ?>

Assigned to: <?= query['Name']; ?>

but i got the same name in both columns.

答:
Your current query only joins to users when the creator and assigned-to user ID are the same.

You'll need to join to your users table twice to retrieve the separate records. You do this by adding more joins...

```<code>SELECT
  c_users.Name as created_by_name,
  c_users.LastName as created_by_last_name,
  a_users.Name as assigned_to_name,
  a_users.LastName as assigned_to_last_name
FROM tickets t
INNER JOIN users c_users
  ON t.created_by = c_users.uid
  -- or t.id_usuario = c_users.uid, it is not clear from your question
INNER JOIN users a_users
  ON t.assigned_to = a_users.uid
</code>```

I've used INNER JOIN instead of LEFT JOIN as it doesn't seem feasible that you'd have broken relationships between the two tables.

Body:
I have a table with two columns.

created_by | assigned_to

One is the person who create a "to do card", the other column is the person who is assigned to do it.

The columns are filled with id, for example; (1,2,3).

My question is how can i replace this id with the names that are saved in another table.

by far this is what i got.

SELECT tickets.*, users.Name, users.LastName
FROM tickets
LEFT JOIN users ON tickets.assigned_to = users.uid
AND tickets.id_usuario = users.uid

but when i try to print the name of the persona

Created by: <?= query['Name']; ?>

Assigned to: <?= query['Name']; ?>

but i got the same name in both columns.

Body:
Your current query only joins to users when the creator and assigned-to user ID are the same.

You'll need to join to your users table twice to retrieve the separate records. You do this by adding more joins...

SELECT
  c_users.Name as created_by_name,
  c_users.LastName as created_by_last_name,
  a_users.Name as assigned_to_name,
  a_users.LastName as assigned_to_last_name
FROM tickets t
INNER JOIN users c_users
  ON t.created_by = c_users.uid
  -- or t.id_usuario = c_users.uid, it is not clear from your question
INNER JOIN users a_users
  ON t.assigned_to = a_users.uid

I've used INNER JOIN instead of LEFT JOIN as it doesn't seem feasible that you'd have broken relationships between the two tables.


问:
How would you tidy up this controller logic?
I've got some logic in a controller that sets a status of an object if certain conditions are met:

```<code>if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

答:
This is my take on it. I call it Super DRY.

```<code>statuses =
  [
    ['Awaiting Marketing & Legal Approval','Awaiting Compliance Approval'],
    ['Awaiting Marketing Approval','Pending Approval']
  ]

{:status => statuses[params[:concept][:consulted_legal].to_i][params[:concept][:consulted_marketing].to_i]}
</code>```

Alternatively, a more conventional approach -- lengthy but readable:

```<code>status = if params[:concept][:consulted_legal] == "0"
  if params[:concept][:consulted_marketing] == "1"
    'Awaiting Compliance Approval'
  else
    'Awaiting Marketing & Legal Approval'
  end
else
  if params[:concept][:consulted_marketing] == "0"
    'Awaiting Marketing Approval'
  else
    'Pending Approval'
  end
end

@concept.attributes = {:status => status}
</code>```

Note: It looks like your original code is checking values of check boxes. Values in the params hash are always Strings, not Fixnums so my code compares strings. If for some reason comparing Fixnums is what is required for your situation, just take out the quotes around the numbers.

OwnerDisplayName: The Pied Pipes

Body:
I've got some logic in a controller that sets a status of an object if certain conditions are met:

if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

Body:
This is my take on it. I call it Super DRY.

statuses =
  [
    ['Awaiting Marketing & Legal Approval','Awaiting Compliance Approval'],
    ['Awaiting Marketing Approval','Pending Approval']
  ]

{:status => statuses[params[:concept][:consulted_legal].to_i][params[:concept][:consulted_marketing].to_i]}

Alternatively, a more conventional approach -- lengthy but readable:

status = if params[:concept][:consulted_legal] == "0"
  if params[:concept][:consulted_marketing] == "1"
    'Awaiting Compliance Approval'
  else
    'Awaiting Marketing & Legal Approval'
  end
else
  if params[:concept][:consulted_marketing] == "0"
    'Awaiting Marketing Approval'
  else
    'Pending Approval'
  end
end

@concept.attributes = {:status => status}

Note: It looks like your original code is checking values of check boxes. Values in the params hash are always Strings, not Fixnums so my code compares strings. If for some reason comparing Fixnums is what is required for your situation, just take out the quotes around the numbers.

OwnerDisplayName: bjeanes

LastEditorDisplayName: bjeanes


问:
Custom ASP.NET MVC2 HtmlHelper: How to get the instance of the object passed to it?
I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.

In a view I would like to do this:

```<code> <%: Html.EditorForEnumeracion(Function(v) v.combustible%>
</code>```

So, I created an HtmlHelper extension method:

```<code>Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection

Public Module HtmlHelpers
    <Extension()> _
    Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
        'My stuff goes here
     End Function
End Module
</code>```

The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.

Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.

I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.

More info now.

This is my "Vehiculo" class:

```<code>Namespace Models.Automovil
    Public Class Vehiculo
        Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
        Public Property marca As String
        Public Property modelo As String
        Public Property numeroDePuertas As Integer
        Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
        Public Property potencia As Integer
        Public Property fechaPrimeraMatriculacion As DateTime
        Public Property version As String
        Public Property precio As Decimal
        Public Property descripcion As String
    End Class
End Namespace
</code>```

And this is my "Enumeracion" class:

```<code>Namespace Models
    Public Class Enumeracion
        Private bd As New tarificadorasegasaEntities
        Private diccionario As New Dictionary(Of String, Integer)
        Private _nombre As String
        Private _clave As String
        Private _valor As Integer
        Public ReadOnly Property nombre As String
            Get
                Return _nombre
            End Get
        End Property
        Public ReadOnly Property clave As String
            Get
                Return _clave
            End Get
        End Property
        Public ReadOnly Property valor As Integer
            Get
                Return _valor
            End Get
        End Property

        'More stuff here. Methods.

    End Class
End Namespace
</code>```

The model is the Vehiculo class.

Still not resolving this.

Thanks in advance.

答:
You need to compile the expression into a Func(Of TModel, TValue), then call it on the model:

```<code>Dim func = expression.Compile()
Dim value = func(html.ViewData.Model)
</code>```

Body:
I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.

In a view I would like to do this:

 <%: Html.EditorForEnumeracion(Function(v) v.combustible%>

So, I created an HtmlHelper extension method:

Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection

Public Module HtmlHelpers
    <Extension()> _
    Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
        'My stuff goes here
     End Function
End Module

The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.

Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.

I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.

More info now.

This is my "Vehiculo" class:

Namespace Models.Automovil
    Public Class Vehiculo
        Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
        Public Property marca As String
        Public Property modelo As String
        Public Property numeroDePuertas As Integer
        Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
        Public Property potencia As Integer
        Public Property fechaPrimeraMatriculacion As DateTime
        Public Property version As String
        Public Property precio As Decimal
        Public Property descripcion As String
    End Class
End Namespace

And this is my "Enumeracion" class:

Namespace Models
    Public Class Enumeracion
        Private bd As New tarificadorasegasaEntities
        Private diccionario As New Dictionary(Of String, Integer)
        Private _nombre As String
        Private _clave As String
        Private _valor As Integer
        Public ReadOnly Property nombre As String
            Get
                Return _nombre
            End Get
        End Property
        Public ReadOnly Property clave As String
            Get
                Return _clave
            End Get
        End Property
        Public ReadOnly Property valor As Integer
            Get
                Return _valor
            End Get
        End Property

        'More stuff here. Methods.

    End Class
End Namespace

The model is the Vehiculo class.

Still not resolving this.

Thanks in advance.

Body:
You need to compile the expression into a Func(Of TModel, TValue), then call it on the model:

Dim func = expression.Compile()
Dim value = func(html.ViewData.Model)


问:
asp.net postbacks won't fire
I've made a simple ASP.net website and everything works fine on my computer. But on my colleague's computer no postbacks are fired although he uses the same OS (Win 7) AND the same browser as I do (IE9).

I don't have any access to his computer right now which makes it kind of hard to debug. Does anybody know what could prevent postbacks on one computer although they work on a different one with the same browser?
(I also tried it on a 3rd computer with different browser and OS and it worked there too)

//update: some code

The following code is one of the pages where the problem occures.

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NewList.aspx.cs" Inherits="QAList.NewList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Items</title>

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

    <link href="qalist.css" rel="stylesheet" type="text/css" />

    <script src="lib/jquery-1.4.3.min.js" type="text/javascript"></script>
    <script src="lib/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />

    <style type="text/css">

        input[disabled]
        {
            background-color:#888888;
        }

        .Filled
        {
            width: 98%;
        }

        .Property
        {            margin-bottom: 0px;
        }

       .Date
        {
            /* this class is only used to indicate that the value is a DateTime value */
        }

        .PropertyTable td
        {
            border-bottom: 1px solid #D8D8D8;
            padding:1px;
            background-color:#F6F6F6;
        }

        .Suppler_style
        {
            color: #0000BB;
        }

    </style>

    <script type="text/javascript">

        $(function () {
            $(".Date").datepicker({ dateFormat: "yy/mm/dd" });
        });

    </script>

</head>
<body>

    <form id="form1" runat="server">

    <table style="width: 80%;" border="0" class="PropertyTable" cellspacing="0" cellpadding="0">
    <tr>
        <td style="width: 227px;">
            Project Number</td>
        <td>
            <asp:TextBox ID="ProjectNumber" runat="server" CssClass="Property" Width="200px"></asp:TextBox>
          <asp:Button ID="btApplyPnr" runat="server" Text="  apply  "
                onclick="btApplyPnr_Click" />
        </td>
    </tr>
    <tr>
        <td>
            Contract No.</td>
        <td>
            <asp:DropDownList ID="ddContractNo" runat="server" AutoPostBack="True"
                onselectedindexchanged="ContractNo_SelectedIndexChanged"
                CssClass="Filled">
            </asp:DropDownList>
            <input type="hidden" class="Property" id="V_QA_PO_tp_listId" runat="server" />
            <input type="hidden" class="Property" id="V_QA_PO_tp_ID" runat="server" />
            <input type="hidden" class="Property" id="ContractNo" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            ITP No</td>
        <td>
            <asp:TextBox ID="ITPNo" runat="server" CssClass="Filled Property"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td class="Suppler_style">
            ITP Name</td>
        <td>
            <asp:TextBox ID="ITPName" runat="server" CssClass="Filled Property"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td class="Suppler_style">
            Status Delivery/Finish Date</td>
        <td>
            <asp:TextBox ID="StatusDeliveryFinishDate" runat="server"
                CssClass="Filled Property Date"></asp:TextBox>
        </td>
    </tr>
    </table>

    </form>

</body>
</html>
</code>```

And the C#-Code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace QAList
{
    public partial class NewList : System.Web.UI.Page
    {

        private string current_contract = "0";
        private string current_pnr;

        protected void Page_Load(object sender, EventArgs e)
        {
            current_contract = ddContractNo.SelectedValue;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            //load Contract Numbers
            ddContractNo.Items.Clear();
            ddContractNo.Items.Add(new ListItem("-", "0"));
            foreach (DataRow contract in DBAccess.Instance.getContractNumbers(current_pnr).Rows)
            {
                ddContractNo.Items.Add(new ListItem(contract["ProjectNumber"] + " - " + contract["ContractNo"] + " - " + contract["GoodsServicesSupplied"], contract["tp_listId"] + "_" + contract["tp_ID"]));
            }
            try
            {
                ddContractNo.SelectedValue = current_contract;
            }
            catch (ArgumentOutOfRangeException)
            {
                ddContractNo.SelectedValue = null;
                applyNewContractValue();
            }
        }

        protected void ContractNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            applyNewContractValue();
        }

        private void applyNewContractValue()
        {
            current_contract = ddContractNo.SelectedValue;
            if (!String.IsNullOrEmpty(current_contract) && current_contract != "0")
            {
                Guid tp_listId = new Guid(current_contract.Split('_')[0]);
                int tp_ID = Convert.ToInt32(current_contract.Split('_')[1]);
                DataRow row = DBAccess.Instance.getContractInfos(tp_listId, tp_ID);
                if (row == null)
                    return;
                ITPName.Text = row.IsNull("GoodsServicesSupplied") ? "" : row["GoodsServicesSupplied"].ToString();
                if (!row.IsNull("PlannedDeliveryexworks"))
                {
                    DateTime tmp = (DateTime)row["PlannedDeliveryexworks"];
                    StatusDeliveryFinishDate.Text = tmp.Year + "/" + fillZeros(tmp.Month, 2) + "/" + fillZeros(tmp.Day, 2);
                }
            }
            else
            {
                ITPName.Text = "";
            }
        }

        private string fillZeros(int nr, int min_length)
        {
            string res = nr.ToString();
            while (res.Length < min_length)
                res = "0" + res;
            return res;
        }

        protected void btApplyPnr_Click(object sender, EventArgs e)
        {
            current_pnr = ProjectNumber.Text;
        }

    }
}
</code>```

答:
In case this helps someone:

I had something similar occur and it turned out that it was due to some validation controls on the page.  They were for some hidden text boxes that were not actually visible and had no validation group specified. On one of the computers the errors were ignored and the postback worked, whereas on the second computer the postback failed due to validation errors.  Because the text boxes were not currently visible, the problem was not immediately obvious.

Once I set up validation groups, the problem went away.  I don't know why the behaviour was different on the two computers as both are running Chrome on Windows 10.

Title: asp.net postbacks won't fire

Body:
I've made a simple ASP.net website and everything works fine on my computer. But on my colleague's computer no postbacks are fired although he uses the same OS (Win 7) AND the same browser as I do (IE9).

I don't have any access to his computer right now which makes it kind of hard to debug. Does anybody know what could prevent postbacks on one computer although they work on a different one with the same browser?
(I also tried it on a 3rd computer with different browser and OS and it worked there too)

//update: some code

The following code is one of the pages where the problem occures.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NewList.aspx.cs" Inherits="QAList.NewList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Items</title>

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

    <link href="qalist.css" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />

    <form id="form1" runat="server">

            Project Number

            <asp:TextBox ID="ProjectNumber" runat="server" CssClass="Property" Width="200px"></asp:TextBox>
          <asp:Button ID="btApplyPnr" runat="server" Text="  apply  "
                onclick="btApplyPnr_Click" />

            Contract No.

            <asp:DropDownList ID="ddContractNo" runat="server" AutoPostBack="True"
                onselectedindexchanged="ContractNo_SelectedIndexChanged"
                CssClass="Filled">
            </asp:DropDownList>
            <input type="hidden" class="Property" id="V_QA_PO_tp_listId" runat="server" />
            <input type="hidden" class="Property" id="V_QA_PO_tp_ID" runat="server" />
            <input type="hidden" class="Property" id="ContractNo" runat="server" />

            ITP No

            <asp:TextBox ID="ITPNo" runat="server" CssClass="Filled Property"></asp:TextBox>

            ITP Name

            <asp:TextBox ID="ITPName" runat="server" CssClass="Filled Property"></asp:TextBox>

            Status Delivery/Finish Date

            <asp:TextBox ID="StatusDeliveryFinishDate" runat="server"
                CssClass="Filled Property Date"></asp:TextBox>

    </form>

And the C#-Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace QAList
{
    public partial class NewList : System.Web.UI.Page
    {

        private string current_contract = "0";
        private string current_pnr;

        protected void Page_Load(object sender, EventArgs e)
        {
            current_contract = ddContractNo.SelectedValue;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            //load Contract Numbers
            ddContractNo.Items.Clear();
            ddContractNo.Items.Add(new ListItem("-", "0"));
            foreach (DataRow contract in DBAccess.Instance.getContractNumbers(current_pnr).Rows)
            {
                ddContractNo.Items.Add(new ListItem(contract["ProjectNumber"] + " - " + contract["ContractNo"] + " - " + contract["GoodsServicesSupplied"], contract["tp_listId"] + "_" + contract["tp_ID"]));
            }
            try
            {
                ddContractNo.SelectedValue = current_contract;
            }
            catch (ArgumentOutOfRangeException)
            {
                ddContractNo.SelectedValue = null;
                applyNewContractValue();
            }
        }

        protected void ContractNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            applyNewContractValue();
        }

        private void applyNewContractValue()
        {
            current_contract = ddContractNo.SelectedValue;
            if (!String.IsNullOrEmpty(current_contract) && current_contract != "0")
            {
                Guid tp_listId = new Guid(current_contract.Split('_')[0]);
                int tp_ID = Convert.ToInt32(current_contract.Split('_')[1]);
                DataRow row = DBAccess.Instance.getContractInfos(tp_listId, tp_ID);
                if (row == null)
                    return;
                ITPName.Text = row.IsNull("GoodsServicesSupplied") ? "" : row["GoodsServicesSupplied"].ToString();
                if (!row.IsNull("PlannedDeliveryexworks"))
                {
                    DateTime tmp = (DateTime)row["PlannedDeliveryexworks"];
                    StatusDeliveryFinishDate.Text = tmp.Year + "/" + fillZeros(tmp.Month, 2) + "/" + fillZeros(tmp.Day, 2);
                }
            }
            else
            {
                ITPName.Text = "";
            }
        }

        private string fillZeros(int nr, int min_length)
        {
            string res = nr.ToString();
            while (res.Length < min_length)
                res = "0" + res;
            return res;
        }

        protected void btApplyPnr_Click(object sender, EventArgs e)
        {
            current_pnr = ProjectNumber.Text;
        }

    }
}


问:
Microservice project structure using Spring boot and Spring Cloud
I am trying to convert a normal monolithic web application into microservices structure using Spring Boot and Spring Cloud. I am actually trying to create Angular 2 front-end application and calls these my developed microservices in the cloud. And I am already started to break the modules into independent process's structure for microservice architecture.

Here my doubt is that, when designing the flow of control and microservice structure architecture, can I use only one single Spring Boot project using different controller for this entire web application back end process?

Somewhere I found that when I am reading develop all microservices using 2 different Spring Boot project. I am new to Spring and Spring Cloud. Is it possible to create all services in single project by using different modules?

答:
Currently I am working on microservices too, according my experience  we have designed microservices  as step below,

Maven

You should create the project with different project. But actually you can separate your project to submodule. So you will be easy to manage your project, the  submodule you can use with other project too.

Build the Jar Library put your local repository. it can save your time, you have just find the same component or your functionality then build the jar file put in your local repository , so every project that use this function call point to download this repository, you don't have to write many project same same.

So finally I would like you to create different springboot project, but just create submodule and build local repository.