问:
How to mix objective-c and swift to make a cocoapods framework
I'm creating a swift framework and I want to used an objective-c class in the framework.

I used pod lib create frameworkName to create library.

It's my podspec file:

```<code>http://guides.cocoapods.org/syntax/podspec.html

Pod::Spec.new do |s|
s.name             = 'MyFramework'
s.version          = '0.1.0'
s.summary          = 'A short description of RadiantSensorsRSPOS.'

s.description      = <<-DESC
TODO: Add long description of the pod here.
                   DESC
s.license          = { :type => 'MIT', :file => 'LICENSE' }
s.ios.deployment_target = '8.0'

s.source_files = 'MyFramework/Classes/**/*'
s.public_header_files = 'Pod/Headers/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'CocoaAsyncSocket'
end
</code>```

I have objc.h and objc.m file that contain an Objc class. I have to use this Objc class in MyFramework.swift.

In Standard application (non framework) I made a header bridge and import the objc.h file, so I had access to Objc class.

How can I use the Objc class here?

Where should I put objc.h and objc.m file?

How to make header bridge here?

答:
I realize it may be a bit late to answer your question, but I recently had to do the same thing as you - create a cocoapod of a Swift Framework with some Objective C code mixed in it.

When you create a Swift-based framework in Xcode (8.2 or higher I used) it generates what is called an umbrella header file (.h) which is the same name as the target.  So if your framework target is called 'MyFrameworkTarget', the umbrella header that Xcode adds is called 'MyFrameworkTarget.h'.  It is important to include this header in your cocoapod, along with the other Swift and Objective C source code files.

As an example, here is a working podspec file which combines Swift and Objective C source files into a framework which targets both iOS and macOS:

```<code>Pod::Spec.new do |s|

s.name         = "MyFramework"
s.version      = "1.0.0"
s.summary      = "Example cocoapod spec for a mixed language framework"
s.description  = <<-DESC
  Example cocoapod spec for a mixed language framework that targets both iOS and macOS.
DESC

s.homepage     = "https://github.com/username/MyFramework"

s.license      = "Apache License, Version 2.0"

s.author       = { "My Name" => "info@code.myname.com" }

s.ios.deployment_target = "9.0"
s.osx.deployment_target = "10.11"

s.source       = { :git => "https://github.com/username/MyFramework.git", :tag => "#{s.version}" }

s.source_files       = 'Shared/*.{swift,h,m}'
s.ios.source_files   = 'MyFrameworkMobile/*.h'
s.osx.source_files   = 'MyFrameworkMac/*.h'

end
</code>```

In this particular example, I have the Swift and Objective C files that constitute the framework as built for both iOS and macOS in the folder 'Shared' and referenced in the podspec by 's.source_files'.  Then the framework umbrella files that Xcode generated and I edited for my two framework targets iOS (which I named MyFrameworkMobile) and macOS (which I named MyFrameworkMac) are referenced in 's.ios.source_files' and 's.osx.source_files', respectively.  In my example, they are separate for iOS and macOS because I have two targets.  The actual headers are in folders 'MyFrameworkMobile' and 'MyFrameworkMac'.

Here's my actual on-disk project folder layout to help visualize what the podspec is pointing to:

```<code>MyFramework.podspec
MyFramework.xcodeproj

MyFrameworkMac
  MyFrameworkMac.h
  Info.plist

MyFrameworkMobile
  MyFrameworkMobile.h
  Info.plist

Shared
  MyFramework.swift
  MyFramework.h
  MyFramework.m
</code>```

I hope this information helps.  There's a fine sample project that demos how to create a pod file for a mixed project of Swift and Objective C files on GitHub at https://github.com/axl411/NVMDummyTestPod

Body:
I'm creating a swift framework and I want to used an objective-c class in the framework.

I used pod lib create frameworkName to create library.

It's my podspec file:

http://guides.cocoapods.org/syntax/podspec.html

Pod::Spec.new do |s|
s.name             = 'MyFramework'
s.version          = '0.1.0'
s.summary          = 'A short description of RadiantSensorsRSPOS.'

s.description      = <<-DESC
TODO: Add long description of the pod here.
                   DESC
s.license          = { :type => 'MIT', :file => 'LICENSE' }
s.ios.deployment_target = '8.0'

s.source_files = 'MyFramework/Classes/**/*'
s.public_header_files = 'Pod/Headers/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'CocoaAsyncSocket'
end

I have objc.h and objc.m file that contain an Objc class. I have to use this Objc class in MyFramework.swift.

In Standard application (non framework) I made a header bridge and import the objc.h file, so I had access to Objc class.

How can I use the Objc class here?

Where should I put objc.h and objc.m file?

How to make header bridge here?

Body:
I realize it may be a bit late to answer your question, but I recently had to do the same thing as you - create a cocoapod of a Swift Framework with some Objective C code mixed in it.

When you create a Swift-based framework in Xcode (8.2 or higher I used) it generates what is called an umbrella header file (.h) which is the same name as the target.  So if your framework target is called 'MyFrameworkTarget', the umbrella header that Xcode adds is called 'MyFrameworkTarget.h'.  It is important to include this header in your cocoapod, along with the other Swift and Objective C source code files.

As an example, here is a working podspec file which combines Swift and Objective C source files into a framework which targets both iOS and macOS:

Pod::Spec.new do |s|

s.name         = "MyFramework"
s.version      = "1.0.0"
s.summary      = "Example cocoapod spec for a mixed language framework"
s.description  = <<-DESC
  Example cocoapod spec for a mixed language framework that targets both iOS and macOS.
DESC

s.homepage     = "https://github.com/username/MyFramework"

s.license      = "Apache License, Version 2.0"

s.author       = { "My Name" => "info@code.myname.com" }

s.ios.deployment_target = "9.0"
s.osx.deployment_target = "10.11"

s.source       = { :git => "https://github.com/username/MyFramework.git", :tag => "#{s.version}" }

s.source_files       = 'Shared/*.{swift,h,m}'
s.ios.source_files   = 'MyFrameworkMobile/*.h'
s.osx.source_files   = 'MyFrameworkMac/*.h'

end

In this particular example, I have the Swift and Objective C files that constitute the framework as built for both iOS and macOS in the folder 'Shared' and referenced in the podspec by 's.source_files'.  Then the framework umbrella files that Xcode generated and I edited for my two framework targets iOS (which I named MyFrameworkMobile) and macOS (which I named MyFrameworkMac) are referenced in 's.ios.source_files' and 's.osx.source_files', respectively.  In my example, they are separate for iOS and macOS because I have two targets.  The actual headers are in folders 'MyFrameworkMobile' and 'MyFrameworkMac'.

Here's my actual on-disk project folder layout to help visualize what the podspec is pointing to:

MyFramework.podspec
MyFramework.xcodeproj

MyFrameworkMac
  MyFrameworkMac.h
  Info.plist

MyFrameworkMobile
  MyFrameworkMobile.h
  Info.plist

Shared
  MyFramework.swift
  MyFramework.h
  MyFramework.m

I hope this information helps.  There's a fine sample project that demos how to create a pod file for a mixed project of Swift and Objective C files on GitHub at https://github.com/axl411/NVMDummyTestPod


来源: stackexchange

问:
Dynamically replacing HTML with getJSON by click of button
I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:

```<code>$(document).ready(function() {

$("#nav_list a").click(function(evt) {
    buildName = "../json_files/" + $(this).attr("title") + ".json";
    alert(buildName);
    document.getElementById("main").innerHTML = "";

    $.getJSON(buildName, function(data) {
        $.each(data, function() {
            $.each(this, function(key, value) {
                $("#main").append(
                    "<h1>" + value.title + "</h2>" +
                    "<img src='" + value.image + "'>" +
                    "<h2>" + value.month + "<br>" + value.speaker + "</h2>" +
                    "<p>" + value.text + "</p>";
                );
            }); // inner each
        }); // outer each
    )}; // end of getJSON

}); // end click

}); // end ready
</code>```

Notes:

The alert(buildName) is for my own testing.

The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.

Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).

I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:

```<code>        $.getJSON(buildName, function(data) {
            $.each(data, function(key, value) {
                $("#main").append(
                    ("#main h1").innerHTML.replace("<h1>" + value.title + "</h2>");
                    ("#main img").innerHTML.replace("<img src='" + value.image + "'>");
                    ("#main h2").innerHTML.replace("<h2>" + value.month + "<br>" + value.speaker + "</h2>");
                    ("#main p").innerHTML.replace("<p>" + value.text + "</p>");
                )
            }); // endeach
    )}; // end of getJSON
</code>```

What do you guys think? I am absolutely stumped.

答: Remove the semi-colon at the end inside your .append(). Otherwise, I'm not sure. I wanted to comment this instead of answering but I lack the reputation. With your second attempt, those replace calls shouldn't be made inside the .append(). Good luck!</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:

