问:
Class conforming to Codable protocol fails with encodeWithCoder: unrecognized selector sent to instance
I know that there are several questions similar to this, that tend to all revolve around the class not conforming to the protocol properly, but that should not be the immediate issue here.

The following is a condensed version of the code that is currently giving me this problem:

```<code>enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

final class MyClass: NSCoder {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    override init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyClass: Codable {
    convenience init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}
</code>```

I have created the following class which then attempts to call MyClass with the purpose of writing & reading it to UserDefaults:

```<code>class MyClassController {
    private let myClass: MyClass

    init() {
        self.myClass = MyClass()
        self.myClass.string = "string"
        self.myClass.date = Date()
        self.myClass.binary = .a
    }

    func writeMyClass() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: myClass)
        UserDefaults.standard.set(encodedData, forKey: String(describing: MyClass.self))
    }

    func readMyClass() {
        if let decoded = UserDefaults.standard.object(forKey: String(describing: MyClass.self)) as? Data,
            let myClass = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as? MyClass {
            print("string: \(myClass.string ?? "nil") date: \(myClass.date ?? Date()) binary: \(myClass.binary)")
        }
    }
}
</code>```

As soon as I call the writeMyClass function though, I get this error:

[DemoDecoder.MyClass encodeWithCoder:]: unrecognized selector sent to
  instance #blahblah#

Two things I have also tried:

Adding func encode(with aCoder: NSCoder) to MyClass

Removed all properties from MyClass & CodingKeys and the init/encode functions

答:
This is the working code derived from the answer provided by rmaddy above.

A few highlights:

Convert MyClass to MyStruct

Removed NSCoder inheritance from the object I wished to save

Removed calls to NSKeyedArchiver & NSKeyedUnarchiver

No longer saving to UserDefaults

Relying on JSONEncoder & JSONDecoder to write out struct

Writing to file system now as a Data object

This is the updated struct & enum that I wish to save:

```<code>enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

struct MyStruct {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyStruct: Codable {
    init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}
</code>```

The updated controller class that handles reading & writing the output. In my case, writing out to JSON was fine, so I went with that approach.

```<code>class MyStructController {
    private var myStruct: MyStruct

    init() {
        self.myStruct = MyStruct()
        self.myStruct.string = "string"
        self.myStruct.date = Date()
        self.myStruct.binary = .a
    }

    func writeMyStruct() {
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(myStruct)
            let documentDirectory = try FileManager.default.url(for: .documentDirectory,
                                                                in: .userDomainMask,
                                                                appropriateFor:nil,
                                                                create:false)
            let url = documentDirectory.appendingPathComponent(String(describing: MyStruct.self))
            try data.write(to: url)
        } catch {
            print(error.localizedDescription)
        }
    }

    func readMyStruct() {
        do {
            let documentDirectory = try FileManager.default.url(for: .documentDirectory,
                                                                in: .userDomainMask,
                                                                appropriateFor:nil,
                                                                create:false)
            let url = documentDirectory.appendingPathComponent(String(describing: MyStruct.self))
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let myNewStruct = try decoder.decode(MyStruct.self, from: data)
            print("string: \(myNewStruct.string ?? "nil") date: \(myNewStruct.date ?? Date()) binary: \(myNewStruct.binary)")
        } catch {
            print(error.localizedDescription)
        }
    }
}
</code>```

Body:
I know that there are several questions similar to this, that tend to all revolve around the class not conforming to the protocol properly, but that should not be the immediate issue here.

The following is a condensed version of the code that is currently giving me this problem:

enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

final class MyClass: NSCoder {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    override init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyClass: Codable {
    convenience init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}

I have created the following class which then attempts to call MyClass with the purpose of writing & reading it to UserDefaults:

class MyClassController {
    private let myClass: MyClass

    init() {
        self.myClass = MyClass()
        self.myClass.string = "string"
        self.myClass.date = Date()
        self.myClass.binary = .a
    }

    func writeMyClass() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: myClass)
        UserDefaults.standard.set(encodedData, forKey: String(describing: MyClass.self))
    }

    func readMyClass() {
        if let decoded = UserDefaults.standard.object(forKey: String(describing: MyClass.self)) as? Data,
            let myClass = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as? MyClass {
            print("string: \(myClass.string ?? "nil") date: \(myClass.date ?? Date()) binary: \(myClass.binary)")
        }
    }
}

As soon as I call the writeMyClass function though, I get this error:

[DemoDecoder.MyClass encodeWithCoder:]: unrecognized selector sent to
  instance #blahblah#

Two things I have also tried:

Adding func encode(with aCoder: NSCoder) to MyClass

Removed all properties from MyClass & CodingKeys and the init/encode functions

Body:
This is the working code derived from the answer provided by rmaddy above.

A few highlights:

Convert MyClass to MyStruct

Removed NSCoder inheritance from the object I wished to save

Removed calls to NSKeyedArchiver & NSKeyedUnarchiver

No longer saving to UserDefaults

Relying on JSONEncoder & JSONDecoder to write out struct

Writing to file system now as a Data object

This is the updated struct & enum that I wish to save:

enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

struct MyStruct {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyStruct: Codable {
    init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}

The updated controller class that handles reading & writing the output. In my case, writing out to JSON was fine, so I went with that approach.

class MyStructController {
    private var myStruct: MyStruct

    init() {
        self.myStruct = MyStruct()
        self.myStruct.string = "string"
        self.myStruct.date = Date()
        self.myStruct.binary = .a
    }

    func writeMyStruct() {
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(myStruct)
            let documentDirectory = try FileManager.default.url(for: .documentDirectory,
                                                                in: .userDomainMask,
                                                                appropriateFor:nil,
                                                                create:false)
            let url = documentDirectory.appendingPathComponent(String(describing: MyStruct.self))
            try data.write(to: url)
        } catch {
            print(error.localizedDescription)
        }
    }

    func readMyStruct() {
        do {
            let documentDirectory = try FileManager.default.url(for: .documentDirectory,
                                                                in: .userDomainMask,
                                                                appropriateFor:nil,
                                                                create:false)
            let url = documentDirectory.appendingPathComponent(String(describing: MyStruct.self))
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let myNewStruct = try decoder.decode(MyStruct.self, from: data)
            print("string: \(myNewStruct.string ?? "nil") date: \(myNewStruct.date ?? Date()) binary: \(myNewStruct.binary)")
        } catch {
            print(error.localizedDescription)
        }
    }
}


来源: stackexchange

问:
If statement is not branching correctly
I am a novice at python.  The program was to pass any list into a function and print a string with the words separated with a ',' with the last word separated by a ', and'.  But the If statement does not branch for the last word.  I don't know if putting it in a for loop is breaking it.

```<code>spam = ['apples', 'oranges', 'pears', 'strawberries', 'watermelon']

def comma(x):
    newSpam = x[0]
    del x[0]
    for i in range(len(x)):
        print(type(len(x)))
        if i == (len(x)):
            newSpam = newSpam + ', and ' + [x(i)]
        else:
            newSpam = newSpam + ', '+ x[i]
    print(newSpam)
comma(spam)
</code>```

The output I get is:

```<code>apples, oranges, pears, strawberries, watermelon
</code>```

答: As you've demonstrated in the newSpam = x[0] line, Python is zero-indexed, which means that the first item of the list is index 0 and the last item of the list is one less than the length of the list. Thus, to check if you're at the last item, you need to check if i == (len(x) - 1) rather than if i == len(x).

ContentLicense: CC BY-SA 3.0

Title: If statement is not branching correctly

Body:
I am a novice at python.  The program was to pass any list into a function and print a string with the words separated with a ',' with the last word separated by a ', and'.  But the If statement does not branch for the last word.  I don't know if putting it in a for loop is breaking it.

spam = ['apples', 'oranges', 'pears', 'strawberries', 'watermelon']

def comma(x):
    newSpam = x[0]
    del x[0]
    for i in range(len(x)):
        print(type(len(x)))
        if i == (len(x)):
            newSpam = newSpam + ', and ' + [x(i)]
        else:
            newSpam = newSpam + ', '+ x[i]
    print(newSpam)
comma(spam)

The output I get is:

apples, oranges, pears, strawberries, watermelon


问:
Access file inside folder, matlab mac
I have about 300 files I would like to access and import in Matlab, all these files are inside  300 folders.

The first file lie in the directory users/matt/Documents/folder_1 with the filename line.csv the 2nd file lie in users/matt/Documents/folder_2 with filename line.csv

So I would like to import the data from the 300 line.csv files in Matlab so I can take the average value. Is this possible? I am using mac osx btw.

I know what do with the .csv file, but I have no clue how to access them efficiently.

答:
This should work: All we are doing is generating the string for every file path using sprintf and the loop index i, and then reading the csv file using csvread and storing the data in a cell array.

```<code>for i = 1:300 % Loop 300 times.

    % Full path pointing to the csv file.
    file_path = sprintf('users/matt/Documents/folder_%d/line.csv', i);

    % Read data from csv and store it in a cell array.
    data{i} = csvread(file_path);
end

% Do your computations here.
% ...
</code>```

Remember to replace the 300 by the actual number of folders that you have.

Title: Access file inside folder, matlab mac

Body:
This should work: All we are doing is generating the string for every file path using sprintf and the loop index i, and then reading the csv file using csvread and storing the data in a cell array.

for i = 1:300 % Loop 300 times.

    % Full path pointing to the csv file.
    file_path = sprintf('users/matt/Documents/folder_%d/line.csv', i);

    % Read data from csv and store it in a cell array.
    data{i} = csvread(file_path);
end

% Do your computations here.
% ...