$(document).ready(function() {

$("#nav_list a").click(function(evt) {
    buildName = "../json_files/" + $(this).attr("title") + ".json";
    alert(buildName);
    document.getElementById("main").innerHTML = "";

    $.getJSON(buildName, function(data) {
        $.each(data, function() {
            $.each(this, function(key, value) {
                $("#main").append(
                    "
" + value.title + "
" +
                    "" +
                    "
" + value.month + "
" + value.speaker + "
" +
                    "
" + value.text + "
";
                );
            }); // inner each
        }); // outer each
    )}; // end of getJSON

}); // end click

}); // end ready

Notes:

The alert(buildName) is for my own testing.

The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.

Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).

I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:

        $.getJSON(buildName, function(data) {
            $.each(data, function(key, value) {
                $("#main").append(
                    ("#main h1").innerHTML.replace("
" + value.title + "
");
                    ("#main img").innerHTML.replace("");
                    ("#main h2").innerHTML.replace("
" + value.month + "
" + value.speaker + "
");
                    ("#main p").innerHTML.replace("
" + value.text + "
");
                )
            }); // endeach
    )}; // end of getJSON

What do you guys think? I am absolutely stumped.


问:
I want to insert a column inside a list of lists, the new column would be the 0th column python 3
Given:

```<code>rowTitle = ['Time','Conditions','Temperture (C)','Feels Like (C)','Wind (Km//h','Precipitation','Rain','Snow','Ice','Sky','UV Index','Cloud Cover','Humidity','Dew Point']

data = [['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['Cloudy', 'Snow', 'Snow', 'Cloudy', 'Snow', 'Flurries', 'Snow', 'Cloudy'], ['-1°', '-1°', '-1°', '-1°', '-1°', '-1°', '-2°', '-1°'], ['-7°', '-9°', '-10°', '-10°', '-11°', '-11°', '-13°', '-11°'], ['18 N', '20 N', '24 N', '26 N', '30 NNW', '32 NNW', '33 NNW', '35 NNW'], ['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['0%', '0%', '0%', '0%', '0%', '0%', '0%', '0%'], ['49%', '61%', '61%', '49%', '58%', '51%', '57%', '43%'], ['0%', '0%', '0%', '0%', '0%', '0%', '0%', '0%'], ['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['0', '0', '0', '0', '0', '0', '0', '0'], ['98%', '97%', '97%', '97%', '97%', '96%', '96%', '96%'], ['82%', '80%', '80%', '79%', '79%', '78%', '82%', '79%'], ['-3°', '-4°', '-4°', '-4°', '-4°', '-4°', '-4°', '-4°']]
</code>```

I want to add the list rowTitle into the List of Lists data. But the "row titles" should appear in the first (leftmost) column.

I tried using insert method in python to insert the column inside data[x][0] but its not working..

```<code>for i in data:
    print(data.insert([i][0], rowTitle[i]))
</code>```

This seems logical to me.. but i think I must be wrong.. other posts on here suggest Numpy as the way to do this.

Ultimately I will be making this into an HTML table to email myself, so I'd like the rows labeled.

答:
Ohmygod.. Pandas made it so easy!!!

All I had to do was write one line of code.

```<code>s = pd.Series(data, index = rowTitle)
</code>```

and I got:

```<code>Time                    [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
Conditions        [Mostly Sunny, Mostly Sunny, Mostly Clear, Mos...
Temperture (C)               [1°, 0°, -1°, -1°, -2°, -2°, -2°, -2°]
Feels Like (C)           [-7°, -8°, -9°, -9°, -10°, -10°, -9°, -9°]
Wind (Km//h       [28 N, 28 NNW, 28 NNW, 26 NNW, 24 NNW, 22 NNW,...
Precipitation           [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
Rain                               [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Snow                               [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Ice                                [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Sky                     [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
UV Index                                   [0, 0, 0, 0, 0, 0, 0, 0]
Cloud Cover                   [19%, 17%, 16%, 14%, 10%, 6%, 2%, 2%]
Humidity                   [62%, 66%, 74%, 77%, 80%, 81%, 80%, 81%]
Dew Point                  [-6°, -5°, -5°, -5°, -5°, -5°, -5°, -5°]
dtype: object
</code>```

Oh man.. I spent 6 hours the other night trying to figure out a nested for loop that would do this.

Now I just need to figure out how to put this all into HTML Table and email it to myself everyday. Cool!

Body:
Given:

rowTitle = ['Time','Conditions','Temperture (C)','Feels Like (C)','Wind (Km//h','Precipitation','Rain','Snow','Ice','Sky','UV Index','Cloud Cover','Humidity','Dew Point']

data = [['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['Cloudy', 'Snow', 'Snow', 'Cloudy', 'Snow', 'Flurries', 'Snow', 'Cloudy'], ['-1°', '-1°', '-1°', '-1°', '-1°', '-1°', '-2°', '-1°'], ['-7°', '-9°', '-10°', '-10°', '-11°', '-11°', '-13°', '-11°'], ['18 N', '20 N', '24 N', '26 N', '30 NNW', '32 NNW', '33 NNW', '35 NNW'], ['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['0%', '0%', '0%', '0%', '0%', '0%', '0%', '0%'], ['49%', '61%', '61%', '49%', '58%', '51%', '57%', '43%'], ['0%', '0%', '0%', '0%', '0%', '0%', '0%', '0%'], ['10pm', '11pm', '12am', '1am', '2am', '3am', '4am', '5am'], ['0', '0', '0', '0', '0', '0', '0', '0'], ['98%', '97%', '97%', '97%', '97%', '96%', '96%', '96%'], ['82%', '80%', '80%', '79%', '79%', '78%', '82%', '79%'], ['-3°', '-4°', '-4°', '-4°', '-4°', '-4°', '-4°', '-4°']]

I want to add the list rowTitle into the List of Lists data. But the "row titles" should appear in the first (leftmost) column.

I tried using insert method in python to insert the column inside data[x][0] but its not working..

for i in data:
    print(data.insert([i][0], rowTitle[i]))

This seems logical to me.. but i think I must be wrong.. other posts on here suggest Numpy as the way to do this.

Ultimately I will be making this into an HTML table to email myself, so I'd like the rows labeled.

Body:
Ohmygod.. Pandas made it so easy!!!

All I had to do was write one line of code.

s = pd.Series(data, index = rowTitle)

and I got:

Time                    [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
Conditions        [Mostly Sunny, Mostly Sunny, Mostly Clear, Mos...
Temperture (C)               [1°, 0°, -1°, -1°, -2°, -2°, -2°, -2°]
Feels Like (C)           [-7°, -8°, -9°, -9°, -10°, -10°, -9°, -9°]
Wind (Km//h       [28 N, 28 NNW, 28 NNW, 26 NNW, 24 NNW, 22 NNW,...
Precipitation           [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
Rain                               [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Snow                               [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Ice                                [0%, 0%, 0%, 0%, 0%, 0%, 0%, 0%]
Sky                     [6pm, 7pm, 8pm, 9pm, 10pm, 11pm, 12am, 1am]
UV Index                                   [0, 0, 0, 0, 0, 0, 0, 0]
Cloud Cover                   [19%, 17%, 16%, 14%, 10%, 6%, 2%, 2%]
Humidity                   [62%, 66%, 74%, 77%, 80%, 81%, 80%, 81%]
Dew Point                  [-6°, -5°, -5°, -5°, -5°, -5°, -5°, -5°]
dtype: object

Oh man.. I spent 6 hours the other night trying to figure out a nested for loop that would do this.

Now I just need to figure out how to put this all into HTML Table and email it to myself everyday. Cool!


问:
Regular Expression allow and forbid specific characters
I have a RegularExpression as follows:

```<code>RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-]*$", ...
</code>```

Is there any way to make it forbid double spaces, double dashes and dash-space/space-dash sequences? Also I need to check if the last character is alphanumeric or not.

text OK

text-text OK

text text OK

text--text NOT OK

text  text NOT OK

text- text NOT OK

text -text NOT OK

text NOT OK

-text NOT OK

text- NOT OK

text NOT OK

Thank you all I appreciate any tip.

答:
Change the regex to

```<code>^[a-zA-Z]+(?:[ -][a-zA-Z]+)?$
</code>```

See the regex demo

Details:

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

(?:[ -][a-zA-Z]+)? - one or zero sequences of:

[ -] - a space or -

[a-zA-Z]+ - 1 or more ASCII letters

$ - end of string.

NOTE:

If you just need to match any Unicode letter, replace the [a-zA-Z] in my pattern with \p{L}.

To check if a string is valid in C#, use var valid = Regex.IsMatch(s, @"^\p{L}+(?:[ -]\p{L}+)?$");.

So, based on what you posted, you may use

```<code>^\p{L}+(?:[ -]\p{L}+)?$
</code>```

See this regex demo

Body:
I have a RegularExpression as follows:

RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-]*$", ...

Is there any way to make it forbid double spaces, double dashes and dash-space/space-dash sequences? Also I need to check if the last character is alphanumeric or not.

text OK

text-text OK

text text OK

text--text NOT OK

text  text NOT OK

text- text NOT OK

text -text NOT OK

text NOT OK

-text NOT OK

text- NOT OK

text NOT OK

Thank you all I appreciate any tip.

Body:
Change the regex to

^[a-zA-Z]+(?:[ -][a-zA-Z]+)?$

See the regex demo

Details:

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

(?:[ -][a-zA-Z]+)? - one or zero sequences of:

[ -] - a space or -

[a-zA-Z]+ - 1 or more ASCII letters

$ - end of string.

NOTE:

If you just need to match any Unicode letter, replace the [a-zA-Z] in my pattern with \p{L}.

To check if a string is valid in C#, use var valid = Regex.IsMatch(s, @"^\p{L}+(?:[ -]\p{L}+)?$");.

So, based on what you posted, you may use

^\p{L}+(?:[ -]\p{L}+)?$

See this regex demo


问:
How do I concat a column's unique values in a group by for MySQL?
I know how to concat all the values for a field in a group by (see below), but I don't want repeated values. For example, if "Bob" did 5 actions of type "1" and also a type "2", I want only: 1,2, not 1,1,1,1,1,2.

However, the UNIQUE must not be on the total query because I still need the values of the other columns for those actions.

```<code>SELECT
  user.name,
  GROUP_CONCAT(type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;
</code>```

答:
Something like this.... do the first level of aggregation in a sub-query then do the concatenation on top of it.</p>

```<code>SELECT TMP.NAME
    , GROUP_CONCAT(TYPE SEPARATOR ',') AS TYPES
    , SUM(PRODUCED)
FROM (
    SELECT USER.NAME
        , TYPE
        , SUM(PRODUCED) PRODUCED
    FROM USER
    GROUP BY USER.NAME
        , TYPE
) TMP
GROUP BY TMP.NAME;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know how to concat all the values for a field in a group by (see below), but I don't want repeated values. For example, if "Bob" did 5 actions of type "1" and also a type "2", I want only: 1,2, not 1,1,1,1,1,2.

However, the UNIQUE must not be on the total query because I still need the values of the other columns for those actions.

SELECT
  user.name,
  GROUP_CONCAT(type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;

Body:
Something like this.... do the first level of aggregation in a sub-query then do the concatenation on top of it.

SELECT TMP.NAME
    , GROUP_CONCAT(TYPE SEPARATOR ',') AS TYPES
    , SUM(PRODUCED)
FROM (
    SELECT USER.NAME
        , TYPE
        , SUM(PRODUCED) PRODUCED
    FROM USER
    GROUP BY USER.NAME
        , TYPE
) TMP
GROUP BY TMP.NAME;


问:
How do I screen out NaNs when comparing floats in Ruby?
I'm using Rails 5 wiht Ruby 2.4.  How do I determine if a variable is a number?  I thought is_a?(Numeric) was the way to go, but apparently not with me.  I have this code

```<code>      puts "guesses arr: #{guesses_arr}"
      guesses_arr.map!{|str| str.is_a?(Numeric) && str == guesses_arr.max ? str : 0}
</code>```

which dies with

```<code>guesses arr: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
ArgumentError: comparison of Float with NaN failed
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `max'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `block (2 levels) in guess_headers_from_data_cols'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `map!'
</code>```

I'm unable to reproduce this in a console because I can't seem to produce an array with all those "NaN" values.  The point is, how do I make sure those don't get compared in my loop?

答:
You can get NaN by calling Float::NAN:

```<code>[7] pry(main)> Float::NAN
=> NaN
[8] pry(main)> Float::NAN.nan?
=> true
</code>```

If you just want to remove NaN:

guesses_arr.reject! { |x| x.nan? }

For example:

```<code>[4] pry(main)> [1.0, Float::NAN].reject(&:nan?)
=> [1.0]
</code>```

Body:
I'm using Rails 5 wiht Ruby 2.4.  How do I determine if a variable is a number?  I thought is_a?(Numeric) was the way to go, but apparently not with me.  I have this code

      puts "guesses arr: #{guesses_arr}"
      guesses_arr.map!{|str| str.is_a?(Numeric) && str == guesses_arr.max ? str : 0}

which dies with

guesses arr: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
ArgumentError: comparison of Float with NaN failed
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `max'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `block (2 levels) in guess_headers_from_data_cols'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `map!'

I'm unable to reproduce this in a console because I can't seem to produce an array with all those "NaN" values.  The point is, how do I make sure those don't get compared in my loop?

Body:
You can get NaN by calling Float::NAN:

[7] pry(main)> Float::NAN
=> NaN
[8] pry(main)> Float::NAN.nan?
=> true

If you just want to remove NaN:

guesses_arr.reject! { |x| x.nan? }

For example:

[4] pry(main)> [1.0, Float::NAN].reject(&:nan?)
=> [1.0]


问:
Is it possible in Node to read in a file an export its contents (without exporting asyncronly)?
TLDR: I want to read in a file's contents and then export a function which relies on those contents ... without making that exported function use promises or some other form of asynchronicity.

I'm trying to write an XML-validating module, and in order for it to do its thing I need to read in an XSD file.  However, this only needs to happen once at "load time", so ideally I'd rather not have other modules that use my function have to wait for a promise to resolve to get their results.  If I were using Webpack this would be easy, as I could use it's text file loader to bring in the XSD as if it were any other module ... but unfortunately I'm not.

In other words, currently I have to do (borderline pseudo-code):

```<code>module.exports.validate = () =>
   new Promise((resolve) =>
       fs.readFile(path, (file) => {
           // use file to validate, then:
           resolve(validationResult);
       });
   });
</code>```

};

and instead I'd like to do:

```<code>fs.readFile(path, (file) => {
   module.exports.validate = myValidationFunction;
});
</code>```

But the above doesn't work because you can't export from callbacks, so my question is, is there any other way to accomplish this?

The https://github.com/jonschlinkert/to-exports library seems to offer exactly this, so it seems like it's possible ... but it doesn't work for me :(

P.S. At worst I could literally wrap the contents of the file inside the template string characters, rename the file to be .js, and export it that way:

```<code>module.exports = `*XSD contents go here*`;
</code>```

However, that seems very kludgy, so I'm hoping there is a better way.

答: If you want to read a file synchronously, then use fs.readFileSync. It returns the contents of the file or throws an error.

Body:
TLDR: I want to read in a file's contents and then export a function which relies on those contents ... without making that exported function use promises or some other form of asynchronicity.

I'm trying to write an XML-validating module, and in order for it to do its thing I need to read in an XSD file.  However, this only needs to happen once at "load time", so ideally I'd rather not have other modules that use my function have to wait for a promise to resolve to get their results.  If I were using Webpack this would be easy, as I could use it's text file loader to bring in the XSD as if it were any other module ... but unfortunately I'm not.

In other words, currently I have to do (borderline pseudo-code):

module.exports.validate = () =>
   new Promise((resolve) =>
       fs.readFile(path, (file) => {
           // use file to validate, then:
           resolve(validationResult);
       });
   });

};

and instead I'd like to do:

fs.readFile(path, (file) => {
   module.exports.validate = myValidationFunction;
});

But the above doesn't work because you can't export from callbacks, so my question is, is there any other way to accomplish this?

The https://github.com/jonschlinkert/to-exports library seems to offer exactly this, so it seems like it's possible ... but it doesn't work for me :(

P.S. At worst I could literally wrap the contents of the file inside the template string characters, rename the file to be .js, and export it that way:

module.exports = `*XSD contents go here*`;

However, that seems very kludgy, so I'm hoping there is a better way.


问:
Cairo introspection errors in Eclipse with PyDev `TypeError: Couldn't find conversion for foreign struct 'cairo.Context'`
I am working on adding a printer interface to some home-brewed Python3 code with a Gtk3 UI, using (mostly) Eclipse Indigo with the PyDev plugin.

While developing the PrintOperation callbacks I found a problem where apparently the gi-introspection fails to find the right underlying library struct for the Cairo Context. The error reported in the console is:

```<code>Traceback (most recent call last):
  File "/home/bob/Projects/MovieList/src/MovieList/MovieListIO.py", line 203, in on_printDialog_draw_page
    cr = context.get_cairo_context()
  File "/usr/lib/python3/dist-packages/gi/types.py", line 43, in function
    return info.invoke(*args, **kwargs)
TypeError: Couldn't find conversion for foreign struct 'cairo.Context'
</code>```

At first I thought this was something to do with Eclipse and/or PyDev, because I could run the program within Idle without any error messages. But then I found that when the program was packaged for deployment with the built-in command-line Python tools, the installed version also gave the error. So, I wrote a couple of test scripts abstracting the printer functionality to try to isolate what was going on. In both cases, the key line is in the on_printOperation_draw_page() callback (marked with comments).

Here is the first test script (Script 1, printTestPdf.py), which loads a pdf file using Poppler, and prints it using the system print dialog:

```<code>#!/usr/bin/env python3
import os
from gi.repository import Gtk, Poppler

testFile = 'file://' + os.path.join(os.getcwd(), 'printTestPdf.pdf')
pdfDocument = Poppler.Document.new_from_file(testFile, None)

class Example(Gtk.Window):
    def __init__(self):
        super(Example, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.set_title("Print Pdf Test")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)
        printButton = Gtk.Button('Press Me')
        self.add(printButton)
        printButton.connect('clicked', self.on_printButton_clicked)
        self.show_all()

    def on_printButton_clicked(self, widget):
        """
        Handler for the button click.
        """
        printOperation = Gtk.PrintOperation()
        printOperation.connect('draw-page', self.on_printOperation_draw_page)
        printOperation.set_job_name('Print Pdf Test')
        printOperation.set_n_pages(pdfDocument.get_n_pages())
        printOperation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
                           parent=self)

    def on_printOperation_draw_page(self, printOperation, context, pageNo):
        """
        Handler for the draw-page signal from the printOperation.
        """
        cr = context.get_cairo_context() # <-- THIS IS THE LINE
        page = pdfDocument.get_page(pageNo)
        page.render_for_printing(cr)

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()
</code>```

This is the second script (Script 2, printTestHtml.py), which is almost identical, except it loads an HTML file for printing using weasyprint:

```<code>#!/usr/bin/env python3

import os
from gi.repository import Gtk
from weasyprint import HTML

testFile = os.path.join(os.getcwd(), 'printTestHtml.html')
pdfDocument = HTML(filename=testFile).render()

class Example(Gtk.Window):
    def __init__(self):
        super(Example, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.set_title("Print Html Test")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)
        printButton = Gtk.Button('Press Me')
        self.add(printButton)
        printButton.connect('clicked', self.on_printButton_clicked)
        self.show_all()

    def on_printButton_clicked(self, widget):
        """
        Handler for the button click.
        """
        printOperation = Gtk.PrintOperation()
        printOperation.connect('begin-print', self.on_printOperation_begin_print)
        printOperation.connect('draw-page', self.on_printOperation_draw_page)
        printOperation.set_job_name('Print HTML Test')
        printOperation.set_n_pages(len(pdfDocument.pages))
        printOperation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
                           parent=self)

    def on_printOperation_draw_page(self, printOperation, context, pageNo):
        """
        Handler for the draw-page signal from the printOperation.
        """
        cr = context.get_cairo_context() # <-- THIS IS THE LINE
        page = pdfDocument.pages[pageNo]
        page.paint(cr) # <-- there is a separate issue here

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()
</code>```

Both scripts generate an internal pdf document, which is used to render each page on request via the PrintOperation draw_page callback.

Now, whether and how the scripts succeed or fail depends on the context in which they are run. Script 1 always works, except if it is run after a failure of Script 2 in Idle. Script 2 always generates the error message as reported above when run in Eclipse. In Idle, Script 2's behaviour is complex. Sometimes it fails due to a second problem (marked), and does not exhibit the first failure. However, for reasons I have yet to establish, every so often it generates the original error, and when it does, it keeps doing it and Script 1 show the error too, until Idle is re-booted. Running directly from the command line matches the behaviour in Eclipse. I have tried to summarise this behaviour below:

```<code>*   Eclipse
    -   Script 1: Always OK
    -   Script 2: Always Fails
*   Command line
    -   Script 1: Always OK
    -   Script 2: Always Fails
*   Idle
    -   Script 1: OK, except after failure of Script 2
    -   Script 2: Intermittent Fail. Knock-on to future runs (up to next error)
</code>```

This pattern of failure may help determine what the root problem is, but it is beyond me to understand it.

Ignoring the bizarre behaviour in Idle, it is possible the difference between Script 1 and Script 2 holds a clue to my original problem. Why does Script 1 run successfully, while Script 2 generates the introspection error?

If you can offer any suggestions as to what is going wrong I would be most grateful. If you can come up with a solution I will be delighted!

答:
Just in case it helps I was looking for a solution to the cairo error.

Had this cairo error happen on my RPi3 with Pandas and Matplotlib. The plot window was showing up blank.
I had to run sudo apt-get install python-gobject-cairo
Based on this: https://github.com/rbgirshick/py-faster-rcnn/issues/221

Body:
I am working on adding a printer interface to some home-brewed Python3 code with a Gtk3 UI, using (mostly) Eclipse Indigo with the PyDev plugin.

While developing the PrintOperation callbacks I found a problem where apparently the gi-introspection fails to find the right underlying library struct for the Cairo Context. The error reported in the console is:

Traceback (most recent call last):
  File "/home/bob/Projects/MovieList/src/MovieList/MovieListIO.py", line 203, in on_printDialog_draw_page
    cr = context.get_cairo_context()
  File "/usr/lib/python3/dist-packages/gi/types.py", line 43, in function
    return info.invoke(*args, **kwargs)
TypeError: Couldn't find conversion for foreign struct 'cairo.Context'

At first I thought this was something to do with Eclipse and/or PyDev, because I could run the program within Idle without any error messages. But then I found that when the program was packaged for deployment with the built-in command-line Python tools, the installed version also gave the error. So, I wrote a couple of test scripts abstracting the printer functionality to try to isolate what was going on. In both cases, the key line is in the on_printOperation_draw_page() callback (marked with comments).

Here is the first test script (Script 1, printTestPdf.py), which loads a pdf file using Poppler, and prints it using the system print dialog:

#!/usr/bin/env python3
import os
from gi.repository import Gtk, Poppler

testFile = 'file://' + os.path.join(os.getcwd(), 'printTestPdf.pdf')
pdfDocument = Poppler.Document.new_from_file(testFile, None)

class Example(Gtk.Window):
    def __init__(self):
        super(Example, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.set_title("Print Pdf Test")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)
        printButton = Gtk.Button('Press Me')
        self.add(printButton)
        printButton.connect('clicked', self.on_printButton_clicked)
        self.show_all()

    def on_printButton_clicked(self, widget):
        """
        Handler for the button click.
        """
        printOperation = Gtk.PrintOperation()
        printOperation.connect('draw-page', self.on_printOperation_draw_page)
        printOperation.set_job_name('Print Pdf Test')
        printOperation.set_n_pages(pdfDocument.get_n_pages())
        printOperation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
                           parent=self)

    def on_printOperation_draw_page(self, printOperation, context, pageNo):
        """
        Handler for the draw-page signal from the printOperation.
        """
        cr = context.get_cairo_context() # <-- THIS IS THE LINE
        page = pdfDocument.get_page(pageNo)
        page.render_for_printing(cr)

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()

This is the second script (Script 2, printTestHtml.py), which is almost identical, except it loads an HTML file for printing using weasyprint:

#!/usr/bin/env python3

import os
from gi.repository import Gtk
from weasyprint import HTML

testFile = os.path.join(os.getcwd(), 'printTestHtml.html')
pdfDocument = HTML(filename=testFile).render()

class Example(Gtk.Window):
    def __init__(self):
        super(Example, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.set_title("Print Html Test")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)
        printButton = Gtk.Button('Press Me')
        self.add(printButton)
        printButton.connect('clicked', self.on_printButton_clicked)
        self.show_all()

    def on_printButton_clicked(self, widget):
        """
        Handler for the button click.
        """
        printOperation = Gtk.PrintOperation()
        printOperation.connect('begin-print', self.on_printOperation_begin_print)
        printOperation.connect('draw-page', self.on_printOperation_draw_page)
        printOperation.set_job_name('Print HTML Test')
        printOperation.set_n_pages(len(pdfDocument.pages))
        printOperation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
                           parent=self)

    def on_printOperation_draw_page(self, printOperation, context, pageNo):
        """
        Handler for the draw-page signal from the printOperation.
        """
        cr = context.get_cairo_context() # <-- THIS IS THE LINE
        page = pdfDocument.pages[pageNo]
        page.paint(cr) # <-- there is a separate issue here

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()

Both scripts generate an internal pdf document, which is used to render each page on request via the PrintOperation draw_page callback.

Now, whether and how the scripts succeed or fail depends on the context in which they are run. Script 1 always works, except if it is run after a failure of Script 2 in Idle. Script 2 always generates the error message as reported above when run in Eclipse. In Idle, Script 2's behaviour is complex. Sometimes it fails due to a second problem (marked), and does not exhibit the first failure. However, for reasons I have yet to establish, every so often it generates the original error, and when it does, it keeps doing it and Script 1 show the error too, until Idle is re-booted. Running directly from the command line matches the behaviour in Eclipse. I have tried to summarise this behaviour below:

*   Eclipse
    -   Script 1: Always OK
    -   Script 2: Always Fails
*   Command line
    -   Script 1: Always OK
    -   Script 2: Always Fails
*   Idle
    -   Script 1: OK, except after failure of Script 2
    -   Script 2: Intermittent Fail. Knock-on to future runs (up to next error)

This pattern of failure may help determine what the root problem is, but it is beyond me to understand it.

Ignoring the bizarre behaviour in Idle, it is possible the difference between Script 1 and Script 2 holds a clue to my original problem. Why does Script 1 run successfully, while Script 2 generates the introspection error?

If you can offer any suggestions as to what is going wrong I would be most grateful. If you can come up with a solution I will be delighted!


问:
Should self generated transaction ids be exchanged in HTTP synchronous requests
I am new to the HTTP world. My sincere apologies if the question is too trivial.

I created a HTTP client which send a SOAP message to a 3rd party server. My client sends a synchronous request and has a timeout value of 15 seconds. The API is used to update user balance, so it is very critical. I send the userId in the SOAP request and amount to be added/deducted from user balance to the server. The server responds with Status of 0=SUCCESS or 1=FAILURE

Now considering that multiple failures can occur at server and I might hit the server multiple times for the same user in a day, should there be a transaction id added in the message part. If yes, what would be the use cases for it. As per my understanding, client would always know which transaction it initiated, so it can do the transaction bookkeeping on its own. I would also need to reconcile the transactions with the server on daily basis (which could happen using userId).

Note: Server APIs are being developed and can change right now.

答:
First of all, use HTTPS not HTTP for anything sensitive.

Next, it sounds like your Client is persistent (i.e. not a browser).  In this case it would be useful to return a Transaction ID from the Server which the Client can store, and as you say this facilitates daily audits. This is probably useful because for the Audit request the Server can return a set of Transaction IDs which you can check, in addition to other data.


问:
https, a subdomain and an iframe: Any alternative to purchasing an additional SSL certificate?
I have a website example.com and an SSL certificate for this domain only. No subdomains except www are included. The site is based on Typo3.

On example.com/map is an iframe (note the subdomain):

```<code><iframe src=„https://map.example.com“ width="400" height="300">
</code>```

This doesn’t work with all browsers. Some browsers show an error (SSL_ERROR_BAD_CERT_DOMAIN) because the subdomain is not covered by the certificate.

The subdomain contains rather complex content which I wouldn’t know how to built in Typo3, that’s why I used an iframe.

Question:

Is there any way to insert the contents of map.example.com into the page example.com/map without purchasing an additional SSL certificate for the subdomain?

Thanks

Pida

答:
I see the following solutions:

Get a certificate for map.example.com

Buy one

Use an ACME client, for example Let's Encrypt

Link: Instead of using an iFrame just link to the site map.example.com

Set up a reverse proxy

Server side include: Write an extension for the website example.com/map which includes the content from map.example.com

Rebuild the solution as TYPO3 extension

It is difficult to say which one fits best for you.

A server side include may be easy in some cases, but in most cases it requires a lot of search an replace for the content which is going to be pasted. It also requires to include asset files (images, javascript, css) either in the TYPO3 template or dynamically by parsing the whole include content.

A reverse proxy is easy to set up in case you have the required software components already installed an the required knowledge. Otherwise it requires some reading and some hours to set up.

Body:
I have a website example.com and an SSL certificate for this domain only. No subdomains except www are included. The site is based on Typo3.

On example.com/map is an iframe (note the subdomain):

This doesn’t work with all browsers. Some browsers show an error (SSL_ERROR_BAD_CERT_DOMAIN) because the subdomain is not covered by the certificate.

The subdomain contains rather complex content which I wouldn’t know how to built in Typo3, that’s why I used an iframe.

Question:

Is there any way to insert the contents of map.example.com into the page example.com/map without purchasing an additional SSL certificate for the subdomain?

Thanks

Pida


问:
how to hide user credentials in http headers - angular2 application
i have an angular 2 application . It depends entirely on http calls. This application gets triggered from a main application and gets user id through url. It doesn't have it's login page. To protect all the http calls i need to send an id and password in http headers. The only way i can get these details is to save this sensitive information in a local json config file and get it through http call before making any http call which is not protected. If some one looks at the network they can easily see the id and password in response. Everything we save in front end can be accessed some or the other way. How to hide the id and password from user ? any suggestions ?</p>

答: As a general rule, if you want to protect the content of your http requests (and responses) from prying eyes, you should use https</p>


问:
Using 'Lock' in web applications
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

```<code>lock(HitCounter)
{
   // Bla...
}
</code>```

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?

答:
There is no special reason why locks should not be used in web applications. However, they should be used carefully as they are a mechanism to serialize multi-threaded access which can cause blocking if lock blocks are contended. This is not just a concern for web applications though.

What is always worth remembering is that on modern hardware an uncontended lock takes 20 nanoseconds to flip. With this in mind, the usual practice of trying to make code inside of lock blocks as minimal as possible should be followed. If you have minimal code within a block, the overhead is quite small and potential for contention low.

To say that locks should never be used is a bit of a blanket statement really. It really depends on what your requirements are e.g. a thread-safe in-memory cache to be shared between requests will potentially result in less request blocking than on-demand fetching from a database.

Finally, BCL and ASP.Net Framework types certainly use locks internally, so you're indirectly using them anyway.

ContentLicense: CC BY-SA 2.5

Title: Using 'Lock' in web applications

Body:
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
   // Bla...
}

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?


问:
I would like to parse csv by ruby to create a report
I have a csv report with two rows which has headers of "Date" & "Customer_name":

```<code>["Date", "Customer_Name"]
["Monday", "John"]
["", "David"]
["", "Sam"]
["", "Kenny"]
["Tuesday", "Mary"]
["", "Jade"]
["", "Lindsay"]
["Wednesday", "Tom"]
["", "Lindon"]
["", "Peter"]
</code>```

I am trying to print out a statement to show who is the customer for that day so it would show up like this: Monday has customers John, David, Sam, & Kenny.
\n
Tuesday has Mary, Jade and Lindsay

and my code is:

```<code>require 'csv'

col_date = []
col_name = []
custDate = CSV.foreach("customerVisit.csv") {|row| col_date << row[0]}
customer_name = CSV.foreach("customerVisit.csv") {|row| col_name << row[1]}

print "#{col_date} has customers #{col_name} visited the store."
</code>```

But I am not getting the correct output and most likely iam new to programming.. Please help on how I should achieve the requirement?

["Date", "Monday", nil, nil, nil, "Tuesday", nil, nil, "Wednesday", nil, nil] has customers ["Customer_Name", "John", "David", "Sam", "Kenny", "Mary", "Jade", "Lindsay", "Tom", "Lindon", "Peter"] visited the store.C02S51D2G8WL:RubySQL

Regards

答:
The reason for your result can be found here "#{array}", it inserts the array 'as is' into the string. So you get each set in chunks.

I suspect you are using the wrong tool for the job. A ruby hash is better for categorizing data. (This time at least)

For example

```<code>require 'csv'
customer_hash = {} # {"Date" => "Customers"}

temp = ""
CSV.foreach("customerVisit.csv") { |date, customer|
    temp = date if date
    customer_hash[temp] = [] unless customer_hash[temp]
    customer_hash[temp] << customer
}

customer_hash.each { |date, customers|
    print "#{date} has customers"
    customers.each { |name| print ", #{name}" }
    print "\nvisiting the store.\n"
}
</code>```

This should output all the customers after the day they are associated with.

I'm away from home and unable to run this, I hope it works as intended >_<.

Edited code due to miss-reading your data sample.

Body:
I have a csv report with two rows which has headers of "Date" & "Customer_name":

["Date", "Customer_Name"]
["Monday", "John"]
["", "David"]
["", "Sam"]
["", "Kenny"]
["Tuesday", "Mary"]
["", "Jade"]
["", "Lindsay"]
["Wednesday", "Tom"]
["", "Lindon"]
["", "Peter"]

I am trying to print out a statement to show who is the customer for that day so it would show up like this: Monday has customers John, David, Sam, & Kenny.
\n
Tuesday has Mary, Jade and Lindsay

and my code is:

require 'csv'

col_date = []
col_name = []
custDate = CSV.foreach("customerVisit.csv") {|row| col_date << row[0]}
customer_name = CSV.foreach("customerVisit.csv") {|row| col_name << row[1]}

print "#{col_date} has customers #{col_name} visited the store."

But I am not getting the correct output and most likely iam new to programming.. Please help on how I should achieve the requirement?

["Date", "Monday", nil, nil, nil, "Tuesday", nil, nil, "Wednesday", nil, nil] has customers ["Customer_Name", "John", "David", "Sam", "Kenny", "Mary", "Jade", "Lindsay", "Tom", "Lindon", "Peter"] visited the store.C02S51D2G8WL:RubySQL

Regards

Body:
The reason for your result can be found here "#{array}", it inserts the array 'as is' into the string. So you get each set in chunks.

I suspect you are using the wrong tool for the job. A ruby hash is better for categorizing data. (This time at least)

For example

require 'csv'
customer_hash = {} # {"Date" => "Customers"}

temp = ""
CSV.foreach("customerVisit.csv") { |date, customer|
    temp = date if date
    customer_hash[temp] = [] unless customer_hash[temp]
    customer_hash[temp] << customer
}

customer_hash.each { |date, customers|
    print "#{date} has customers"
    customers.each { |name| print ", #{name}" }
    print "\nvisiting the store.\n"
}

This should output all the customers after the day they are associated with.

I'm away from home and unable to run this, I hope it works as intended >_<.

Edited code due to miss-reading your data sample.


问:
Create group ID for runs of non-zero values
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

```<code>   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3
</code>```

答:
Another possibility:</p>

```<code>ifelse(value != 0,
       cumsum(value != 0 & dplyr::lag(value) %in% c(0, NA)),
       NA)

# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
</code>```

Body:
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3

Body:
Another possibility:

ifelse(value != 0,
       cumsum(value != 0 & dplyr::lag(value) %in% c(0, NA)),
       NA)

# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3


问:
i want to count occurrence of each word in a given sentence in java
beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
           Output : chair :2,
                    is :1,
                    equal :2,
                    to :2,
                    but :1,
                    not :1,
                    table :1 )
I have written some part of the code and tried using for loop but i failed....

```<code>public static void main(String[] args)
{
            int counter = 0;
   String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

   String[] b =a.split(" "); //stored in array and splitted

 for(int i=0;i<b.length;i++)
 {
     counter=0;
     for(int j<b.length;j>0;j--)
     {
         if(b[i] = b[j])
          //

     }
 }
}
</code>```

}

答: A simple (but not very efficient) way would be to add all the elements to a set, which doesn't allow duplicates. See How to efficiently remove duplicates from an array without using Set. Then iterate through the set and count the number of occurrences in your array, printing out the answer after each set element you check.</p>

Body:
beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
           Output : chair :2,
                    is :1,
                    equal :2,
                    to :2,
                    but :1,
                    not :1,
                    table :1 )
I have written some part of the code and tried using for loop but i failed....

public static void main(String[] args)
{
            int counter = 0;
   String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

   String[] b =a.split(" "); //stored in array and splitted

 for(int i=0;i<b.length;i++)
 {
     counter=0;
     for(int j0;j--)
     {
         if(b[i] = b[j])
          //

     }
 }
}

}


问:
Algorithm for incomplete ranking with imprecise comparisons

SUMMARY

I'm looking for an algorithm to rank objects. Two objects can be compared. However, the comparisons are real world comparisons that may be flawed. Also, I care more about finding out the very best object than which ones are the worst.

TO MOTIVATE:

Think that I'm scientifically evaluating materials. I combine two materials. I want to find the best working material for in-depth testing. So, I don't care about materials that are unpromising. However, each test can be a false positive or have anomalies between those particular two materials.

PRECISE PROBLEM:

There is an unlimited pool of objects.

Two objects can be compared to each other. It is resource expensive to compare two objects.

It's resource expensive to consider an additional object. So, an object should only be included in the evaluation if it can be fully ranked.

It is very important to find the very best object  in the pool of the tested ones. If an object is in the bottom half, it doesn't matter to find out where in the bottom half it is. The importance of finding out the exact rank is a gradient with the top much more important.

Most of the time, if A > B and B > C, it is safe to assume that A > C. Sometimes, there are false positives. Sometimes A > B and B > C and C > A. This is not an abstract math space but real world measurements.

At the start, it is not known how many comparisons are allowed to be taken. The algorithm is granted permission to do another comparison until it isn't. Thus, the decision on including an additional object or testing more already tested objects has to be made.

TO MOTIVATE MORE IN-DEPTH:

Imagine that you are tasked with hiring a team of boxers. You know nothing about evaluating boxers but can ask two boxers to fight each other. There is an unlimited number of boxers in the world. But it's expensive to fly them in. Ideally, you want to hire the n best boxers. Realistically, you don't know if the boxers are going to accept your offer. Plus, you don't know how competitively the other boxing clubs bid. You are going to make offers to only the best n boxers, but have to be prepared to know which next n boxers to send offers to. That you only get the worst boxers is very unlikely.

SOME APPROACHES

I could think of the following approaches. However, they all have drawbacks. I feel like there should be a much better approach.

USE TRADITIONAL SORTING ALGORITHMS

Traditional sorting algorithms could be used.

Drawback:
 - A false positive could serious throw of the correctness of the algorithm.
 - A sorting algorithm would spend half the time sorting the bottom half of the pack, which is unimportant.
 - Sorting algorithms start with all items. With this problem, we are allowed to do the first test, not knowing if we are allowed to do a second test. We may end up only being allowed to do two test. Or we may be allowed to do a million tests.

USE TOURNAMENT ALGORITHMS
There are algorithms for tournaments. E.g., everyone gets a first match. The winner of the first match moves on to the next round. There is a variety of tournament strategies that accounts for people having a bad day or being paired with the champion in their first match.

Drawback:
 - This seems pretty promising. The difficulty is to find one that allows adding one more player at a time as we are allowed more comparisons. It seems that there should be a highly specialized solution that's better than a standard tournament algorithm.

BINARY SEARCH
We could start with two objects. Each time an object is added, we could use a binary search to find its spot in the ranking. Because the top is more important, we could use a weighted binary search. E.g. instead of testing the mid point, it tests the point at the top 1/3.

Drawback:
 - The algorithm doesn't correct for false positives. If there is a false positive at the top early on, it could skew the whole rest of the tests.

COUNT WINS AND LOSSES
The wins and losses could be counted. The algorithm would choose test subjects by a priority of the least losses and second priority of the most wins. This would focus on testing the best objects. If an object has zero losses, it would get the focus of the testing. It would either quickly get a loss and drop in priority, or it would get a lot more tests because it's the likely top candidate.

DRAWBACK:
 - The approach is very nice in that it corrects for false positives. It also allows adding more objects to the test pool easily. However, it does not consider that a win against a top object counts a lot more than a win against a bottom object. Thus, comparisons are wasted.

GRAPH
All the objects could be added to a graph. The graph could be flattened.

DRAWBACK:
 - I don't know how to flatten such a messy graph that could have cycles and ambiguous end nodes. There could be multiple objects that are undefeated. How would one pick a winner in such a messy graph? How would one know which comparison would be the most valuable?

SCORING
As a win depends on the rank of the loser, a win could be given a score. Say A > B, means that A gets 1 point. if C > A, C gets 2 points because A has 1 point. In the end, objects are ranked by how many points they have.

DRAWBACK
 - The approach seems promising in that it is easy to add new objects to the pool of tested objects. It also takes into account that wins against top objects should count for more. I can't think of a good way to determine the points. That first comparison, was awarded 1 point. Once 10,000 objects are in the pool, an average win would be worth 5,000 points. The award of both tests should be roughly equal. Later comparisons overpower the earlier comparisons and make them be ignored when they shouldn't.

Does anyone have a good idea on tackling this problem?

答:
I would search for an easily computable value for an object, that could be compared between objects to give a good enough approximation of order. You could compare each new object with the current best accurately, then insertion sort the loser into a list of the rest using its computed value.

The best will always be accurate. The ordering of the rest depending on your "value".


问:
Angular 2 app is very slow on android devices
I have built an angular 2 app using the angular seed project. But the application is very slow on android devices. I am using lazy loading. For testing purpose I disabled all the pages and kept only the 404 page . But just the 404 page is also take 9 sec to see the page. Please can anyone help me optimize the loading time. I am attaching the screen shot below of the production build.
In the network there are lot of breaks. I don't know why that is happening

答:
I was analysis my angular project and I noticed that using require() makes the app slow on android devices .
In order to make my app size small i have used used systemjs to load libraries later (example datepicker ,moment etc) in my components

```<code>var moment = require('moment-timezone');

declare var moment:any;
@Component({
    moduleId: module.id,
    selector: "timezone",
    templateUrl: "timeZone.component.html"
})

export class TimeZoneComponent implements OnInit {
</code>```

But Loading the module containing this component is taking time .

Secondly lazy loading a module is also taking time to load the app. After the spinner stops loading there is a delay till the module is lazy loading.

```<code> { path: 'home', loadChildren: './app/core/publicPage/publicPage.module#PublicPageModule' },
</code>```

Making the above changes the app loads on android devices in 13 sec other than previous 22 sec .(Which is still not good enough but much better)

I don't know if this is an issue with systemjs on android devices. Has any one faced this simlar issue with system js ?

Body:
I was analysis my angular project and I noticed that using require() makes the app slow on android devices .
In order to make my app size small i have used used systemjs to load libraries later (example datepicker ,moment etc) in my components

var moment = require('moment-timezone');

declare var moment:any;
@Component({
    moduleId: module.id,
    selector: "timezone",
    templateUrl: "timeZone.component.html"
})

export class TimeZoneComponent implements OnInit {

But Loading the module containing this component is taking time .

Secondly lazy loading a module is also taking time to load the app. After the spinner stops loading there is a delay till the module is lazy loading.

 { path: 'home', loadChildren: './app/core/publicPage/publicPage.module#PublicPageModule' },

Making the above changes the app loads on android devices in 13 sec other than previous 22 sec .(Which is still not good enough but much better)

I don't know if this is an issue with systemjs on android devices. Has any one faced this simlar issue with system js ?


问:
Name of a constant given its value
How do you get the name of a constant given its value ?

More specifically (and to get a more readable understanding), I'm working with the crypto/tls package. Cipher suites are defined as constants:

```<code>const (
    TLS_RSA_WITH_RC4_128_SHA            uint16 = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       uint16 = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        uint16 = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        uint16 = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      uint16 = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  uint16 = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  uint16 = 0xc014
)
</code>```

After a successful handshake with a server, I can get to the Ciphersuite agreed on through the connection:

```<code>c, _ := tls.Dial("tcp", "somedomain.com:443", nil)
// Suppose everything went right

// This is the Ciphersuite for the conn:
cipher := c.ConnectionState().Ciphersuite
</code>```

cipher here is an uint16. Is there a way to display it as a string, for instance TLS_RSA_WITH_3DES_EDE_CBC_SHA if that's what was agreed upon ?

答:
You can use go generate to have this generated for you.

Install stringer using

```<code>go get golang.org/x/tools/cmd/stringer
</code>```

Now define a type for your const. You can do it like this

```<code>type TLSType uint16
const (
    TLS_RSA_WITH_RC4_128_SHA            TLSType = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       TLSType = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        TLSType = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        TLSType = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      TLSType = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA TLSType = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  TLSType = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  TLSType = 0xc014
)
</code>```

Then add this line to your file (spacing is important)

```<code>//go:generate stringer -type=TLSType
</code>```

Now go to the terminal in the folder where your program is and run

```<code>go generate
</code>```

This will create a file called tlstype_string.go in your code directory, which is the generated code that implements the fmt.Stringer interface for your TLSType. Open it if you want to see the implementation but you don't need to. It will just work.

Now when you run go build or go run *.go on this directory, your source files will use the generated code.

The full program would look something like this

```<code>package main

import (
    "fmt"
)

//go:generate stringer -type=TLSType
type TLSType uint16

const (
    TLS_RSA_WITH_RC4_128_SHA            TLSType = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       TLSType = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        TLSType = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        TLSType = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      TLSType = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA TLSType = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  TLSType = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  TLSType = 0xc014
)

func main() {
    fmt.Println("This const will be printed with its name instead of its number:")
    fmt.Println(TLS_RSA_WITH_RC4_128_SHA)
    fmt.Println()
    fmt.Println("So will this one:")
    fmt.Println(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA)
    fmt.Println()
    fmt.Println("Or maybe we want to give it a value and convert:")
    fmt.Println(TLSType(0xc011))
    fmt.Println()
    fmt.Println("No problem:")
    fmt.Println(TLSType(0xc013))
}
</code>```

Which outputs

```<code>This const will be printed with its name instead of its number:
TLS_RSA_WITH_RC4_128_SHA

So will this one:
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA

Or maybe we want to give it a value and convert:
TLS_ECDHE_RSA_WITH_RC4_128_SHA

No problem:
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
</code>```

If you add new const values, just run go generate again to update the generated code.

Title: Name of a constant given its value

Body:
How do you get the name of a constant given its value ?

More specifically (and to get a more readable understanding), I'm working with the crypto/tls package. Cipher suites are defined as constants:

const (
    TLS_RSA_WITH_RC4_128_SHA            uint16 = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       uint16 = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        uint16 = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        uint16 = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      uint16 = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  uint16 = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  uint16 = 0xc014
)

After a successful handshake with a server, I can get to the Ciphersuite agreed on through the connection:

c, _ := tls.Dial("tcp", "somedomain.com:443", nil)
// Suppose everything went right

// This is the Ciphersuite for the conn:
cipher := c.ConnectionState().Ciphersuite

cipher here is an uint16. Is there a way to display it as a string, for instance TLS_RSA_WITH_3DES_EDE_CBC_SHA if that's what was agreed upon ?

Body:
You can use go generate to have this generated for you.

Install stringer using

go get golang.org/x/tools/cmd/stringer

Now define a type for your const. You can do it like this

type TLSType uint16
const (
    TLS_RSA_WITH_RC4_128_SHA            TLSType = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       TLSType = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        TLSType = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        TLSType = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      TLSType = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA TLSType = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  TLSType = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  TLSType = 0xc014
)

Then add this line to your file (spacing is important)

//go:generate stringer -type=TLSType

Now go to the terminal in the folder where your program is and run

go generate

This will create a file called tlstype_string.go in your code directory, which is the generated code that implements the fmt.Stringer interface for your TLSType. Open it if you want to see the implementation but you don't need to. It will just work.

Now when you run go build or go run *.go on this directory, your source files will use the generated code.

The full program would look something like this

package main

import (
    "fmt"
)

//go:generate stringer -type=TLSType
type TLSType uint16

const (
    TLS_RSA_WITH_RC4_128_SHA            TLSType = 0x0005
    TLS_RSA_WITH_3DES_EDE_CBC_SHA       TLSType = 0x000a
    TLS_RSA_WITH_AES_128_CBC_SHA        TLSType = 0x002f
    TLS_RSA_WITH_AES_256_CBC_SHA        TLSType = 0x0035
    TLS_ECDHE_RSA_WITH_RC4_128_SHA      TLSType = 0xc011
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA TLSType = 0xc012
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA  TLSType = 0xc013
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA  TLSType = 0xc014
)

func main() {
    fmt.Println("This const will be printed with its name instead of its number:")
    fmt.Println(TLS_RSA_WITH_RC4_128_SHA)
    fmt.Println()
    fmt.Println("So will this one:")
    fmt.Println(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA)
    fmt.Println()
    fmt.Println("Or maybe we want to give it a value and convert:")
    fmt.Println(TLSType(0xc011))
    fmt.Println()
    fmt.Println("No problem:")
    fmt.Println(TLSType(0xc013))
}

Which outputs

This const will be printed with its name instead of its number:
TLS_RSA_WITH_RC4_128_SHA

So will this one:
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA

Or maybe we want to give it a value and convert:
TLS_ECDHE_RSA_WITH_RC4_128_SHA

No problem:
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

If you add new const values, just run go generate again to update the generated code.


问:
SoapHttpClientProtocol throws NameResolutionFailure, not ProxyNameResolutionFailure
SoapHttpClientProtocol throws a WebException with status NameResolutionFailure when the proxy name is invalid. How then can I tell if it's the proxy or the destination that is in err?

I'd rather not perform a check if the proxy server exists when a NameResolutionFailure shows up. The only think I can think to do is check the WebException.message property and see if it contains the proxy name vs. the destination name, but this seems icky. Is it the best available?

答: Check the message property, I suppose :/</p>


问:
Getting android contacts details very slow
My app has a listView populated by the contacts registered on the device, but when i load the listView, it takes too long! Here is my code:

```<code>public List<Contact> getContactsList(Context context, ContentResolver contentResolver) {

    List<Contact> listContatos = new ArrayList<Contact>();
    Uri uri = ContactsContract.Contacts.CONTENT_URI;

    Cursor cursorContacts = contentResolver.query(uri, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE ASC;");
    try {
        // while there is a next contact, retrieves your data
        while (cursorContacts.moveToNext()) {

            Contact c = getContact(context, cursorContacts);

            if (c != null) {
                listContatos.add(c);
            }
        }
    } finally {

        // Closes Cursor
        cursorContacts.close();
    }
    return listContatos;
}

public Contact getContact(Context context, Cursor contactsCur) {

    Contact c = new Contact();

    // get contact id
    long id = contactsCur.getLong(contactsCur.getColumnIndexOrThrow(BaseColumns._ID));
    String strId = contactsCur.getString(contactsCur.getColumnIndex(BaseColumns._ID));

    // get contact name
    String name = contactsCur.getString(contactsCur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

    boolean temFone = false;
    // if return is different than 1, doesn't has phone number
    temFone = "1".equals(contactsCur.getString(contactsCur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
    if (temFone) {
        contactsCur = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                new String[] { strId }, null);

        ArrayList<PhoneNumber> phones = new ArrayList<PhoneNumber>();
        while (contactsCur.moveToNext()) {

            int idx = contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            if (idx != -1) {
                String phoneNumber = contactsCur.getString(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                int phonetype = contactsCur.getInt(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                String customLabel = contactsCur.getString(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
                String phoneLabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), phonetype, customLabel);

                phones.add(new PhoneNumber(phoneLabel, phoneNumber));
            }
        }
        c.setPhones(phones);

        contactsCur.close();
    } else {
        c.setPhones(null);
    }

    loadAddress(context, c, id);
    c.setContactId(id);
    c.setName(name);
    loadEmails(context, c, id);
    loadPhotoUri(context, c, id);
    return c;
}

private void loadEmails(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + id,
            null, null);

    ArrayList<ContactMail> emails = new ArrayList<ContactMail>();
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);

        if (idx != -1) {
            String stremail = cursor.getString(idx);

            int emailtype = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            String customLabel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL));
            String emailLabel = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), emailtype, customLabel);

            if (!stremail.equals(""))
                emails.add(new ContactMail(stremail, emailLabel));
        }
    }
    c.setEmails(emails);
    cursor.close();

}

private void loadAddress(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + id, null, null);

    ArrayList<Address> addresses = new ArrayList<Address>();
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA);

        if (idx != -1) {
            String address = cursor.getString(idx);

            int addresstype = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
            String customLabel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.LABEL));
            String addressLabel = (String) ContactsContract.CommonDataKinds.StructuredPostal.getTypeLabel(context.getResources(), addresstype, customLabel);

            if (!address.equals(""))
                addresses.add(new Address(address, addressLabel, null));

        }
    }
    c.setAddresses(addresses);
    cursor.close();
}

public void loadPhotoUri(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                    null,
                    ContactsContract.Data.CONTACT_ID
                            + "="
                            + id
                            + " AND "

                            + ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                            + "'", null, null);

    while (cursor.moveToNext()) {
        int idx = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.DATA);

        if (idx != -1) {
            Uri person = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI, id);
            c.setPhoto( Uri.withAppendedPath(person,
                    ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));
            }
        }
    }
</code>```

It's working just fine, perfectly, the only problem is that takes forever to get all contacts information's. I use the getContact method to get all detailed info about every contact in the device, than in getContactsList I put then in a list of Contact. The list of Contact is used by the adapter of the listView.

Thanks in advance!

Sorry about any english mistakes...

答:
Here is my fast solution:</p>

```<code>Cursor cursorPhones = getContentResolver().query(
    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    new String[]{
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER,
        ContactsContract.CommonDataKinds.Phone.TYPE,
        ContactsContract.CommonDataKinds.Phone.LABEL
    },
    ContactsContract.Contacts.HAS_PHONE_NUMBER + ">0 AND LENGTH(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ")>0",
    null,
    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
);

while (cursorPhones.moveToNext()) {

    String displayName = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String number = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    int type = cursorPhones.getInt(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
    String label = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
    CharSequence phoneLabel = ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), type, label);

}

cursorPhones.close();
</code>```

Body:
My app has a listView populated by the contacts registered on the device, but when i load the listView, it takes too long! Here is my code:

public List<Contact> getContactsList(Context context, ContentResolver contentResolver) {

    List<Contact> listContatos = new ArrayList<Contact>();
    Uri uri = ContactsContract.Contacts.CONTENT_URI;

    Cursor cursorContacts = contentResolver.query(uri, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE ASC;");
    try {
        // while there is a next contact, retrieves your data
        while (cursorContacts.moveToNext()) {

            Contact c = getContact(context, cursorContacts);

            if (c != null) {
                listContatos.add(c);
            }
        }
    } finally {

        // Closes Cursor
        cursorContacts.close();
    }
    return listContatos;
}

public Contact getContact(Context context, Cursor contactsCur) {

    Contact c = new Contact();

    // get contact id
    long id = contactsCur.getLong(contactsCur.getColumnIndexOrThrow(BaseColumns._ID));
    String strId = contactsCur.getString(contactsCur.getColumnIndex(BaseColumns._ID));

    // get contact name
    String name = contactsCur.getString(contactsCur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

    boolean temFone = false;
    // if return is different than 1, doesn't has phone number
    temFone = "1".equals(contactsCur.getString(contactsCur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
    if (temFone) {
        contactsCur = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                new String[] { strId }, null);

        ArrayList<PhoneNumber> phones = new ArrayList<PhoneNumber>();
        while (contactsCur.moveToNext()) {

            int idx = contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            if (idx != -1) {
                String phoneNumber = contactsCur.getString(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                int phonetype = contactsCur.getInt(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                String customLabel = contactsCur.getString(contactsCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
                String phoneLabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), phonetype, customLabel);

                phones.add(new PhoneNumber(phoneLabel, phoneNumber));
            }
        }
        c.setPhones(phones);

        contactsCur.close();
    } else {
        c.setPhones(null);
    }

    loadAddress(context, c, id);
    c.setContactId(id);
    c.setName(name);
    loadEmails(context, c, id);
    loadPhotoUri(context, c, id);
    return c;
}

private void loadEmails(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + id,
            null, null);

    ArrayList<ContactMail> emails = new ArrayList<ContactMail>();
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);

        if (idx != -1) {
            String stremail = cursor.getString(idx);

            int emailtype = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            String customLabel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL));
            String emailLabel = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), emailtype, customLabel);

            if (!stremail.equals(""))
                emails.add(new ContactMail(stremail, emailLabel));
        }
    }
    c.setEmails(emails);
    cursor.close();

}