Remember to replace the 300 by the actual number of folders that you have.


问:
Archiving an Asana Project using the API
How can I archive a project using the api?

The api documentation for projects shows that projects have an 'archived' attribute, but when I try to update it, I get a message that it's read only.

答: Unfortunately, there is no way to write to this endpoint in the Asana API. </p>


问:
How to hide the BarButtonItem on the ToolBar?
I have a UIView tha contain a ToolBar,and I add some BarButtonItem on the ToolBar.
Now I want to hide the BarButtonItem in some time ,and display them in some time ,how can  i accomplish it ?? </p>

答:
Change your toolbar.items accordingly.

For example if you had toolbar.items set to [NSArray arrayWithObjects: button1, button2, nil] and you need to hide button1, do toolbar = [NSArray arrayWithObject: button2]

ContentLicense: CC BY-SA 2.5


问:
Returning non-const attribute reference from const function
Is there something wrong with this code?

```<code>// Example program
#include <iostream>
#include <string>
#include <vector>

class A
{
public:
    A( std::vector<int>& ref ) : data(ref) {}

    std::vector<int>& getData() const { return data; }

private:
    std::vector<int>& data;
};

void modifyA( const A& a )
{
    a.getData().push_back(3);
}

int main()
{
    std::vector<int> foo;
    A a(foo);
    modifyA(a);
    std::cout << foo.size() << std::endl;
    std::cout << foo.front() << std::endl;
}
</code>```

It looks good to me, but I'm experiencing undefined behaviour under Android when deploying a much more complex code with similar approach. At some point, a member (a shared_ptr) of the class gets corrupted when the previous member of the class (a std::vector) is modified through such a getter (the shared_ptr becomes NULL, while it was not modified at all). I also saw the program above return unexpected values on http://cpp.sh at some point but not consistently. In the end, I could not isolate the problem in a MVCE...

I'm just wondering if returning a non-const reference to a non-const member from a const getter could possibly be a problem.

答:
This code can easily lead to undefined behavior. Consider this example, based on what you said in comments:

```<code>struct B {
  std::vector<int> vec;
  A a;
  B() : vec{}, a{vec} {}
};

int main() {
  const B b;

  auto& vec = b.a.getData();

  vec.push_back(0);
}
</code>```

I have a const object, and by extension all its members are const. But here I am getting a non-const reference to one of these const objects. No warning, no explicit ugly cast. Just silent nasal demons.

Even if the ownership is never a problem, this is just terribly error prone.

Body:
Is there something wrong with this code?

// Example program
#include <iostream>
#include <string>
#include <vector>

class A
{
public:
    A( std::vector<int>& ref ) : data(ref) {}

    std::vector<int>& getData() const { return data; }

private:
    std::vector<int>& data;
};

void modifyA( const A& a )
{
    a.getData().push_back(3);
}

int main()
{
    std::vector<int> foo;
    A a(foo);
    modifyA(a);
    std::cout << foo.size() << std::endl;
    std::cout << foo.front() << std::endl;
}

It looks good to me, but I'm experiencing undefined behaviour under Android when deploying a much more complex code with similar approach. At some point, a member (a shared_ptr) of the class gets corrupted when the previous member of the class (a std::vector) is modified through such a getter (the shared_ptr becomes NULL, while it was not modified at all). I also saw the program above return unexpected values on http://cpp.sh at some point but not consistently. In the end, I could not isolate the problem in a MVCE...

I'm just wondering if returning a non-const reference to a non-const member from a const getter could possibly be a problem.

Body:
This code can easily lead to undefined behavior. Consider this example, based on what you said in comments:

struct B {
  std::vector<int> vec;
  A a;
  B() : vec{}, a{vec} {}
};

int main() {
  const B b;

  auto& vec = b.a.getData();

  vec.push_back(0);
}

I have a const object, and by extension all its members are const. But here I am getting a non-const reference to one of these const objects. No warning, no explicit ugly cast. Just silent nasal demons.

Even if the ownership is never a problem, this is just terribly error prone.


问:
Rails - Find missing keys between different locales (.yml files)
I have 2 locale files en.yml and pt.yml. There are some keys that exist only on pt.yml and other keys that exist only on en.yml

Is there a method or routine to list all these keys? (Just comparing the two files)

Example output:

```<code>en.activerecord.attributes.person.hand
pt.activerecord.models.bird
</code>```

Obs: something other than the  i18n-tasks missing task.

答:
I find this solution work perfect. It's from a blog post of Kisko Labs. Reference is here: http://blog.kiskolabs.com/post/908453942/comparing-rails-locale-files-for-missing

LOCALE_1 = "~/Code/project/config/locales/fi.yml"
LOCALE_2 = "~/Code/project/config/locales/en.yml"

require 'yaml'

def flatten_keys(hash, prefix="")
  keys = []
  hash.keys.each do |key|
    if hash[key].is_a? Hash
      current_prefix = prefix + "#{key}."
      keys << flatten_keys(hash[key], current_prefix)
    else
      keys << "#{prefix}#{key}"
    end
  end
  prefix == "" ? keys.flatten : keys
end

def compare(locale_1, locale_2)
  yaml_1 = YAML.load(File.open(File.expand_path(locale_1)))
  yaml_2 = YAML.load(File.open(File.expand_path(locale_2)))

  keys_1 = flatten_keys(yaml_1[yaml_1.keys.first])
  keys_2 = flatten_keys(yaml_2[yaml_2.keys.first])

  missing = keys_2 - keys_1
  file = locale_1.split('/').last
  if missing.any?
    puts "Missing from #{file}:"
    missing.each { |key| puts "  - #{key}" }
  else
    puts "Nothing missing from #{file}."
  end
end
```

Body:
I have 2 locale files en.yml and pt.yml. There are some keys that exist only on pt.yml and other keys that exist only on en.yml

Is there a method or routine to list all these keys? (Just comparing the two files)

Example output:

en.activerecord.attributes.person.hand
pt.activerecord.models.bird

Obs: something other than the  i18n-tasks missing task.

ContentLicense: CC BY-SA 4.0


答:
You can do all of this with dataframe transformations and udfs. The only slightly annoying thing is that, because you technically have two different types of dictionaries (one where key=integer and value=dictionary, the other where key=integer value=float), you will have to define two udfs with different datatypes. Here is one possible way to do this:

```<code>from pyspark.sql.functions import udf,collect_list,create_map
from pyspark.sql.types import MapType,IntegerType,FloatType

data = [[160,163,27.0],[160,183,27.0],[161,162,22.0],
      [161,170,31.0],[162,161,22.0],[162,167,24.0],
      [163,160,27.0],[163,164,27.0],[164,163,27.0],
      [164,165,35.0],[165,164,35.0],[165,166,33.0],
      [166,165,33.0],[166,167,31.0],[167,162,24.0],
      [167,166,31.0],[167,168,27.0],[168,167,27.0],
      [168,169,23.0],[169,168,23.0]]

cols = ['FromComponentID','ToComponentID','Cost']
df = spark.createDataFrame(data,cols)

combineMap = udf(lambda maps: {key:f[key] for f in maps for key in f},
             MapType(IntegerType(),FloatType()))

combineDeepMap = udf(lambda maps: {key:f[key] for f in maps for key in f},
             MapType(IntegerType(),MapType(IntegerType(),FloatType())))

mapdf = df.groupBy('FromComponentID')\
.agg(collect_list(create_map('ToComponentID','Cost')).alias('maps'))\
.agg(combineDeepMap(collect_list(create_map('FromComponentID',combineMap('maps')))))