private void loadAddress(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + id, null, null);

    ArrayList<Address> addresses = new ArrayList<Address>();
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA);

        if (idx != -1) {
            String address = cursor.getString(idx);

            int addresstype = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
            String customLabel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.LABEL));
            String addressLabel = (String) ContactsContract.CommonDataKinds.StructuredPostal.getTypeLabel(context.getResources(), addresstype, customLabel);

            if (!address.equals(""))
                addresses.add(new Address(address, addressLabel, null));

        }
    }
    c.setAddresses(addresses);
    cursor.close();
}

public void loadPhotoUri(Context context, Contact c, long id) {

    Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                    null,
                    ContactsContract.Data.CONTACT_ID
                            + "="
                            + id
                            + " AND "

                            + ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                            + "'", null, null);

    while (cursor.moveToNext()) {
        int idx = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.DATA);

        if (idx != -1) {
            Uri person = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI, id);
            c.setPhoto( Uri.withAppendedPath(person,
                    ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));
            }
        }
    }

It's working just fine, perfectly, the only problem is that takes forever to get all contacts information's. I use the getContact method to get all detailed info about every contact in the device, than in getContactsList I put then in a list of Contact. The list of Contact is used by the adapter of the listView.

Thanks in advance!

Sorry about any english mistakes...

Body:
Here is my fast solution:

Cursor cursorPhones = getContentResolver().query(
    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    new String[]{
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER,
        ContactsContract.CommonDataKinds.Phone.TYPE,
        ContactsContract.CommonDataKinds.Phone.LABEL
    },
    ContactsContract.Contacts.HAS_PHONE_NUMBER + ">0 AND LENGTH(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ")>0",
    null,
    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
);

while (cursorPhones.moveToNext()) {

    String displayName = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String number = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    int type = cursorPhones.getInt(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
    String label = cursorPhones.getString(cursorPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
    CharSequence phoneLabel = ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), type, label);

}

cursorPhones.close();


问:
Meaning of the Sharp Sign in this Mathematica Split Function
I have some problems understanding sharp signs in Mathematica. I understand # & as a placeholder for variables. But how are #1 and #2 understood in the following code?

```<code>x = {0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1};
Split[x, #1 =!= 0 && #2 =!= 0 &]
</code>```

What are #1 and #2 here? The output of these lines is

```<code>{{0}, {1, 1, 1}, {0}, {0}, {1, 1, 1}, {0}, {0}, {1}}
</code>```

答:
That version of Split is of the form Split[list,test], where test is a function that takes two variables. So

```<code>#1 =!= 0 && #2 =!= 0 &
</code>```

is shorthand for a two-variable pure function where #1 and #2 are the variable names.