result_dict = mapdf.collect()[0][0]
</code>```

For a large dataset, this should offer some performance boosts over a solution that requires the data to be collected onto a single node. But since spark still has to serialize the udf, there won't be huge gains over an rdd based solution.

Update:

An rdd solution is a lot more compact but, in my opinion, it is not as clean. This is because pyspark doesn't store large dictionaries as rdds very easily. The solution is to store it as a distributed list of tuples and then convert it to a dictionary when you collect it to a single node. Here is one possible solution:

```<code>maprdd = df.rdd.groupBy(lambda x:x[0]).map(lambda x:(x[0],{y[1]:y[2] for y in x[1]}))
result_dict = dict(maprdd.collect())
</code>```

Again, this should offer performance boosts over a pure python implementation on single node, and it might not be that different than the dataframe implementation, but my expectation is that the dataframe version will be more performant.

Title: Dataframe pyspark to dict

Body:
I have this dataframe path_df:

path_df.show()
+---------------+-------------+----+
|FromComponentID|ToComponentID|Cost|
+---------------+-------------+----+
|            160|          163|27.0|
|            160|          183|27.0|
|            161|          162|22.0|
|            161|          170|31.0|
|            162|          161|22.0|
|            162|          167|24.0|
|            163|          160|27.0|
|            163|          164|27.0|
|            164|          163|27.0|
|            164|          165|35.0|
|            165|          164|35.0|
|            165|          166|33.0|
|            166|          165|33.0|
|            166|          167|31.0|
|            167|          162|24.0|
|            167|          166|31.0|
|            167|          168|27.0|
|            168|          167|27.0|
|            168|          169|23.0|
|            169|          168|23.0|
+---------------+-------------+----+
only showing top 20 rows

From this, I want to make a dictionnary, as follow:
{FromComponentID:{ToComponentID:Cost}}

For my current data, it would be:

{160 : {163 : 27,
        183 : 27},
 161 : {162 : 22,
        170 : 31},
 162 : {161 : 22
        167 : 24},
 ...
 167 : {162 : 24,
        166 : 31,
        168 : 27}
 168 : {167 : 27,
        169 : 23},
 169 : {168 : 23}
}

Can I do that using only PySpark and how ? Or maybe it's better to extract my data and process them directly with python.

Body:
You can do all of this with dataframe transformations and udfs. The only slightly annoying thing is that, because you technically have two different types of dictionaries (one where key=integer and value=dictionary, the other where key=integer value=float), you will have to define two udfs with different datatypes. Here is one possible way to do this:

from pyspark.sql.functions import udf,collect_list,create_map
from pyspark.sql.types import MapType,IntegerType,FloatType

data = [[160,163,27.0],[160,183,27.0],[161,162,22.0],
      [161,170,31.0],[162,161,22.0],[162,167,24.0],
      [163,160,27.0],[163,164,27.0],[164,163,27.0],
      [164,165,35.0],[165,164,35.0],[165,166,33.0],
      [166,165,33.0],[166,167,31.0],[167,162,24.0],
      [167,166,31.0],[167,168,27.0],[168,167,27.0],
      [168,169,23.0],[169,168,23.0]]

cols = ['FromComponentID','ToComponentID','Cost']
df = spark.createDataFrame(data,cols)

combineMap = udf(lambda maps: {key:f[key] for f in maps for key in f},
             MapType(IntegerType(),FloatType()))

combineDeepMap = udf(lambda maps: {key:f[key] for f in maps for key in f},
             MapType(IntegerType(),MapType(IntegerType(),FloatType())))

mapdf = df.groupBy('FromComponentID')\
.agg(collect_list(create_map('ToComponentID','Cost')).alias('maps'))\
.agg(combineDeepMap(collect_list(create_map('FromComponentID',combineMap('maps')))))

result_dict = mapdf.collect()[0][0]

For a large dataset, this should offer some performance boosts over a solution that requires the data to be collected onto a single node. But since spark still has to serialize the udf, there won't be huge gains over an rdd based solution.

Update:

An rdd solution is a lot more compact but, in my opinion, it is not as clean. This is because pyspark doesn't store large dictionaries as rdds very easily. The solution is to store it as a distributed list of tuples and then convert it to a dictionary when you collect it to a single node. Here is one possible solution:

maprdd = df.rdd.groupBy(lambda x:x[0]).map(lambda x:(x[0],{y[1]:y[2] for y in x[1]}))
result_dict = dict(maprdd.collect())

Again, this should offer performance boosts over a pure python implementation on single node, and it might not be that different than the dataframe implementation, but my expectation is that the dataframe version will be more performant.


问:
Dynamically adding ActiveRecord scopes
I have many scopes that use date ranges to do something, e.g. clicks_between(start_date, end_date). I also have want to support adding in a school year string, where we have an existing SchoolYear that has a start and end methods.

I could do something like:

```<code>scope :clicks_during, -> (year) {
    year = Year.new(year) if year.is_a?(Integer)
    send('clicks_between', year.start, year.end)
}
</code>```

However, I'd rather not have to copy and paste this code everywhere. Is there a way to just dynamically add this scope if the "betweeen" scope exists already?

答:
Applying the concept of concerns, you may group together dependent scopes inside a module and include that module in the models as you need. Moreover as your scopes do accept arguments, using a class method is the preferred way in place of scopes. For more, please check Passing in arguments.

```<code>module Clickable
  extend ActiveSupport::Concern

  class_methods do
    def clicks_between(start_date, end_date)
      # ...
    end

    def clicks_during(year)
      year = Year.new(year) if year.is_a?(Integer)
      send('clicks_between', year.start, year.end)
    end
  end
end
</code>```

In your model:

```<code>class SomeModel < ActiveRecord::Base
  include Clickable
end

class OtherModel < ActiveRecord::Base
  has_many :some_models
end
</code>```

Now you can call scopes as usual:

```<code>SomeModel.clicks_during(2017)
other_model.some_models.clicks_during(2017)
</code>```

ActiveSupport::Concern api

Title: Dynamically adding ActiveRecord scopes

Body:
I have many scopes that use date ranges to do something, e.g. clicks_between(start_date, end_date). I also have want to support adding in a school year string, where we have an existing SchoolYear that has a start and end methods.

I could do something like:

scope :clicks_during, -> (year) {
    year = Year.new(year) if year.is_a?(Integer)
    send('clicks_between', year.start, year.end)
}

However, I'd rather not have to copy and paste this code everywhere. Is there a way to just dynamically add this scope if the "betweeen" scope exists already?

Body:
Applying the concept of concerns, you may group together dependent scopes inside a module and include that module in the models as you need. Moreover as your scopes do accept arguments, using a class method is the preferred way in place of scopes. For more, please check Passing in arguments.

module Clickable
  extend ActiveSupport::Concern

  class_methods do
    def clicks_between(start_date, end_date)
      # ...
    end

    def clicks_during(year)
      year = Year.new(year) if year.is_a?(Integer)
      send('clicks_between', year.start, year.end)
    end
  end
end

In your model:

class SomeModel < ActiveRecord::Base
  include Clickable
end

class OtherModel < ActiveRecord::Base
  has_many :some_models
end

Now you can call scopes as usual:

SomeModel.clicks_during(2017)
other_model.some_models.clicks_during(2017)

ActiveSupport::Concern api


问:
Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:

Uncaught TypeError: Cannot read property 'checked' of undefined.

Here is part of the HTML:

```<code><form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
  Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
  <br>
  <p>Please choose your favourite types of books.(check all that apply)</p>
  <input type="checkbox" name="books" value="Science Fiction">Science Fiction
  <input type="checkbox" name="books" value="Travel Guide">Travel Guide
  <input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
  <input type="checkbox" name="books" value="Other">Other <br>
  <textarea></textarea><br>
  <input type="submit" name="submit">
  <input type="reset" name="reset">
</form>
</code>```

and part of the JavaScript for the checkboxes:

```<code>function validChoice()
    {
        var bookChoice = document.userSurvey.books.value;
        var x= "";

        for (i=0;i< 4;i++)
        {
            if (document.userSurvey['bookChoice'+i].checked)
            {
                bookChoice = document.userSurvey['bookChoice'+i].value;
                x = x +"\n"+ bookChoice;
            }
        }

        if (bookChoice == "")
        {
            window.alert("You must select at least one book category.");
                return false;
            }
        else
        {
            var userName = document.userSurvey.userName.value;
            var eMail = document.userSurvey.email.value;
            var phoneNo = document.userSurvey.phone.value;
            return true;
    }
}
</code>```

I am currently learning in JavaScript therefore I would prefer help in JavaScript only.

Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/

答:
You missed some tag names and missspell them in js function:

```<code><h1>User Survey</h1>

<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">

</form>
</code>```

and js code goes like this:

```<code>function validName() {
  var name = document.userSurvey.userName.value;

  if (!/^[a-zA-Z]*$/g.test(name)) {
    alert("Please enter letters a - z only");
    document.userSurvey.userName.focus();
    return false;
  } else {
    return true;
  }

}

function validNumber() {
  var theNumbersOnly = "";
  var theChar = "";
  var theInput = document.userSurvey.phone.value;

  for (i = 0; i < theInput.length; i++) {
    theChar = theInput.substring(i, i + 1);
    if (theChar >= "0" && theChar <= "9") {
      theNumbersOnly = "" + theNumbersOnly + theChar;
    }
  }

  if (theNumbersOnly.length < 10) {
    alert("You must enter 10 numbers.");
    document.userSurvey.phone.focus();
  } else {
    var areacode = theNumbersOnly.substring(0, 3);
    var exchange = theNumbersOnly.substring(3, 6);
    var extension = theNumbersOnly.substring(6, 10);
    var newNumber = "(" + areacode + ") ";
    newNumber += exchange + "-" + extension;

    document.userSurvey.phone.value = newNumber;
    return true;
  }
}

function validEmail() {
  var email = document.userSurvey.email.value;
  var atLoc = email.indexOf("@", 1);
  var dotLoc = email.indexOf(".", atLoc + 2);
  var len = email.length;

  if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
    return true;
  } else {
    alert("Please enter your e-mail address properly.");
    return false;
  }
}

function validChoice() {
  //var bookChoice = document.userSurvey.books.value;
  var bookChoice;
  var x = "";

  for (var i = 0; i < 4; i++) {
    if (document.userSurvey.books[i].checked) {
    console.log(document.userSurvey);
      bookChoice = document.userSurvey.books[i].value;
      x = x + "\n" + bookChoice;
    }
  }

  if (bookChoice == "") {
    window.alert("You must select at least one book category.");
    return false;
  } else {
    var userName = document.userSurvey.userName.value;
    var eMail = document.userSurvey.email.value;
    var phoneNo = document.userSurvey.phone.value;
    console.log(userName);
    console.log(eMail);
    console.log(phoneNo);
    return true;
  }
}