In general, Split will take a list and return the same list partitioned into consecutive runs of "identical" elements. So if your list is list={0,0,2,2,3,4,4,5,5,5,7}, then Split[list] yields

```<code>{{0,0}, {2,2}, {3}, {4,4}, {5,5,5}, {7}}
</code>```

But maybe you want to define what it means for two things to be "identical" differently. That's where the general Split[list,test] function comes in. The test function here is a function that takes two parameters and returns true if they are identical; the test function is your test for whether or two things are identical. For example, the test function your gave

```<code>#1 =!= 0 && #2 =!= 0 &
</code>```

returns true if the two elements are both nonzero. So your Split function groups elements if they are a run of zeros, or if they are a run of nonzeros.

For another example, say you want to say two integers are identical if they have the same parity (even or odd). Then your split function would be

```<code>Split[list, Mod[#1,2] == Mod[#2,2]]
</code>```

which for the list I defined would return

```<code>{{0,0,2,2}, {3}, {4,4}, {5,5,5,7}}
</code>```

Body:
I have some problems understanding sharp signs in Mathematica. I understand # & as a placeholder for variables. But how are #1 and #2 understood in the following code?

x = {0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1};
Split[x, #1 =!= 0 && #2 =!= 0 &]

What are #1 and #2 here? The output of these lines is

{{0}, {1, 1, 1}, {0}, {0}, {1, 1, 1}, {0}, {0}, {1}}

Body:
That version of Split is of the form Split[list,test], where test is a function that takes two variables. So

#1 =!= 0 && #2 =!= 0 &

is shorthand for a two-variable pure function where #1 and #2 are the variable names.

In general, Split will take a list and return the same list partitioned into consecutive runs of "identical" elements. So if your list is list={0,0,2,2,3,4,4,5,5,5,7}, then Split[list] yields

{{0,0}, {2,2}, {3}, {4,4}, {5,5,5}, {7}}

But maybe you want to define what it means for two things to be "identical" differently. That's where the general Split[list,test] function comes in. The test function here is a function that takes two parameters and returns true if they are identical; the test function is your test for whether or two things are identical. For example, the test function your gave

#1 =!= 0 && #2 =!= 0 &

returns true if the two elements are both nonzero. So your Split function groups elements if they are a run of zeros, or if they are a run of nonzeros.

For another example, say you want to say two integers are identical if they have the same parity (even or odd). Then your split function would be

Split[list, Mod[#1,2] == Mod[#2,2]]

which for the list I defined would return

{{0,0,2,2}, {3}, {4,4}, {5,5,5,7}}