function validAll() {
  if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
    return true;
  } else {
    return false;
  }
}
</code>```

You missed email tag name too. regards

Body:
I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:

Uncaught TypeError: Cannot read property 'checked' of undefined.

Here is part of the HTML:

<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
  Name (Required): <input type="text" name="userName" id="userName" required="">
 E-Mail (Required): <input type="text" name="mail" id="mail" required="">
 Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()">

Please choose your favourite types of books.(check all that apply)

  <input type="checkbox" name="books" value="Science Fiction">Science Fiction
  <input type="checkbox" name="books" value="Travel Guide">Travel Guide
  <input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
  <input type="checkbox" name="books" value="Other">Other

  <textarea></textarea>

  <input type="submit" name="submit">
  <input type="reset" name="reset">
</form>

and part of the JavaScript for the checkboxes:

function validChoice()
    {
        var bookChoice = document.userSurvey.books.value;
        var x= "";

        for (i=0;i< 4;i++)
        {
            if (document.userSurvey['bookChoice'+i].checked)
            {
                bookChoice = document.userSurvey['bookChoice'+i].value;
                x = x +"\n"+ bookChoice;
            }
        }

        if (bookChoice == "")
        {
            window.alert("You must select at least one book category.");
                return false;
            }
        else
        {
            var userName = document.userSurvey.userName.value;
            var eMail = document.userSurvey.email.value;
            var phoneNo = document.userSurvey.phone.value;
            return true;
    }
}

I am currently learning in JavaScript therefore I would prefer help in JavaScript only.

Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/

Body:
You missed some tag names and missspell them in js function:

<h1>User Survey</h1>

<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery@worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">

</form>

and js code goes like this:

function validName() {
  var name = document.userSurvey.userName.value;

  if (!/^[a-zA-Z]*$/g.test(name)) {
    alert("Please enter letters a - z only");
    document.userSurvey.userName.focus();
    return false;
  } else {
    return true;
  }

}

function validNumber() {
  var theNumbersOnly = "";
  var theChar = "";
  var theInput = document.userSurvey.phone.value;

  for (i = 0; i < theInput.length; i++) {
    theChar = theInput.substring(i, i + 1);
    if (theChar >= "0" && theChar <= "9") {
      theNumbersOnly = "" + theNumbersOnly + theChar;
    }
  }

  if (theNumbersOnly.length < 10) {
    alert("You must enter 10 numbers.");
    document.userSurvey.phone.focus();
  } else {
    var areacode = theNumbersOnly.substring(0, 3);
    var exchange = theNumbersOnly.substring(3, 6);
    var extension = theNumbersOnly.substring(6, 10);
    var newNumber = "(" + areacode + ") ";
    newNumber += exchange + "-" + extension;

    document.userSurvey.phone.value = newNumber;
    return true;
  }
}

function validEmail() {
  var email = document.userSurvey.email.value;
  var atLoc = email.indexOf("@", 1);
  var dotLoc = email.indexOf(".", atLoc + 2);
  var len = email.length;

  if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
    return true;
  } else {
    alert("Please enter your e-mail address properly.");
    return false;
  }
}

function validChoice() {
  //var bookChoice = document.userSurvey.books.value;
  var bookChoice;
  var x = "";

  for (var i = 0; i < 4; i++) {
    if (document.userSurvey.books[i].checked) {
    console.log(document.userSurvey);
      bookChoice = document.userSurvey.books[i].value;
      x = x + "\n" + bookChoice;
    }
  }

  if (bookChoice == "") {
    window.alert("You must select at least one book category.");
    return false;
  } else {
    var userName = document.userSurvey.userName.value;
    var eMail = document.userSurvey.email.value;
    var phoneNo = document.userSurvey.phone.value;
    console.log(userName);
    console.log(eMail);
    console.log(phoneNo);
    return true;
  }
}

function validAll() {
  if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
    return true;
  } else {
    return false;
  }
}

You missed email tag name too. regards


问:
sql inner join reference a table in subquery
The query below:

```<code>select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId
    join Yetkilendirme.Users yu
        on mi.CreatedBy = yu.ID
    join Muayene.Tani mt
        on mm.ID = mt.MuayeneId
where
    mm.IsDeleted <> 1
    and mi.IsDeleted <> 1
    and mt.IsDeleted <> 1
group by
    yu.Soyad,
    mt.ICD10Kodu
</code>```

returns the data below:

```<code>HALAÇ           J00 5
DEĞİRMENCİOĞLU  J00 12
GÖKALP          J02 22
DİKİLİLER       J03 14
</code>```

but actually I need the rate of the entity not the exact number it occurs so I need to divide it like this:

```<code>select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID)/count(select * from Muayene.Muayene where ID=mm.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId...
</code>```

but it doesn't work. It gives the error message:

the multipart identifier mi.ID couldn't be found

How can I make it work?

答:
You need to do your COUNT operations in joined queries, not a query inside your SELECT list.  Queries in SELECT lists don't work unless you're pulling exactly 1 value, which you are not doing here.  Also, you can't do mathematical operations on derived values like COUNT() in the same query in which you're deriving them.

So to calculate your rate you can do the below and then join it to whatever else you need using ID

```<code>select
    a.mi_ID as ID
    , a.ct_mi / b.ct_mm as Rate
from
    (select
        mi.ID as mi_ID
        , count(mi.ID) as ct_mi
    from  [Muayene.Ilac] as mi
    group by mi.ID) as a
inner join
    (select
        mm.ID as mm_ID
        , count(mm.ID) as ct_mm
    from [Muayene.Muayene] as mm
    group by mm.ID) as b
on a.mi_ID = b.mm_ID
</code>```

Body:
The query below:

select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId
    join Yetkilendirme.Users yu
        on mi.CreatedBy = yu.ID
    join Muayene.Tani mt
        on mm.ID = mt.MuayeneId
where
    mm.IsDeleted <> 1
    and mi.IsDeleted <> 1
    and mt.IsDeleted <> 1
group by
    yu.Soyad,
    mt.ICD10Kodu

returns the data below:

HALAÇ           J00 5
DEĞİRMENCİOĞLU  J00 12
GÖKALP          J02 22
DİKİLİLER       J03 14

but actually I need the rate of the entity not the exact number it occurs so I need to divide it like this:

select
    yu.Soyad,
    mt.ICD10Kodu,
    count(mi.ID)/count(select * from Muayene.Muayene where ID=mm.ID) as AASayisi
from
    Muayene.Muayene mm
    join Muayene.Ilac mi
        on mm.ID = mi.MuayeneId...

but it doesn't work. It gives the error message:

the multipart identifier mi.ID couldn't be found

How can I make it work?

Body:
You need to do your COUNT operations in joined queries, not a query inside your SELECT list.  Queries in SELECT lists don't work unless you're pulling exactly 1 value, which you are not doing here.  Also, you can't do mathematical operations on derived values like COUNT() in the same query in which you're deriving them.

So to calculate your rate you can do the below and then join it to whatever else you need using ID

select
    a.mi_ID as ID
    , a.ct_mi / b.ct_mm as Rate
from
    (select
        mi.ID as mi_ID
        , count(mi.ID) as ct_mi
    from  [Muayene.Ilac] as mi
    group by mi.ID) as a
inner join
    (select
        mm.ID as mm_ID
        , count(mm.ID) as ct_mm
    from [Muayene.Muayene] as mm
    group by mm.ID) as b
on a.mi_ID = b.mm_ID


问:
Method cannot be applied to given types Program09
I made this program as a project for one of my classes, and upon compiling it, I get this error:

Program09.java:21: error: method calculateCelsius in class Program09 cannot be applied to given types;
             double cTemp = calculateCelsius();
                            ^
    required: int
    found: no arguments
    reason: actual and formal argument lists differ in length
  Program09.java:24: error: method calculateCelsius in class Program09 cannot be applied to given types;
            calculateCelsius();
            ^
    required: int
    found: no arguments
    reason: actual and formal argument lists differ in length
  Program09.java:25: error: method displayResults in class Program09 cannot be applied to given types;
            displayResults();
            ^
    required: int,double
    found: no arguments
    reason: actual and formal argument lists differ in length
  3 errors

This is the program below.  Any help would be greatly appreciated!

```<code>import java.util.Scanner;

public class Program09
{
   public static void main(String[] args)
   {
       int fTemp = getFarenheit();
       double cTemp = calculateCelsius();
      displayInstructions();
      getFarenheit();
      calculateCelsius();
      displayResults();
   }
   public static void displayInstructions()
   {
       System.out.println("This program will convert farenheit to celsius");
       System.out.println("after you enter a farenheit temperature");
   }
   public static int getFarenheit()
   {
       System.out.println("Please enter your temperature below");
       Scanner keyboard = new  Scanner(System.in);
       return keyboard.nextInt();
   }
   public static double calculateCelsius(int farenheit)
   {
       return (5 * (farenheit - 32) / 9.0);
   }
   public static void displayResults(int fTemp, double cTemp)
   {
       System.out.println("Your farenheit temperature is " + fTemp);
       System.out.printf("Your celsius temperature is ", + cTemp);
       System.out.println("Thank you for using the program!");
       System.out.println("The rest of the world needs to conform to imperial measurments, cuz 'merica");
       return;

   }
}
</code>```

答:
Your calling calculateCelsius without a parameter, you need to pass your parameter correctly, like this.

```<code>int fTemp = getFarenheit();
double cTemp = calculateCelsius(fTemp);
</code>```

additionally displayResults will also fail for the same reason, pass in fTemp and cTemp when calling it

Body:
I made this program as a project for one of my classes, and upon compiling it, I get this error:

Program09.java:21: error: method calculateCelsius in class Program09 cannot be applied to given types;
             double cTemp = calculateCelsius();
                            ^
    required: int
    found: no arguments
    reason: actual and formal argument lists differ in length
  Program09.java:24: error: method calculateCelsius in class Program09 cannot be applied to given types;
            calculateCelsius();
            ^
    required: int
    found: no arguments
    reason: actual and formal argument lists differ in length
  Program09.java:25: error: method displayResults in class Program09 cannot be applied to given types;
            displayResults();
            ^
    required: int,double
    found: no arguments
    reason: actual and formal argument lists differ in length
  3 errors

This is the program below.  Any help would be greatly appreciated!

import java.util.Scanner;

public class Program09
{
   public static void main(String[] args)
   {
       int fTemp = getFarenheit();
       double cTemp = calculateCelsius();
      displayInstructions();
      getFarenheit();
      calculateCelsius();
      displayResults();
   }
   public static void displayInstructions()
   {
       System.out.println("This program will convert farenheit to celsius");
       System.out.println("after you enter a farenheit temperature");
   }
   public static int getFarenheit()
   {
       System.out.println("Please enter your temperature below");
       Scanner keyboard = new  Scanner(System.in);
       return keyboard.nextInt();
   }
   public static double calculateCelsius(int farenheit)
   {
       return (5 * (farenheit - 32) / 9.0);
   }
   public static void displayResults(int fTemp, double cTemp)
   {
       System.out.println("Your farenheit temperature is " + fTemp);
       System.out.printf("Your celsius temperature is ", + cTemp);
       System.out.println("Thank you for using the program!");
       System.out.println("The rest of the world needs to conform to imperial measurments, cuz 'merica");
       return;

   }
}

Body:
Your calling calculateCelsius without a parameter, you need to pass your parameter correctly, like this.

int fTemp = getFarenheit();
double cTemp = calculateCelsius(fTemp);

additionally displayResults will also fail for the same reason, pass in fTemp and cTemp when calling it


问:
Check if letters from word are all in string Hangman
I'm trying to create a simple hangman game in Python. I've come quite far for a beginner I guess :) The only thing I can't accomplish is checking wether the word is actually guessed. I need to check if all the letters are actually in a list I've created, yet I'm not sure how.
I do realise there was a topic regarding this, this didn't help me tho. </p>

```<code>import random

with open('randomlist.txt') as bestand:
woordenlijst = bestand.read().splitlines()

print("Welcome to Hangman.")
naam = input("What is your name? ")
print("Hello", naam, ", the computer selecter a secret word.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("The length of the word is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Letter: ")
    if letter in ingevoerde_letters:
        print("You already tried this letter.")
    elif letter in woord:
        print("This letter is in the word. We'll fill it in for you.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        print("This letter is not in the word", galg[levens])
        levens = levens + 1
print(galg[10], "\nGame over!")
</code>```

答:
You have most of what you need to determine this, and while there are far more efficient ways to do what you've done (check out sets in Python), the following will work just fine:</p>

```<code># Somewhere towards the top of the script
total_letters_guessed = 0

...

while levens <= 10:
    ...
    if woord[i] == letter:
        print(letter, end=" ")
        ingevoerde_letters.append(letter)
        i = i + 1
        total_letters_guessed += 1

    ...

    # Before your loop ends
    if total_letters_guessed == lengte_woord:
        print("You won!")
</code>```

Body:
I'm trying to create a simple hangman game in Python. I've come quite far for a beginner I guess :) The only thing I can't accomplish is checking wether the word is actually guessed. I need to check if all the letters are actually in a list I've created, yet I'm not sure how.
I do realise there was a topic regarding this, this didn't help me tho.

import random

with open('randomlist.txt') as bestand:
woordenlijst = bestand.read().splitlines()

print("Welcome to Hangman.")
naam = input("What is your name? ")
print("Hello", naam, ", the computer selecter a secret word.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("The length of the word is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Letter: ")
    if letter in ingevoerde_letters:
        print("You already tried this letter.")
    elif letter in woord:
        print("This letter is in the word. We'll fill it in for you.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        print("This letter is not in the word", galg[levens])
        levens = levens + 1
print(galg[10], "\nGame over!")

Body:
You have most of what you need to determine this, and while there are far more efficient ways to do what you've done (check out sets in Python), the following will work just fine:

# Somewhere towards the top of the script
total_letters_guessed = 0

...

while levens <= 10:
    ...
    if woord[i] == letter:
        print(letter, end=" ")
        ingevoerde_letters.append(letter)
        i = i + 1
        total_letters_guessed += 1

    ...

    # Before your loop ends
    if total_letters_guessed == lengte_woord:
        print("You won!")


问:
Getting the first int value of a tuple but the first value is a string (Error) Python
I am trying to get the first int value from all of the tuples in my dictionary keys. The problem is I keep getting the error: "ValueError: invalid literal for int() with base 10: 'Population'" The code I am using is

print([int(item[0]) for item in self.countryCat.values()])

Is there any way I can skip over the first value in my tuple which is "Population" so I will not get this error anymore? I have been stuck on this forever.

Thanks!

答:
If you really want to use list comprehension, you need to make it a conditional list as described here and then for your condition, create a function that returns true/false if the string can be converted to a string as described here</p>

```<code>def represent_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return

print([int(item[0]) for item in self.countryCat.values() if represent_int(item[0])])
</code>```

Body:
If you really want to use list comprehension, you need to make it a conditional list as described here and then for your condition, create a function that returns true/false if the string can be converted to a string as described here

def represent_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return

print([int(item[0]) for item in self.countryCat.values() if represent_int(item[0])])


问:
Drupal Folder and File Permissions
I'm having a craptastic time trying to figure out how I should configure my Drupal folders and files. I've search all over drupal.org but keep coming up with dribble about the www-data needing access to the "sites" and the "files" folder and how "settings.php" needs some awesome permissions.

But what I need is a list like this:

/ = 744 or drwxr-r--

/includes/ = ...

/misc/ = ...

/modules/ = ...

/profiles/ = ...

/scripts/ = ...

/sites/ = ...

/sites/all/ = ...

/sites/default/ = ...

/sites/default/settings.php = 444?

/sites/default/files/ = ...

I don't think I need someone to catalog every single file, folder, and permission settings for me. I'm guessing that I can just set the root folder permissions to "apply to enclosed items" and then fix the few folders and files that need special settings.

I would really appreciate any contributions that can lead me back to sanity! :)

Scott

答:
default install on my local machine has

-rw-r--r-- all php files

drwxr-xr-x directories

drwxrwxr-x files folder

-r--r--r-- settings.php file

Title: Drupal Folder and File Permissions


问:
Running two threads in same time ( multithreading?)
I'm trying to get two threads to work in same time.
Let me explain with code:

Main Class that runs both threads

```<code>public static void main(String[] args) {
    abThread.move(5);
    cdThread.move(5);
}
</code>```

Thread 1:

```<code>static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("a");
            i -= 1;
            continue;
        } else {
            System.out.println("b");
            i -= 1;
            continue;
        }
    }
}
</code>```

Thread 2:

```<code>static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("c");
            i -= 1;
            continue;
        } else {
            System.out.println("d");
            i -= 1;
            continue;
        }
    }
}
</code>```

Im getting random a/b x 5 and after 5 of them im getting random (c/d) x5

My goal is to get a/b,c/d,a/b,c/d... and so on

Any help or redirection to some way-would greatly appreciate it!

Edit: Notice i tryed with try sleep but it just postpones how long before next a/b after a/b. Only way i could do it a/b,c/b would be

```<code>    abThread.move(1);
    cdThread.move(1);
    abThread.move(1);
</code>```

......

Thanks

答:
The work performed by a thread other than the main one is determined by the Runnable with which it was initialized or by the implementation of its run() method if you've overridden that.  One of those places is where you should be placing the invocations of the various move() methods.  Then your main thread should start() both thread instances.

That (probably) achieves the threads running in parallel, subject to thread scheduling and the availability of execution resources.  As @Alexander described, however, it does not necessarily produce perfect alternation between the outputs of the two threads, nor does it even guarantee that any of the output produced by one thread will appear before any of the output produced by the other.

If you need perfect alternation then the two threads need to synchronize with each other to take turns.  There is a large number of ways you could implement that, but if you want it, it needs to be built in to your move() methods.  The low-level, old-school ways revolve around using the wait() and notify() / notifyAll() methods of a shared object.  You might also use a SynchronousQueue for just two threads taking turns, among many other possibilities.

Body:
I'm trying to get two threads to work in same time.
Let me explain with code:

Main Class that runs both threads

public static void main(String[] args) {
    abThread.move(5);
    cdThread.move(5);
}

Thread 1:

static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("a");
            i -= 1;
            continue;
        } else {
            System.out.println("b");
            i -= 1;
            continue;
        }
    }
}

Thread 2:

static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("c");
            i -= 1;
            continue;
        } else {
            System.out.println("d");
            i -= 1;
            continue;
        }
    }
}

Im getting random a/b x 5 and after 5 of them im getting random (c/d) x5

My goal is to get a/b,c/d,a/b,c/d... and so on

Any help or redirection to some way-would greatly appreciate it!

Edit: Notice i tryed with try sleep but it just postpones how long before next a/b after a/b. Only way i could do it a/b,c/b would be

    abThread.move(1);
    cdThread.move(1);
    abThread.move(1);

......

Thanks


问:
How to do bulk insert from text file into sql table
I saw a few examples here, but I could not find the right solution.

I have a .txt file with a comma separated data that looks like this:

I have the following logic to bulk insert it into the table:

```<code>SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\n'',TABLOCK)'
EXEC (@cmd)
</code>```

This is the table structure:

.

After the execution, everything is in one row.

I need to insert everything from the file into the table, so each line from the file will be on a separate row.
Later on I will need to extract the data and move it into different tables based on certain conditions.

How can I correctly insert the data?

答: I fixed it by changing to ROWTERMINATOR=''0x0a''</p>

Body:
I saw a few examples here, but I could not find the right solution.

I have a .txt file with a comma separated data that looks like this:

I have the following logic to bulk insert it into the table:

SET @cmd = 'BULK INSERT dbo.vw_RPT_TBL_Bulk_Staging FROM '''+ @FullFilePath +
            '''WITH(FIRSTROW = 1,FIELDTERMINATOR = '','',ROWTERMINATOR=''\n'',TABLOCK)'
EXEC (@cmd)

This is the table structure:

.

After the execution, everything is in one row.

I need to insert everything from the file into the table, so each line from the file will be on a separate row.
Later on I will need to extract the data and move it into different tables based on certain conditions.

How can I correctly insert the data?


问:
Images take time and get loaded after loading text contents on my website
I want my images to be loaded fast as HTML and CSS get loaded.
As of now HTML and CSS don't take time but loading images (all are in .svg format and small) take more than 2 seconds after other content.

Is there a way to load them faster?

I found answers regarding fast-loading and followed as well, which are:

-compress images

-Minify HTML and JS files

But my issue is still unresolved.

答:
As others have said, the way the pages are loading is normal.

If you can't decrease your file sizes any more, you might be interested in showing a highly compressed version while your full sized image loads:

```

In the above snippet, a 25kb image quickly loads and is shown while the 700kb image is still loading. You can watch the process in action by disabling cache and throttling your connection speed in the developer tools.

Body:
As others have said, the way the pages are loading is normal.

If you can't decrease your file sizes any more, you might be interested in showing a highly compressed version while your full sized image loads:

<img border="0" style="background:url(https://i.imgur.com/ML9NHOA.jpg) no-repeat; width:727px; height:484px" src="https://i.imgur.com/Zp8a50J.jpg" width="727" height="484" />

In the above snippet, a 25kb image quickly loads and is shown while the 700kb image is still loading. You can watch the process in action by disabling cache and throttling your connection speed in the developer tools.


问:
reading an xml file line by line with c# gives a reverse output
My code is below. The xml file I used is here.

```<code>using System;
using System.Text;
using System.Xml;

namespace ReadingAnXMLFile
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader xmlReader = XmlReader.Create("D:/C#/GameAssets/Images/alienExplode/images/alienExplode.xml");
            while (xmlReader.Read())
            {
                Console.Write(xmlReader.Name);
                while (xmlReader.MoveToNextAttribute()) // Read the attributes.
                    Console.Write(" " + xmlReader.Name + " = '" + xmlReader.Value + "' ");
                Console.WriteLine(" ");
            }
            Console.ReadKey(); // wait for keyboard input to exit
        }
    }
}
</code>```

The output of this program is in the reverse order from the data in the xml file. For example The xml file line shows

```<code><SubTexture height="25" width="24" y="474" x="180" name="explosion0000.png"/>
</code>```

whereas my console output is

```<code>SubTexture name = 'explosion0000.png'  x = '180'  y = '474'  width = '24'  height = '25'
</code>```

Any idear why this happens?

答:
According to this, XML attribute order is not significant, so the MoveToNextAttribute() order is arbitrary. They may have chosen that direction so that you can remove attributes while looping with MoveToNextAttribute(). If order matters to you, you can do this:

```<code>for (int i = 0; i < xmlReader.AttributeCount; i++) //or (int i = xmlReader.AttributeCount - 1; i >= 0; i--) for the reverse order
{
    xmlReader.MoveToAttribute(i);
    //...
}
</code>```

Body:
My code is below. The xml file I used is here.

using System;
using System.Text;
using System.Xml;

namespace ReadingAnXMLFile
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader xmlReader = XmlReader.Create("D:/C#/GameAssets/Images/alienExplode/images/alienExplode.xml");
            while (xmlReader.Read())
            {
                Console.Write(xmlReader.Name);
                while (xmlReader.MoveToNextAttribute()) // Read the attributes.
                    Console.Write(" " + xmlReader.Name + " = '" + xmlReader.Value + "' ");
                Console.WriteLine(" ");
            }
            Console.ReadKey(); // wait for keyboard input to exit
        }
    }
}

The output of this program is in the reverse order from the data in the xml file. For example The xml file line shows

<SubTexture height="25" width="24" y="474" x="180" name="explosion0000.png"/>

whereas my console output is

SubTexture name = 'explosion0000.png'  x = '180'  y = '474'  width = '24'  height = '25'

Any idear why this happens?

Body:
According to this, XML attribute order is not significant, so the MoveToNextAttribute() order is arbitrary. They may have chosen that direction so that you can remove attributes while looping with MoveToNextAttribute(). If order matters to you, you can do this:

for (int i = 0; i < xmlReader.AttributeCount; i++) //or (int i = xmlReader.AttributeCount - 1; i >= 0; i--) for the reverse order
{
    xmlReader.MoveToAttribute(i);
    //...
}


问:
jQuery pause function on hover?
I have a jQuery/JS function that is using setInterval to loop through some image slides I have.  It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it.  How do I go about doing that on the setInterval function?

```<code>var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);
</code>```

答:
Something like this would work assuming interval is defined in an outer scope:

```<code>$('.slideshow img').hover(function() {
  interval = clearInterval(interval);
}, function() {
  interval = setInterval(flip, 5000);
});
</code>```

Title: jQuery pause function on hover?

Body:
I have a jQuery/JS function that is using setInterval to loop through some image slides I have.  It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it.  How do I go about doing that on the setInterval function?

var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);

Body:
Something like this would work assuming interval is defined in an outer scope:

$('.slideshow img').hover(function() {
  interval = clearInterval(interval);
}, function() {
  interval = setInterval(flip, 5000);
});


问:
DATEADD and missing dates
How do you reliably add 10 months to a date in the DAX formula for a PowerPivot calculated column?

My first attempt only works for dates that already exist in the EventDate column.

```<code>=DATEADD(Dates[EventDate], 10, month)
</code>```

As Chris Webb wrote in his blog DATEADD is unreliable as it returns blanks whenever the resulting date is not found in the EventDate column.

My second attempt always returns data, but the day of the month is incorrect.

```<code>=[EventDate] + 10 * 31
</code>```

Notes: All dates in EventDate are on the first day of the month. I am using PowerPivot for Excel 2010. The formula is for the financial year hierarchy in a date dimension.

Is there a better way to add months in DAX?

答:
Another way to add time to a date using DAX is using EDATE(), this function add months and it will return the right day of the month. For example:</p>

```<code>Foo = EDATE(Dates[EventDate], 10)
</code>```

Title: DATEADD and missing dates

Body:
How do you reliably add 10 months to a date in the DAX formula for a PowerPivot calculated column?

My first attempt only works for dates that already exist in the EventDate column.

=DATEADD(Dates[EventDate], 10, month)

As Chris Webb wrote in his blog DATEADD is unreliable as it returns blanks whenever the resulting date is not found in the EventDate column.

My second attempt always returns data, but the day of the month is incorrect.

=[EventDate] + 10 * 31

Notes: All dates in EventDate are on the first day of the month. I am using PowerPivot for Excel 2010. The formula is for the financial year hierarchy in a date dimension.

Is there a better way to add months in DAX?

Body:
Another way to add time to a date using DAX is using EDATE(), this function add months and it will return the right day of the month. For example:

Foo = EDATE(Dates[EventDate], 10)


问:
Finding correlation coefficient from 2 lists
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

```<code>def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r
</code>```

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

```<code>def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation
</code>```

答:
Your standard deviation is wrong. You forgot to take the squareroot.
You are actually returning variance and not standard deviation from that function.
@DeathPox</p>

Body:
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation


问:
What does "abstract over" mean?
Often in the Scala literature, I encounter the phrase "abstract over", but I don't understand the intent.  For example, Martin Odersky writes

You can pass methods (or "functions") as parameters, or you can abstract over them. You can specify types as parameters, or you can abstract over them.

As another example, in the "Deprecating the Observer Pattern" paper,

A consequence from our event streams being first-class values is that we can abstract over them.

I have read that first order generics "abstract over types", while monads "abstract over type constructors".  And we also see phrases like this in the Cake Pattern paper.  To quote one of many such examples:

Abstract type members provide flexible way to abstract over concrete types of components.

Even relevant stack overflow questions use this terminology.  "can't existentially abstract over parameterized type..."

So... what does "abstract over" actually mean?

答:
Here is my narrow show and tell interpretation. It's self-explanatory and runs in the REPL.</p>

```<code>class Parameterized[T] { // type as a parameter
  def call(func: (Int) => Int) = func(1)  // function as a parameter
  def use(l: Long) { println(l) } // value as a parameter
}

val p = new Parameterized[String] // pass type String as a parameter
p.call((i:Int) => i + 1) // pass function increment as a parameter
p.use(1L) // pass value 1L as a parameter

abstract class Abstracted {
  type T // abstract over a type
  def call(i: Int): Int // abstract over a function
  val l: Long // abstract over value
  def use() { println(l) }
}

class Concrete extends Abstracted {
  type T = String // specialize type as String
  def call(i:Int): Int = i + 1 // specialize function as increment function
  val l = 1L // specialize value as 1L
}

val a: Abstracted = new Concrete
a.call(1)
a.use()
</code>```

Title: What does "abstract over" mean?

Body:
Here is my narrow show and tell interpretation. It's self-explanatory and runs in the REPL.

class Parameterized[T] { // type as a parameter
  def call(func: (Int) => Int) = func(1)  // function as a parameter
  def use(l: Long) { println(l) } // value as a parameter
}

val p = new Parameterized[String] // pass type String as a parameter
p.call((i:Int) => i + 1) // pass function increment as a parameter
p.use(1L) // pass value 1L as a parameter

abstract class Abstracted {
  type T // abstract over a type
  def call(i: Int): Int // abstract over a function
  val l: Long // abstract over value
  def use() { println(l) }
}

class Concrete extends Abstracted {
  type T = String // specialize type as String
  def call(i:Int): Int = i + 1 // specialize function as increment function
  val l = 1L // specialize value as 1L
}

val a: Abstracted = new Concrete
a.call(1)
a.use()


问:
Detect an indirect update to a field with jQuery
I have a <textarea> that is getting updated from a form with jquery. I might never actually enter anything into the textarea directly.

But I need to know how I can monitor changes to the textarea that aren't directly from direct input on the textarea?

I can use

```<code>$('#myTextbox').on('input', function() {
    // do something
});
</code>```

to know when the user is editing the myTextbox.

I tried

```<code>$('#myTextbox').on('change', function () {
  // do something
});
</code>```

but that didn't work either.

Is this possible?

答:
You can try using interval or timeout like this

```<code>var searchValue = $('#myTextbox').val();

function checkSearchChanged() {
    var currentValue = $('#myTextbox').val();
    if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $('#myTextbox').val();
       console.log(searchValue)
    }
    setTimeout(checkSearchChanged, 0.1);
}

$(function () {
    setTimeout(checkSearchChanged, 0.1);
});
</code>```

checkout working plunker here

Body:
I have a <textarea> that is getting updated from a form with jquery. I might never actually enter anything into the textarea directly.

But I need to know how I can monitor changes to the textarea that aren't directly from direct input on the textarea?

I can use

$('#myTextbox').on('input', function() {
    // do something
});

to know when the user is editing the myTextbox.

I tried

$('#myTextbox').on('change', function () {
  // do something
});

but that didn't work either.

Is this possible?

Body:
You can try using interval or timeout like this

var searchValue = $('#myTextbox').val();

function checkSearchChanged() {
    var currentValue = $('#myTextbox').val();
    if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $('#myTextbox').val();
       console.log(searchValue)
    }
    setTimeout(checkSearchChanged, 0.1);
}

$(function () {
    setTimeout(checkSearchChanged, 0.1);
});

checkout working plunker here


问:
Is "Symmetric mean absolute surface distance" (SMAD) used for 2D images or 3D images?
I am not sure if the "Symmetric mean absolute surface distance" (SMAD) is used as a metric to evaluate the segmentation algorithm for 2D images or 3D images? Thanks!</p>

答:
I found two papers which address the definitions of SMAD:

https://www.cs.ox.ac.uk/files/7732/CS-RR-15-08.pdf (see section 7.1 on average symmetric surface distance, but this is the same thing)

http://ai2-s2-pdfs.s3.amazonaws.com/2b8b/079f5eeb31a555f1a48db3b93cd8c73b2b0c.pdf (page 1439, see equation 7)

I tried to post the equation here but I do not have enough reputation.  Basically look at equation 15 in the first reference listed above.

It appears that this is defined for 3D voxels, though I don't see why it should not work in 2D.


问:
How to detect value changes of an input jQuery?
I am currently using this function to detect for any changes made to an input box in jQuery.

```<code>$(document).on("input change paste keyup", "input, textarea, select", function(e) {
    //do something
});
</code>```

The problem is that when you change the value of an input through code such as this $("input").val(currentColorChosen);, the function does not run.

How do I solve this so that the function can detect all changes made to an input, including value changes made through jQuery.

答:
$("input").change(function(){console.log("there was a change")}) and I think you can pass the value into it as well, it's a shortcut for .on( "change", handler )

More info: https://api.jquery.com/change/

Body:
I am currently using this function to detect for any changes made to an input box in jQuery.

$(document).on("input change paste keyup", "input, textarea, select", function(e) {
    //do something
});

The problem is that when you change the value of an input through code such as this $("input").val(currentColorChosen);, the function does not run.

How do I solve this so that the function can detect all changes made to an input, including value changes made through jQuery.


答:
did you want all the values together?

[n for v in dict1.values() for n in v] 'flattens' the list of values

then a boxplot is a matplotlib standard plot https://matplotlib.org/examples/pylab_examples/boxplot_demo.html

```<code>from matplotlib import pyplot as plt

plt.boxplot([n for v in dict1.values() for n in v])
</code>```

or by key

```<code># Python 3.5+
labels, data = [*zip(*dict1.items())]  # 'transpose' items to parallel key, value lists

# or backwards compatable
labels, data = dict1.keys(), dict1.values()

plt.boxplot(data)
plt.xticks(range(1, len(labels) + 1), labels)
plt.show()
</code>```

Title: Boxplot from dictionary with different length

Body:
I have one dictionary with different length of the values for each key. Trying to plot as a boxplot, I cant go forward. is there any other method to do this?

I wrote this but it doesn't work:

import matplotlib.pyplot as plt
import matplotlib as mpl

dict1 = {'Pb': [53.0, 56.0, 56.0, 57.0, 57.0, 57.0, 46.0], 'Pa': [56.0, 55.0], 'Pg': [57.0, 57.0, 58.0, 57.0, 57.0, 57.0, 57.0, 57.0,53.0, 57.0, 55.0, 58.0, 58.0, 58.0, 57.0, 57.0, 57.0, 57.0, 57.0, 55.0, 55.0, 57.0, 57.0, 55.0, 58.0, 58.0, 58.0, 55.0, 58.0, 54.0, 58.0, 57.0, 57.0, 58.0, 55.0, 56.0, 55.0, 55.0, 55.0, 58.0, 56.0, 57.0, 57.0, 57.0, 57.0, 56.0, 57.0, 56.0],'Pf': [54.0], 'Pn': [56.0, 56.0, 55.0, 56.0, 56.0, 56.0], 'Ps': [58.0, 56.0, 57.0, 56.0, 56.0, 55.0, 56.0, 56.0, 56.0, 55.0, 56.0, 56.0, 56.0, 58.0, 57.0, 58.0, 57.0, 57.0, 56.0, 58.0, 56.0, 53.0, 56.0, 56.0, 56.0, 56.0, 56.0, 56.0]}

      # remove from here
for k, v in dict1.iteritems():
      boxplot(k,v)
      plt.show()

The solution proposed and tested: Just substitute the interpretation to the text below. It works with python 3.5

#And include this:
labels, data = [*zip(*dict1.items())]  # 'transpose' items to parallel key, value lists
    plt.boxplot(data)
    plt.xticks(range(1, len(labels) + 1), labels)
    plt.show()

Body:
did you want all the values together?

[n for v in dict1.values() for n in v] 'flattens' the list of values

then a boxplot is a matplotlib standard plot https://matplotlib.org/examples/pylab_examples/boxplot_demo.html

from matplotlib import pyplot as plt

plt.boxplot([n for v in dict1.values() for n in v])

or by key

# Python 3.5+
labels, data = [*zip(*dict1.items())]  # 'transpose' items to parallel key, value lists

# or backwards compatable
labels, data = dict1.keys(), dict1.values()

plt.boxplot(data)
plt.xticks(range(1, len(labels) + 1), labels)
plt.show()


问:
After I install a theme it should say Recommended Plugins
I am learning WordPress theme development and now I need to know a feature how can I add the option on my theme so my client after install the theme he can get a notification that you need to install following recommanded plugin.
How can I do that? I need it as early as possible.
Waiting for your response.
Thanks.</p>

答:
WordPress doesn't have this feature implemented yet. But you can use external libraries.

Currently, the most used is TGM Plugin Activator.

You can configure required and recommended plugins.

On the TGMPA site, you can found an tutorial of how use it.


问:
Center Outlook WPF Add-In
I have created an Add-In for Outlook using WPF. Everything is working correctly, except for the "Flare." When the WPF Window opens, it's not being centered on the Outlook form, it opens centered on the screen. I have the WindowStartLocation set to CenterOwner, but this doesn't seem to be doing the trick.</p>

答:
You should be able to get a reference to the current instance of Outlook, access the Application object for that instance and get the Window size, and location (Left, Top) and do some math to get the positioning for your window.

Something akin to:

```<code>Dim interopApplication As Outlook.Application = _
    Me.ActiveExplorer().Application

With interopApplication.ActiveWindow
    Dim _left = Me.Width - (.Width / 2)
    Dim _top = Me.Height - (.Height / 2)
End With
</code>```

This supposes that the Outlook window is on the first monitor and is maximized.  Some more logic will have to be written to take care of other contingencies

Title: Center Outlook WPF Add-In

Body:
You should be able to get a reference to the current instance of Outlook, access the Application object for that instance and get the Window size, and location (Left, Top) and do some math to get the positioning for your window.

Something akin to:

Dim interopApplication As Outlook.Application = _
    Me.ActiveExplorer().Application

With interopApplication.ActiveWindow
    Dim _left = Me.Width - (.Width / 2)
    Dim _top = Me.Height - (.Height / 2)
End With

This supposes that the Outlook window is on the first monitor and is maximized.  Some more logic will have to be written to take care of other contingencies


问:
Clean Way to Force Use of a Derived Interface
In my application, some of the entities implement interface A, others implement interface B, and some implement both A and B.  How can I force code that looks at these entities that implement both A and B to use the derived interface for A and B?

Here's some examples:

Interface A

```<code>public interface IActive
{
   DateTime? StartEffDT { get; set; }
   DateTime? EndEffDT { get; set; }
}
</code>```

Interface B

```<code>public interface ISecured
{
    object SecurityToCheck { get; set; }
}
</code>```

Interface A and B

```<code>public interface IActiveSecured : IActive, ISecured
{
}
</code>```

Method Example

```<code>public void ExampleMethod1(IActive x) { }
public void ExampleMethod2(ISecured y) { }
public void ExampleMethod3(IActiveSecured z) { }
</code>```

Is there a way to force ExampleMethod1 to only take IActive, but not IActiveSecured?

```<code>public void UpdateItem(IActive item) {
    //update the item, if it is currently active
}
</code>```

If I tried to call UpdateItem with an IActiveSecured item, it would work. No surprise, that's how inheritance works.  But what if I want to ensure that you can't call UpdateItem with an IActiveSecured, because the security needs to be checked to make sure that the user is authorized to update the item?

Thanks for the help!

答:
Create

```<code>public interface INonSecured
{}

public interface IActiveNonSecured : IActive, INonSecured
{}
</code>```

Then change UpdateItem like so:

```<code>public void UpdateItem(IActiveNonSecured item)
{}
</code>```

The additional surfacing of the "non secured" concept makes your intent far more clearer and prevents the scenario you mentioned.

Body:
In my application, some of the entities implement interface A, others implement interface B, and some implement both A and B.  How can I force code that looks at these entities that implement both A and B to use the derived interface for A and B?

Here's some examples:

Interface A

public interface IActive
{
   DateTime? StartEffDT { get; set; }
   DateTime? EndEffDT { get; set; }
}

Interface B

public interface ISecured
{
    object SecurityToCheck { get; set; }
}

Interface A and B

public interface IActiveSecured : IActive, ISecured
{
}

Method Example

public void ExampleMethod1(IActive x) { }
public void ExampleMethod2(ISecured y) { }
public void ExampleMethod3(IActiveSecured z) { }

Is there a way to force ExampleMethod1 to only take IActive, but not IActiveSecured?

public void UpdateItem(IActive item) {
    //update the item, if it is currently active
}

If I tried to call UpdateItem with an IActiveSecured item, it would work. No surprise, that's how inheritance works.  But what if I want to ensure that you can't call UpdateItem with an IActiveSecured, because the security needs to be checked to make sure that the user is authorized to update the item?

Thanks for the help!

Body:
Create

public interface INonSecured
{}

public interface IActiveNonSecured : IActive, INonSecured
{}

Then change UpdateItem like so:

public void UpdateItem(IActiveNonSecured item)
{}

The additional surfacing of the "non secured" concept makes your intent far more clearer and prevents the scenario you mentioned.


问:
Find consecutive Nans in pandas dataframe
I would like to find consecutive nans in my dataframe columns, something like

```<code>>>> df = pd.DataFrame([[np.nan, 2, np.nan],
...                    [3, 4, np.nan],
...                    [np.nan, np.nan, np.nan],
...                    [np.nan, 3, np.nan]],
...                    columns=list('ABC'))
>>> df
     A    B   C
0  NaN  2.0 NaN
1  3.0  4.0 NaN
2  NaN  NaN NaN
3  NaN  3.0 NaN
</code>```

would give

```<code>>>> df
     A    B   C
0  1.0  NaN 4.0
1  NaN  NaN 4.0
2  2.0  1.0 4.0
3  2.0  NaN 4.0
</code>```

答:
Use:

```<code>a = df.isnull()
b = a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())).where(a)
print (b)
     A    B  C
0  1.0  NaN  4
1  NaN  NaN  4
2  2.0  1.0  4
3  2.0  NaN  4
</code>```

Detail:

```<code>#unique consecutive values
print (a.ne(a.shift()).cumsum())
   A  B  C
0  1  1  1
1  2  1  1
2  3  2  1
3  3  3  1

#count values per columns and map
print (a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())))
   A  B  C
0  1  2  4
1  1  2  4
2  2  1  4
3  2  1  4

#add NaNs by mask a
print (a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())).where(a))
     A    B  C
0  1.0  NaN  4
1  NaN  NaN  4
2  2.0  1.0  4
3  2.0  NaN  4
</code>```

One column alternative:

```<code>a = df['A'].isnull()
b = a.ne(a.shift()).cumsum()
c = b.map(b.value_counts()).where(a)

print (c)
0    1.0
1    NaN
2    2.0
3    2.0
Name: A, dtype: float64
</code>```

Body:
I would like to find consecutive nans in my dataframe columns, something like

>>> df = pd.DataFrame([[np.nan, 2, np.nan],
...                    [3, 4, np.nan],
...                    [np.nan, np.nan, np.nan],
...                    [np.nan, 3, np.nan]],
...                    columns=list('ABC'))
>>> df
     A    B   C
0  NaN  2.0 NaN
1  3.0  4.0 NaN
2  NaN  NaN NaN
3  NaN  3.0 NaN

would give

>>> df
     A    B   C
0  1.0  NaN 4.0
1  NaN  NaN 4.0
2  2.0  1.0 4.0
3  2.0  NaN 4.0

Body:
Use:

a = df.isnull()
b = a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())).where(a)
print (b)
     A    B  C
0  1.0  NaN  4
1  NaN  NaN  4
2  2.0  1.0  4
3  2.0  NaN  4

Detail:

#unique consecutive values
print (a.ne(a.shift()).cumsum())
   A  B  C
0  1  1  1
1  2  1  1
2  3  2  1
3  3  3  1

#count values per columns and map
print (a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())))
   A  B  C
0  1  2  4
1  1  2  4
2  2  1  4
3  2  1  4

#add NaNs by mask a
print (a.ne(a.shift()).cumsum().apply(lambda x: x.map(x.value_counts())).where(a))
     A    B  C
0  1.0  NaN  4
1  NaN  NaN  4
2  2.0  1.0  4
3  2.0  NaN  4

One column alternative:

a = df['A'].isnull()
b = a.ne(a.shift()).cumsum()
c = b.map(b.value_counts()).where(a)

print (c)
0    1.0
1    NaN
2    2.0
3    2.0
Name: A, dtype: float64


答:
Add the one more line after your code:</p>

```<code>$("input").val(currentColorChosen);
$("input").bind("change");
</code>```

Title: How to detect value changes of an input jQuery?

Body:
Add the one more line after your code:

$("input").val(currentColorChosen);
$("input").bind("change");


问:
Does GWT have a widget which represent  HTML tag
I know that Flowpanel in GWT will be compiled into div and Horizontal/Vertical Panel will be compiled to table. Is there any widget available to represent span in GWT ?

Or

Is there a way to achieve it apart from GWT - HTML widget ?

答:
If you just need a HTML  container then SpanElement is a way to go.

But, if you want a widget (with all its features) that is rendered as a  element you want something else.

Take a look at the SimplePanel constructors:

public SimplePanel()

Creates an empty panel that uses a DIV for its contents.

and

protected SimplePanel(Element elem)

Creates an empty panel that uses the specified browser element for its contents.

Now you look at the implementation of the first constructor:

```<code>public SimplePanel() {
    this(DOM.createDiv());
}
</code>```

So, you just want to replace it with DOM.createSpan().

This constructor is protected so you need to extend SimplePanel:

```<code>public class SpanPanel extends SimplePanel {
    public SpanPanel() {
        super(DOM.createSpan());
    }
}
</code>```

Title: Does GWT have a widget which represent <span> HTML tag

Body:
If you just need a HTML <span> container then SpanElement is a way to go.

But, if you want a widget (with all its features) that is rendered as a <span> element you want something else.

Take a look at the SimplePanel constructors:

public SimplePanel()

Creates an empty panel that uses a DIV for its contents.

and

protected SimplePanel(Element elem)

Creates an empty panel that uses the specified browser element for its contents.

Now you look at the implementation of the first constructor:

public SimplePanel() {
    this(DOM.createDiv());
}

So, you just want to replace it with DOM.createSpan().

This constructor is protected so you need to extend SimplePanel:

public class SpanPanel extends SimplePanel {
    public SpanPanel() {
        super(DOM.createSpan());
    }
}


问:
How to use an object of type class from an generic class as a parameter? - generics and reflection combined
I have two classes:

```<code>public abstract class MyAbstractSuperClass<A, B> {

    public MyAbstractSuperClass(Class<A> a, Class<B> b) {
        ...
    }

    ...
}

public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass<A>> {

    public MyClass(Class<A> a) {
    super(a, MyOtherClass.class));
            ...
    }

    ...
}
</code>```

Now you see, the subclass has to call the superclass's constructor. At that line I get the following error:

```<code>The constructor MySuperClass<A, MyOtherClass<A>>(Class<A>, Class<MyOtherClass>) is undefined
</code>```

So how do I get an object of type Class<MyOtherClass>?

And how do I do it in the super constructor call, where I can't execute much?

Thanks in advance.

答:
Remove the type parameter of MyOtherClass in the MyClass definition. You're apparently not interested in this anywhere in MyClass' body.

```<code>public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass> {
    public MyClass(Class<A> a) {
       super(a, MyOtherClass.class);
    }
}
</code>```

Add a @SuppressWarnings("rawtypes") if the warning bothers you.

Body:
I have two classes:

public abstract class MyAbstractSuperClass {

    public MyAbstractSuperClass(Class a, Class b) {
        ...
    }

    ...
}

public class MyClass extends MyAbstractSuperClass<A, MyOtherClass> {

    public MyClass(Class a) {
    super(a, MyOtherClass.class));
            ...
    }

    ...
}

Now you see, the subclass has to call the superclass's constructor. At that line I get the following error:

The constructor MySuperClass<A, MyOtherClass>(Class, Class<MyOtherClass>) is undefined

So how do I get an object of type Class<MyOtherClass>?

And how do I do it in the super constructor call, where I can't execute much?

Thanks in advance.

Body:
Remove the type parameter of MyOtherClass in the MyClass definition. You're apparently not interested in this anywhere in MyClass' body.

public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass> {
    public MyClass(Class<A> a) {
       super(a, MyOtherClass.class);
    }
}

Add a @SuppressWarnings("rawtypes") if the warning bothers you.