问:
R How to remove "INFO: Remember to close the consumer after done reading messages" when calling rkafka.read
I am currently using R's package for kafka - rkafka. Every time I read from Kafka, I get "INFO: Remember to close the consumer after done reading messages". How do I avoid that?</p>

```<code>>library(rkafka)
>consumer<-rkafka.createConsumer("1.2.3.4:2181","Real-time-data", consumerTimeoutMs = "-1")
>rkafka.read(consumer)
[1] "INFO: Remember to close the consumer after done reading messages"
{\"type\":\"activity_log\",\"id\":0,\"group\":\"prod\",\"screen\":null,\"event\":null,\"time\":\"19:25:00\",\"region\":2657896}"
</code>```

答:
If you want capture the INFO message you can use the "capture.output" command:

```<code>capture.output(rkafka.read(consumer))
</code>```

You can put the message in a variable and then discard it, like this:

```<code>info_msg<-capture.output(rkafka.read(consumer))
rm(info_msg)
</code>```

Body:
I am currently using R's package for kafka - rkafka. Every time I read from Kafka, I get "INFO: Remember to close the consumer after done reading messages". How do I avoid that?

>library(rkafka)
>consumer<-rkafka.createConsumer("1.2.3.4:2181","Real-time-data", consumerTimeoutMs = "-1")
>rkafka.read(consumer)
[1] "INFO: Remember to close the consumer after done reading messages"
{\"type\":\"activity_log\",\"id\":0,\"group\":\"prod\",\"screen\":null,\"event\":null,\"time\":\"19:25:00\",\"region\":2657896}"

Body:
If you want capture the INFO message you can use the "capture.output" command:

capture.output(rkafka.read(consumer))

You can put the message in a variable and then discard it, like this:

info_msg<-capture.output(rkafka.read(consumer))
rm(info_msg)


来源: stackexchange

问:
VueJs - reuse component and pass through background-image

Im trying to reuse a component i VueJs. This is the first time Im using Vue.
I have a couple of components in app.vue. And one of them I want to use two times with the only differens between them is the text and the background-image.
I can't wrap my head around how Im gonna make that work. Any Ideas??? </p>

```<code>App.vue
<!-- first contact banner -->
<lrContactBanner bannerText="The text to the first component"></lrContactBanner>

<!-- second contact banner -->
<lrContactBanner bannerText="text text" backgroundImage="contact.jpeg"></lrContactBanner>

ContactBanner.vue
<div class="banner parallax overlay" :style="{ 'background-image': backgroundImage }">
    <div class="container section">
        <div class="columns">
            <div class="column">
                <h3> {{ bannerText }} </h3>
            </div>
        </div>
    </div>
</div>

<script>
    export default {
      name: 'lrContactBanner',
      props: ['bannerText', 'backgroundImage']
    }
</script>
<style>
    .parallax {
        /* background-image: url("../img/lrImage.jpg"); */
        height: 250px;
        /* Create the parallax scrolling effect */
        background-attachment: fixed;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
        position: relative;
    }
</style>
</code>```

答:
You need to use bound props with v-bind:bannerText or short-hand :bannerText to pass the values to the Banner component.  You also need to use quoted single quotes to pass a string to the component since it's looking for an object by default.  Here's a working example.

```<code><lrContactBanner :bannerText="'text text'" :backgroundImage="'contact.jpeg'"></lrContactBanner>
</code>```

For the background-image I would actually use a computed property like

```<code><template>
  <div class="banner parallax overlay" :style="style">
       <h3>{{ bannerText }} </h3>
  </div>
</template>

<script>
export default {
   props: ['bannerText', 'backgroundImage', 'color'],
   computed: {
     style() {
       return 'background-image: url(' + this.backgroundImage + ')';
     }
   }
}
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to reuse a component i VueJs. This is the first time Im using Vue.
I have a couple of components in app.vue. And one of them I want to use two times with the only differens between them is the text and the background-image.
I can't wrap my head around how Im gonna make that work. Any Ideas???

App.vue

<lrContactBanner bannerText="The text to the first component"></lrContactBanner>

<lrContactBanner bannerText="text text" backgroundImage="contact.jpeg"></lrContactBanner>

ContactBanner.vue

 {{ bannerText }}

Body:
You need to use bound props with v-bind:bannerText or short-hand :bannerText to pass the values to the Banner component.  You also need to use quoted single quotes to pass a string to the component since it's looking for an object by default.  Here's a working example.

<lrContactBanner :bannerText="'text text'" :backgroundImage="'contact.jpeg'"></lrContactBanner>

For the background-image I would actually use a computed property like

<template>
  <div class="banner parallax overlay" :style="style">
       <h3>{{ bannerText }} </h3>
  </div>
</template>

<script>
export default {
   props: ['bannerText', 'backgroundImage', 'color'],
   computed: {
     style() {
       return 'background-image: url(' + this.backgroundImage + ')';
     }
   }
}
</script>


问:
Splay tree real life applications
Where would you use splay-tree in production. I mean a REAL LIFE example.

I was thinking about implementing autocomplete using tries and splay trees. For a large dataset it's not a good idea to traverse through trie from node x to the leaves to return results, so the idea was of having a splay tree inside a node in trie, so when user entered 'sta' it will go to s-t-a,  'a' - node and then return the top 5 elements in the splay tree (by BFS/level traversing, which doesn't necessarily mutates/modifies the tree)

Of course after the autocomplete variant was picked, we should traverse up the trie and update all splay trees inside those nodes.

Since splay trees are sensitive in concurrent environments I was questioning its' usage in production

Your ideas?

答:
Splay trees are not a good match for data which rarely or never changes, particularly in a threaded environment. The extra mutations during read operations defeat memory caches and can create unnecessary lock contention. In any case, for read-only data structures, you can do a one-time computation of an optimal tree. Even if that computation is slow, it will have no impact on the long-term execution time.

I'm not entirely persuaded by the claim that large tries are slow, and certainly not in the case of autocompleters. On even not-so-modern hardware, the cost of a trie traversal is trivial compared to the time it takes for the user to type a character, or even the time it takes for the underlying keyboard driver and input processor to deliver the keypress to your application.

If you really need to optimise a trie, there is good reason to believe that a hybrid data structure with a trie at the root combined with a linear (or binary) search once the alternatives can fit in a cache line. This maximizes the benefit of the trie's large fan-out while avoiding the poor caching behaviour and excessive storage overhead at the end of the lines.

Splay trees are most useful (if they are useful at all) on data structures which are modified frequently. The ckassic example is a "rope" data structure (a tree of string segments), which is one way to attempt to optimise a text editor by avoiding large string copies. Compared with a deterministic tree-balancing algorithm such as RB-trees, the splay tree algorithm has the benefit of simplicity, as well as only touching nodes which form part of the tree traversal.

However, the ready availability of self-balancing tree libraries (part of the standard libraries of many modern programming languages) combined with often-disappointing empirical results make the splay algorithm a niche product at best, although it is certainly a fascinating idea.

Title: Splay tree real life applications


问:
Connected component initial render fails because Redux state is not yet populated from server
I am using Redux thunk and axios to make server calls and modify the state depending on the result.

The problem is that when I use a connected component, and its initial state depends on data from the server, it does not render (the connected props are empty)

```<code>render () (<div>{this.props.someData}</data>) // empty, or error, if nested

...

const mapStateToProps = state => ({
  someData: state.someData
})
</code>```

I also tried this:

```<code>componentWillMount = () => {
  this.setState({
    someData: this.props.someData
  })
}
</code>```

And used state in render, but it didn't help.

Is there a way to wait for the server response before rendering or some other solution?

答:
You can conditionally render that part. Use a property to indicate fetching status (property name is loading in my example).

```<code>class UserDetails extends React.Component {
    state = {
        loading: true,
        data: null
    }

    fetch() {
        this.setState({
            loading: true
        })

        // an axios call in your case
        setTimeout(() => this.setState({
            loading: false,
            data: {
                nestedValue: 'nested value'
            }
        }), 500)
    }

    componentDidMount() {
        this.fetch()
    }

    render() {
        return <div>
            {this.state.loading ? <span>loading...</span> : <div>nested prop value: {this.state.data.nestedValue}</div>}
        </div>
    }
}
</code>```

Body:
I am using Redux thunk and axios to make server calls and modify the state depending on the result.

The problem is that when I use a connected component, and its initial state depends on data from the server, it does not render (the connected props are empty)

render () (
{this.props.someData}</data>) // empty, or error, if nested

...

const mapStateToProps = state => ({
  someData: state.someData
})

I also tried this:

componentWillMount = () => {
  this.setState({
    someData: this.props.someData
  })
}

And used state in render, but it didn't help.

Is there a way to wait for the server response before rendering or some other solution?

Body:
You can conditionally render that part. Use a property to indicate fetching status (property name is loading in my example).

class UserDetails extends React.Component {
    state = {
        loading: true,
        data: null
    }

    fetch() {
        this.setState({
            loading: true
        })

        // an axios call in your case
        setTimeout(() => this.setState({
            loading: false,
            data: {
                nestedValue: 'nested value'
            }
        }), 500)
    }

    componentDidMount() {
        this.fetch()
    }

    render() {
        return <div>
            {this.state.loading ? <span>loading...</span> : <div>nested prop value: {this.state.data.nestedValue}</div>}
        </div>
    }
}


问:
egrep two identical numbers and two identical letters n times
Hi I've been having trouble with the command egrep. Here is my question:
Lets just say I was running in a for loop on these words:

```<code>99aa88bb99aa88bb 9a9a 11bb11bb 11bb11dd 12aa12aa
33aa33bb33aa33bb
</code>```

I only want to print the word if it has two identical numbers and two identical letters and the word repeats itself. for example in this case the only words that should print are:

```<code>99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb
</code>```

because each word has at least one or more set of two identical numbers and the two identical letters and then it repeats itself

Here is another example, I am going over these words in a loop:

```<code> aa99aa99 00aa00bb00aa00bb 44aa44aac
 2222aaaa2222aaaa 11cc11cc11cc11cc
</code>```

The only words that should print are

```<code> 00aa00bb00aa00bb
 11cc11cc11cc11cc
</code>```

because of whats mentioned above.
I am really struggling on how to do this My current command that isnt working is:

```<code>egrep "^((([0-9])\3([a-z])\4)(([0-9])\6([a-z])\7))\1*$" tmp
</code>```

The reason why its not working because it prints for me words like:

```<code>11bb11dd
</code>```

which are not allowed.

any help would be highly appreciated.

答:
Try this:

```<code>$ cat ip.txt
99aa88bb99aa88bb 9a9a 11bb11bb 11bb11dd 12aa12aa
33aa33bb33aa33bb
 aa99aa99 00aa00bb00aa00bb 44aa44aac
 2222aaaa2222aaaa 11cc11cc11cc11cc

$ grep -owE '(([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+|(([0-9])\7([a-z])\8)\6' ip.txt
99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb
00aa00bb00aa00bb
11cc11cc11cc11cc
</code>```

This has two cases

1) (([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+ which has 8 character construct repeating at least once - that is the key, using \1* will falsely match 11bb11dd

2) (([0-9])\7([a-z])\8)\6 this has 4 character construct repeating exactly once

If you have them on separate lines, this would do

```<code>grep -xE '(([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+|(([0-9])\7([a-z])\8)\6'
</code>```

If 11bb11bb11bb has to be matched as well, use \6+

Or, use this very clever suggestion by Nahuel Fouilleul

```<code>$ grep -owE '((([0-9])\3([a-z])\4)+)\1+' ip.txt
99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb
00aa00bb00aa00bb
11cc11cc11cc11cc
</code>```

(([0-9])\3([a-z])\4)+ forms the base, 4/8/12/16/etc characters which consists of repeating digit followed by repeating alphabet

that is then captured in outer group and then repeated at least once

Note that if input is large, and you have PCRE -P option, use that instead of -E as backreferences would be much faster, at least in case of GNU grep

Body:
Hi I've been having trouble with the command egrep. Here is my question:
Lets just say I was running in a for loop on these words:

99aa88bb99aa88bb 9a9a 11bb11bb 11bb11dd 12aa12aa
33aa33bb33aa33bb

I only want to print the word if it has two identical numbers and two identical letters and the word repeats itself. for example in this case the only words that should print are:

99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb

because each word has at least one or more set of two identical numbers and the two identical letters and then it repeats itself

Here is another example, I am going over these words in a loop:

 aa99aa99 00aa00bb00aa00bb 44aa44aac
 2222aaaa2222aaaa 11cc11cc11cc11cc

The only words that should print are

 00aa00bb00aa00bb
 11cc11cc11cc11cc

because of whats mentioned above.
I am really struggling on how to do this My current command that isnt working is:

egrep "^((([0-9])\3([a-z])\4)(([0-9])\6([a-z])\7))\1*$" tmp

The reason why its not working because it prints for me words like:

11bb11dd

which are not allowed.

any help would be highly appreciated.

Body:
Try this:

$ cat ip.txt
99aa88bb99aa88bb 9a9a 11bb11bb 11bb11dd 12aa12aa
33aa33bb33aa33bb
 aa99aa99 00aa00bb00aa00bb 44aa44aac
 2222aaaa2222aaaa 11cc11cc11cc11cc

$ grep -owE '(([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+|(([0-9])\7([a-z])\8)\6' ip.txt
99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb
00aa00bb00aa00bb
11cc11cc11cc11cc

This has two cases

1) (([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+ which has 8 character construct repeating at least once - that is the key, using \1* will falsely match 11bb11dd

2) (([0-9])\7([a-z])\8)\6 this has 4 character construct repeating exactly once

If you have them on separate lines, this would do

grep -xE '(([0-9])\2([a-z])\3([0-9])\4([a-z])\5)\1+|(([0-9])\7([a-z])\8)\6'

If 11bb11bb11bb has to be matched as well, use \6+

Or, use this very clever suggestion by Nahuel Fouilleul

$ grep -owE '((([0-9])\3([a-z])\4)+)\1+' ip.txt
99aa88bb99aa88bb
11bb11bb
33aa33bb33aa33bb
00aa00bb00aa00bb
11cc11cc11cc11cc

(([0-9])\3([a-z])\4)+ forms the base, 4/8/12/16/etc characters which consists of repeating digit followed by repeating alphabet

that is then captured in outer group and then repeated at least once

Note that if input is large, and you have PCRE -P option, use that instead of -E as backreferences would be much faster, at least in case of GNU grep


问:
Attributes in C++. Are they really required for programmers?
I read that C++11 has introduced the concept of attributes for example [[noreturn]] which is to indicate that the function doesn not return to the caller.

```<code>[[noreturn]] void fun()
{
    throw std::string("Error!!!");
}

void func()
{
    fun();
}

void aTempFunc()
{
    try
    {
        func();
    }
    catch (std::string &e)
    {
        std::cout << e << std::endl;
    }
}
</code>```

By looking at the example the reader can understand that the function throws an exception and call will not be returned to the func function.
I am bit confused to understand what are C++ attributes and why it is required? How a programmer can really make use of these attributes?

Can someone explain in detail. Please correct me if my understanding about the attributes is wrong.
Thanks.

答:
attributes are put by the programmer, for the compiler benefit. Basically, they give the compiler more information and allow for more optimization.

For example the noreturn attribute allow the compiler to reclaim stack memory before calling the function (because you will not need the stack frames again) or at least consider the code following the call as dead code.

Body:
I read that C++11 has introduced the concept of attributes for example [[noreturn]] which is to indicate that the function doesn not return to the caller.

[[noreturn]] void fun()
{
    throw std::string("Error!!!");
}

void func()
{
    fun();
}

void aTempFunc()
{
    try
    {
        func();
    }
    catch (std::string &e)
    {
        std::cout << e << std::endl;
    }
}

By looking at the example the reader can understand that the function throws an exception and call will not be returned to the func function.
I am bit confused to understand what are C++ attributes and why it is required? How a programmer can really make use of these attributes?

Can someone explain in detail. Please correct me if my understanding about the attributes is wrong.
Thanks.


问:
AEM6.2: How to store an xml file under content node which is created using JAXB
I am reading properties stored in the content node(mypage.html) and creating an xml with those values(using JAXB). Now i have a requirement to store that xml file under the content node. How do i meet this requirement?</p>

答:
While the best solution would be to create the xml on the fly when that page is requested with a special selector, I do not know your exact reason for why you need to create an xml file. Regardless, here is how you do it:
Using JcrUtils#putFile</p>

```<code>JcrUtils.putFile(yourPageContentNode, “someFile.xml”, “application/xml”, yourFileInputStream)
</code>```

Body:
While the best solution would be to create the xml on the fly when that page is requested with a special selector, I do not know your exact reason for why you need to create an xml file. Regardless, here is how you do it:
Using JcrUtils#putFile

JcrUtils.putFile(yourPageContentNode, “someFile.xml”, “application/xml”, yourFileInputStream)


问:
Go next only if Android studio
I have this code:

```<code>spinRoullete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (something) { check errors.}
                    if (something){something else}
</code>```

If some errors exists stay there and show errors
If errors doesn't exist go forward to next if ..
And the errors

```<code>public void Errors () {
                    if (Rone.isChecked()) {
            if (nr1.getText().length() == 0) {
                nr1.setError("");
                nr1.requestFocus();
            } else {
                nr1.setError(null);
            }
        }           if (Rtwo.isChecked()) {
            if (nr1.getText().length() == 0) {
                nr1.setError("");
                nr1.requestFocus();
            } else {
                nr1.setError(null);
            }
            if (nr2.getText().length() == 0) {
                nr2.setError("");
                nr2.requestFocus();
            } else {
                nr2.setError(null);
            }
        }
}
</code>```

How can I make that? I'm new in this..

答:
You can use return; to exit the method anywhere, so if you make your method checkErrors() to return a boolean, you can do this:

```<code>spinRoullete.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (something) {
            if (check errors) {
                return;
            }
        }
        if (something) {
            something else
        }
    }
});
</code>```

Title: Go next only if Android studio

Body:
I have this code:

spinRoullete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (something) { check errors.}
                    if (something){something else}

If some errors exists stay there and show errors
If errors doesn't exist go forward to next if ..
And the errors

public void Errors () {
                    if (Rone.isChecked()) {
            if (nr1.getText().length() == 0) {
                nr1.setError("");
                nr1.requestFocus();
            } else {
                nr1.setError(null);
            }
        }           if (Rtwo.isChecked()) {
            if (nr1.getText().length() == 0) {
                nr1.setError("");
                nr1.requestFocus();
            } else {
                nr1.setError(null);
            }
            if (nr2.getText().length() == 0) {
                nr2.setError("");
                nr2.requestFocus();
            } else {
                nr2.setError(null);
            }
        }
}

How can I make that? I'm new in this..

Body:
You can use return; to exit the method anywhere, so if you make your method checkErrors() to return a boolean, you can do this:

spinRoullete.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (something) {
            if (check errors) {
                return;
            }
        }
        if (something) {
            something else
        }
    }
});


问:
How to access inputs attributes in node js?
Or simpler, how do I implement an equivalent of the code below in node js?

```<code>selectedRadio = document.querySelector('input[name="device"]:checked').dataset.name;
</code>```

I'm using Node js for backend of an app with Express.js and BodyParser.

I was able to access HTML elements with their Names with req.body.elementName, but I have trouble getting value from the code above.

答:
Like Zammy said, there is no DOM. Just try using events for this.
just give your checkbox the onChange property and add the function you want to handle your event with. </p>

```<code><input
  type="checkbox"
  onChange=YOUR JS_EVENT_CODE
/>
</code>```

<p>There you could bind an existing function or just insert sth. like an arrow function. </p>

Body:
Or simpler, how do I implement an equivalent of the code below in node js?

selectedRadio = document.querySelector('input[name="device"]:checked').dataset.name;

I'm using Node js for backend of an app with Express.js and BodyParser.

I was able to access HTML elements with their Names with req.body.elementName, but I have trouble getting value from the code above.

Body:
Like Zammy said, there is no DOM. Just try using events for this.
just give your checkbox the onChange property and add the function you want to handle your event with.

<input
  type="checkbox"
  onChange=YOUR JS_EVENT_CODE
/>

There you could bind an existing function or just insert sth. like an arrow function.


问:
Is there a way to stop rails logging everything?
I don't want it to log incoming IPs, I don't want it to log any internal happenings.

I just want Rails to process the requests as they come in and that's that.

Is this possible to do?

How can I prevent having a growing development.log or production.log?

答:
Simplifying Chris Heald answer, you can set the logger to /dev/null by environment:

```<code>Rails.application.configure do
  config.logger = Logger.new("/dev/null")
end
</code>```

Just place the code in the right file(s):

Development: config/environments/development.rb

Test: config/environments/test.rb

Production: config/environments/production.rb

All environments: congig/applications.rb

Body:
Simplifying Chris Heald answer, you can set the logger to /dev/null by environment:

Rails.application.configure do
  config.logger = Logger.new("/dev/null")
end

Just place the code in the right file(s):

Development: config/environments/development.rb

Test: config/environments/test.rb

Production: config/environments/production.rb

All environments: congig/applications.rb


问:
How can I check the SBT version?
How do I check which version of SBT I'm running?

I have the Bash file set up that uses sbt-launch.jar, and it works, but

```<code>sbt version
</code>```

only shows the "project version" (0.1) and

```<code>sbt --version
</code>```

does nothing.

答: Run the SBT console and then type sbtVersion to check the SBT version, and scalaVersion for the Scala runtime version.

ContentLicense: CC BY-SA 4.0

Title: How can I check the SBT version?

Body:
How do I check which version of SBT I'm running?

I have the Bash file set up that uses sbt-launch.jar, and it works, but

sbt version

only shows the "project version" (0.1) and

sbt --version

does nothing.


问:
Trac - get programmatically wiki page content behind authentication
I'd like to get the content of a wiki page from my trac (1.0.9) using a script.
My Trac is served through apache httpd and adopts a Basic AuthType.

So I tried to use wget as follows

```<code>wget http://my/trac/wiki/MyWikiPage?format=txt --user=<THISISME> --ask-password --auth-no-challenge -q -O -
</code>```

but I get a 403 error.

```<code>HTTP request sent, awaiting response... 403 Forbidden
</code>```

Is there something wrong? Or in other words, is thre a way to simply fetch remotely a wiki page from Trac (taking authentication into account)? Thx

答: You could install XmlRpcPlugin and use one of the supported libraries, such as xmlrpclib in Python, to fetch the page.

Body:
I'd like to get the content of a wiki page from my trac (1.0.9) using a script.
My Trac is served through apache httpd and adopts a Basic AuthType.

So I tried to use wget as follows

wget http://my/trac/wiki/MyWikiPage?format=txt --user=<THISISME> --ask-password --auth-no-challenge -q -O -

but I get a 403 error.

HTTP request sent, awaiting response... 403 Forbidden

Is there something wrong? Or in other words, is thre a way to simply fetch remotely a wiki page from Trac (taking authentication into account)? Thx


问:
exportlink for Google drive api v3
I'm switching to the Google drive V3 apis and I'm not able to retrieve the stream to the document.

Goal:  I want to push a google drive document to another location and I need to retrieve the stream of the file in order to use it to push it to the target.

I can't find a way to do it using Google Drive API V3 !

In V2, I used:

```<code>downloadUrl = file.ExportLinks[(string)ExportTable[file.MimeType]];
</code>```

And then I could use something like:

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(downloadUrl));
</code>```

I don't find the equivalent in V3.
I tried:

```<code> var getfile = _service.Files.Get(file.Id).Execute();
 var request = _service.Files.Export(file.Id, getfile.MimeType);
 System.IO.Stream stream = request.ExecuteAsStream();
</code>```

And the content of the stream is:

```<code>{
"error": {
 "errors": [
 {
"domain": "global",
"reason": "fileNotExportable",
"message": "Export only supports Google Docs."
}   ],
"code": 403,
"message": "Export only supports Google Docs."
}
}
</code>```

Of course, we don't want to download it to a local file and then generate a new stream from the file cached locally. We want to remain entirely in memory.

Thanks for your help

答:
You can also create a link yourself if you are logged in as the right user or the file is public with a link:

https://docs.google.com/feeds/download/documents/export/Export?id={{ID}}&exportFormat=pdf

Title: exportlink for Google drive api v3

Body:
I'm switching to the Google drive V3 apis and I'm not able to retrieve the stream to the document.

Goal:  I want to push a google drive document to another location and I need to retrieve the stream of the file in order to use it to push it to the target.

I can't find a way to do it using Google Drive API V3 !

In V2, I used:

downloadUrl = file.ExportLinks[(string)ExportTable[file.MimeType]];

And then I could use something like:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(downloadUrl));

I don't find the equivalent in V3.
I tried:

 var getfile = _service.Files.Get(file.Id).Execute();
 var request = _service.Files.Export(file.Id, getfile.MimeType);
 System.IO.Stream stream = request.ExecuteAsStream();

And the content of the stream is:

{
"error": {
 "errors": [
 {
"domain": "global",
"reason": "fileNotExportable",
"message": "Export only supports Google Docs."
}   ],
"code": 403,
"message": "Export only supports Google Docs."
}
}

Of course, we don't want to download it to a local file and then generate a new stream from the file cached locally. We want to remain entirely in memory.

Thanks for your help


问:
Why is garbage collector allowed to collect seemingly referenced objects with a finalizer?
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

```<code>public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}
</code>```

and our code uses that wrapper:

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
</code>```

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);
</code>```

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

```<code> public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }
</code>```

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?

答:
Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer?

Because that's not what the GC (or the C# specification) guarantees. The guarantee is that if an object won't be finalized or collected while it's still possible to read a field from it. If the JIT/GC detects that although you're currently executing an instance method, there's no execution path whereby that method will read any more fields, it is legal for the object to be collected (assuming there's nothing else keeping it alive).

It's surprising, but that's the rule - and I strongly suspect that the reason for it is to allow optimization paths that would otherwise be impossible.

Your fix of using GC.KeepAlive is a perfectly reasonable one. Note that the number of situations where this is relevant is pretty tiny.

Body:
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}

and our code uses that wrapper:

var wrapper = CoolWrapper();
wrapper.DoSomething();

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

 public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?


问:
Regex does not work in IE9
Any ideas as to why the following doesn't work for any of the IE9 betas? IE8 fine (or IE9 running compatibility mode):</p>

```<code>if(b.msie){
  b.ver = /MSIE (\d+(.\d+)?)/.exec(ua)[1];
 }else if(b.mozilla){
  b.ver = /Firefox\/(\d+(.\d+)?)/.exec(ua)[1];
 }else if(b.opera){
  b.ver = /Opera\/? ?(\d+(\.\d+)?)/.exec(ua)[1];
 }else if(b.safari){
  b.ver = /Version\/(\d+(\.\d+)+)/.exec(ua)[1];
 }else if(b.chrome){
  b.ver = /Chrome\/(\d+(\.\d+)+)/.exec(ua)[1];
 }
</code>```

答:
don't you want String.match()? e.g. b.ver = ua.match(/MSIE (\d+(\.\d+)?)/)[1];

you also need to escape the . outside a character class.

ContentLicense: CC BY-SA 2.5

Title: Regex does not work in IE9

Body:
Any ideas as to why the following doesn't work for any of the IE9 betas? IE8 fine (or IE9 running compatibility mode):

if(b.msie){
  b.ver = /MSIE (\d+(.\d+)?)/.exec(ua)[1];
 }else if(b.mozilla){
  b.ver = /Firefox\/(\d+(.\d+)?)/.exec(ua)[1];
 }else if(b.opera){
  b.ver = /Opera\/? ?(\d+(\.\d+)?)/.exec(ua)[1];
 }else if(b.safari){
  b.ver = /Version\/(\d+(\.\d+)+)/.exec(ua)[1];
 }else if(b.chrome){
  b.ver = /Chrome\/(\d+(\.\d+)+)/.exec(ua)[1];
 }


问:
Do 128bit cross lane operations in AVX512 give better performance?
In designing forward looking algorithms for AVX256, AVX512 and one day AVX1024 and considering the potential implementation complexity/cost of fully generic permutes for large SIMD width I wondered if it is better to generally keep to isolated 128bit operations even within AVX512?

Especially given that AVX had 128bit units to execute 256bit operations.

To that end I wanted to know if there was a performance difference between AVX512 permute type operations across all of the 512bit vector as opposed to permute type operations within each 4x128bit sub-vectors of a 512bit vector?

答:
Generally yes, in-lane is still lower latency on SKX (1 cycle vs. 3), but usually it's not worth spending extra instructions to use them instead of the powerful lane-crossing shuffles.  However, vpermt2w and a couple other shuffles need multiple shuffle-port uops, so they cost as much as multiple simpler shuffles.

Shuffle throughput very easily becomes a bottleneck if you aren't careful on recent Intel CPUs (only one shuffle execution unit on port 5).  Sometimes it's even worth using two overlapping loads instead of loading once and shuffling, i.e. using an unaligned load as a shuffle, because L1D cache is fast, and so is load-port handling of unaligned loads.  (Less so with AVX512, though, especially because every unaligned 512b load is automatically a cache-line split, because vectors and cache lines are both 64 bytes.)

For 256-bit loads, one trick is to choose a load address that splits the data you care about into the two lanes, so you can use a vpshufb (_mm256_shuffle_epi8) in-lane byte shuffle to get each byte where it's needed.

There are also rotate (new in AVX512) and shift instructions (not new).  The 64-bit element size versions can move data between smaller elements if you use a shift or rotate count of 32 or 16, for example.  vprolq zmm, zmm, 32 is 1c latency and runs on port 0 (and also port1 for the xmm/ymm versions), swapping every element with it's neighbour.  Shifts/rotates don't compete for port 5 on SKX.

For a horizontal sum, the only real choice is what order to shuffle in.  Usually start with extract / add down to 128b, then use __m128 shuffles (or integer shifts), instead of using vpermd/q for every shuffle.  Or if you want the result broadcast to all elements, use in-lane shuffles between the first few adds, and then shuffle in 128b then 256b chunks with lane-crossing shuffles.  (Shuffling in 128b chunks isn't faster than smaller granularity immediate-control shuffles like vpermq z,z,imm8 on SKX, but that's all you need for an hsum after doing the in-lane stuff with vshufps or vpermilps.)

Note that some future CPUs may split 512b ops into two 256b ops, perhaps an E-core in some future Intel CPU.  If done like Zen 1, that could make 512-bit lane-crossing shuffles significantly more expensive.  Even vperm2f128 on Zen1 is 8 uops, 3c lat / 3c throughput, vs. 1 uop on SKL.  In-lane shuffles obviously decompose into 1 uop per lane fairly easily, but lane-crossing doesn't.

Fortunately Zen 4 does not have this downside - 512-bit instructions are still single-uop (including ZMM shuffles like vpermt2d), they just occupy an execution port for longer.  This let them make a few execution units be full-width, notably shuffles.  So things like vpermb are as fast as on Intel, or faster like vpermt2b which Intel runs as 3 uops.  This implementation strategy is much better than Zen 1's, generally not creating performance potholes, and making 512-bit vectors more usable on Zen 4 for general-purpose uses than they are on Intel.  (Saving front-end bandwidth for the same amount of back-end work.)  https://uops.info/ and see Mysticial's writeup.

Xeon Phi (discontinued)

On KNL, it's not lanes, it's 1-source vs. 2-source shuffles that matter.

e.g. vshufps dst, same,same, imm8 is half the throughput of vpermilps dst, src, imm8.

1-source shuffles with a vector control like vpermd v,v,v are still fast, though (1 source + 1 shuffle-control vector).

Even when they're only 1 uop, the 4-7c latency shuffles (2-input) have worse than 2c throughput.  I guess that means KNL's shuffle unit isn't fully pipelined.

Raw data

https://uops.info/ is the go-to for uops / latency / ports microbenchmark info these days.  Generally well-crafted microbenchmarks and detailed results that don't try to boil things down to a single number when there multiple uops and different latencies from different inputs to the ouput(s).  And no manual typos like there sometimes are in Agner Fog's otherwise-good instruction tables.  Agner's microarch guide is essential reading for understanding the numbers, and possible other bottlenecks like in the front-end.

When this answer was first written, https://uops.info/ didn't exist, and Agner Fog didn't yet have test results for Skylake-X (SKX) aka SKL-SP or gcc -march=skylake-avx512.  But there was already InstLatx64 (Instruction throughput/Latency) results, and IACA support.  InstLatx64 has a spreadsheet (ODS OpenOffice/LibreOffice format) combining data from IACA (just uop count and ports), and published by Intel in a PDF (throughput/latency), and from real experimental testing on real hardware (throughput/latency).  These days https://uops.info/ is pretty quick to get new microarchitectures tested, but InstLat sometimes has CPUID dumps before test results.

Agner Fog's instruction tables have data for Knight's Landing Xeon Phi (KNL), and there's a section about it's Silvermont-based microarchitecture in his microarch PDF.

KNL instructions have better latency if their input is coming from the same execution unit (e.g. shuffle -> shuffle) vs. FMA -> shuffle.  (See the note at the top of Agner's spreadsheet).  This is what the 4-7c latency numbers are about.  A transpose or something doing a chain of shuffles might see mostly the lower latency number.  (But KNL has generally high latencies, which is why it has 4-way hyperthreading
to try to hide them).

SKX: Skylake-AVX512 (and probably future mainstream Intel CPUs)

All lane crossing shuffles are at best 1 uop, 3c latency, 1c throughput.  But even complex/powerful ones like 2-input vpermt2ps are that fast.  This includes all shuffles that shuffle whole lanes, or insert/extract 256b chunks.

All in-lane-only shuffles are 1c latency (except for the xmm version of some new-in-avx512 lane-crossing shuffles).  So use vpshufd zmm, zmm, imm8 or vpunpcklqdq zmm, zmm, zmm when that's all you need.  Or vpshufb or vpermilps with a vector control input.

Like Haswell and SKL (non-avx512), SKX can only run shuffle uops on port 5.  Again like those earlier CPUs, it can broadcast-load using only the load ports, so that's just as cheap as a regular vector load.  AVX512 broadcast loads can micro-fuse, making memory-source broadcasts cheaper (in shuffle throughput terms) than register source.

Even vmovsldup ymm, [mem] / vmovshdup ymm, [mem] use just a load uop for the 256b shuffle.  IDK about 512b; Instlat didn't test memory-source movsl/hdup, so we only have Agner Fog's data.  (And IIRC I confirmed that on my own SKL).

Note that when running 512b instructions, the vector ALUs on port 1 are disabled, so you have a max throughput of 2 vector ALU uops per clock.  (But p1 can still run integer stuff.)  And vector load/store uops don't need p0 / p5, so you can still bottleneck on the front-end (4 uops per clock issue/rename) in code with a mix of non-fused loads, stores, and ALU (and integer loop overhead, and vmovdqa register copying handled in the rename stage with unfused-domain uop).

Exceptions to the rule on SKX:

VPMOVWB ymm, zmm and similar truncate or signed/unsigned saturate instructions are 2 uops, 4c latency.  (Or 2c for the xmm versions).  vpmovqd is 1 uop, 3c (or 1c xmm) latency, because its smallest granularity is dword and it's only truncating, not saturating, so it can be implemented internally with the same hardware that's needed for pshufb for example.  vpmovz/sx instructions are still only 1 uop.

vpcompressd/q (left-pack based on a mask) is 2 uops (p5), 3c latency.  (Or 6c according to what Intel publishes; maybe Instlat is testing the vector->vector latency and Intel is giving the k register -> vector latency?  Unlikely that it's data-dependent and faster with a trivial mask.)  vpexpandd is also 2 uops.

AVX512BW vpermt2w / vpermi2w is 3 uops (p0 + 2p5), 7c latency for all 3 operand sizes (xmm/ymm/zmm).  Small-granularity wide shuffles are expensive in hardware (See Where is VPERMB in AVX2? including the comments).  This is a 2-source 16-bit-element shuffle with the control in a 3rd vector.  It might get faster eventually in future generations, the way pshufb (and all full-register shuffles with granularity smaller than 8 bytes) was slow in first-gen Core2 Conroe/Merom, but got fast in the die-shrink next generation (Penryn).

AVX512BW vpermw (one-source lane-crossing word shuffle) is 2p5, 6c latency, 2c throughput because it's a lane-crossing word shuffle.

expect AVX512VBMI vpermt2b to be as bad or worse on Cannonlake, even if Cannonlake does improve vpermt2w / vpermw.

vpermt2d/q/ps/pd are all efficient in SKX because their granularity is dword (32-bit) or wider.  (But still apparently 3c latency for the xmm version, so they didn't build separate hardware to speed up the one-lane version).  These are even more powerful than a lane-crossing shufps: a variable control and with no limitation on which source register each element comes from.  It's a fully general 2-source shuffle where you index into the concatenation of 2 registers, overwriting the index (vpermi2*) or one of the tables (vpermt2*).  There's only one intrinsic because the compiler handles register allocation and copying to preserve still-needed values.

Knight's Landing:

Shuffles run on the FP0 port only, but front-end throughput is only 2 uops per clock.  So more of your total instructions can be shuffles without bottlenecking on that (vs. SKX), unless they're half-throughput shuffles.

In general, 2-input shuffles like vperm2f128/vshuff32x4 or vshufps are 2c throughput / 4-7c latency, while 1-input shuffles like vpermd are 1c throughput / 3-6c latency.  (i.e. 2 inputs occupies the shuffle unit for an extra cycle (half throughput) and costs 1 extra cycle of latency).  Agner isn't clear on exactly what the effect of the not-fully-pipelined shuffles is, but I assume it just ties up the shuffle unit, and not everything on port FP0 (like the FMA unit).

Lane-crossing or not makes no difference on KNL, e.g. vpermilps and vpermps are both fast (1c throughput, 3-6c latency), but vpermi2ps and vshufps are both slow (2c throughput, 4-7c latency).  I don't see any exceptions to that for instructions where KNL supports an AVX512 version.  (i.e. not counting AVX2 vpshufb, i.e. pretty much anything with 32-bit or larger granularity).

vinserti32x4 and so on (insert/extract with granularity of at least 128b) is a 2-input shuffle for insert, but is fast: 3-6c lat / 1c tput.  But extract-to-memory is multiple uops and causes a decode bottleneck: e.g. VEXTRACTF32X4 m128,z is 4 uops, one per 8c throughput.  (mostly because of decode).

vcompress/ps/d, vpcompressd/q and v[p]expandd/q/ps/pd are 1 uop, 3-6c latency.  (vs. 2 uops on SKX).  But throughput is only one per 3c: Agner doesn't indicate whether this ties up the whole shuffle unit for 2c, or if only this part is not fully pipelined.

AVX2 byte/word shuffles are very slow for 256b operand-size: pshufb xmm is 5 uops / 10c throughput, vpshufb ymm is 12 uops / 12c throughput.  (MMX pshufb mm is 1 uop, 2-6c latency, 1c throughput, so I guess the byte-granularity shuffle unit is 64b wide.)

pshuflw xmm is 1 uop fast, but vpshuflw ymm is 4 uops, 8c throughput.

Video encoding on KNL might be barely worth it with 128-bit AVX (vpsadbw xmm is fast), but AVX2 ymm instructions are generally slower than using more 1 uop xmm instructions.

movss/sd xmm,xmm is a blend, not a shuffle, and has 0.5c throughput / 2c latency.

vpunpcklbw / wd are super slow (except the xmm version), but DQ and QDQ are the regular speed even for ymm / zmm operand size.  (2c throughput / 4-7c latency, because it's a 2-input shuffle).

vpmovzx is 3c latency (not 3-6c?) and 2c throughput even for vpmovzxbw.  vpmovsx is slower: 2 uops and thus a decode bottleneck, making it 8c latency and 7c throughput.  The narrowing truncate instructions (vpmovqb and so on) are 1 uop, 3c lat / 1c tput, but the narrowing saturate instructions are 2 uops and thus slow.  Agner didn't test them with a memory destination.


问:
Protractor + chrome driver: Element is not clickable at point
Hi I am having some trouble getting a basic protractor test to work.

My setup:

I use requirejs so I init angular using angular.bootstrap(), not the ng-app attr. According to protractor docs this is not supported out of the box, but seems to work fine for tests that don' involve clicking.

Protractor conf.json:

```<code>"use strict";
exports.config = {
    specs: '../E2ETests/**/*.js',
    chromeOnly: true,
    getPageTimeout: 30000,
    allScriptsTimeout: 30000
}
</code>```

I use some third party jquery plugs which I wrap in directives, I suspect these might be part of the issue.

The test:

```<code>"use strict";
describe('When clicking should add stuff', function () {
    var ptor;
    beforeEach(function () {
        browser.get('https://localhost/myApp');
        ptor = protractor.getInstance();
    });
    it('add stuff', function () {
        // If I comment this, the test pass.
        element(by.id('add-stuff-button')).click();
        // This does not matter fails on the line above..
        expect(browser.getTitle()).toBeDefined();
    });
});
</code>```

The error:

```<code>UnknownError: unknown error: Element is not clickable at point (720, 881). Other element would         receive the click: <div class="col-md-5 col-md-offset-5">...</div>
(Session info: chrome=37.0.2062.124)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)
</code>```

Thoughts

The chromedriver do find the button, because if I change the id it complains that no element is found. So I think the problem is that the button moves from its initial position. As the element(***)  function should wait for angular to be done, I suspect that its the third party plugins that might interfere as they might not use angular api's fetching data etc. So angular think its done but then the third party plug populates and moves stuff around.

Any ideas what to do?
If the third party plugs is the problem, can I somehow tell angular that third party stuff is going on and then later tell it when its done?

Thx
Br
Twd

答:
This works better than specifying the window size, in case you test need to run on multiple displays.

browser.manage().window().maximize();

Body:
Hi I am having some trouble getting a basic protractor test to work.

My setup:

I use requirejs so I init angular using angular.bootstrap(), not the ng-app attr. According to protractor docs this is not supported out of the box, but seems to work fine for tests that don' involve clicking.

Protractor conf.json:

"use strict";
exports.config = {
    specs: '../E2ETests/**/*.js',
    chromeOnly: true,
    getPageTimeout: 30000,
    allScriptsTimeout: 30000
}

I use some third party jquery plugs which I wrap in directives, I suspect these might be part of the issue.

The test:

"use strict";
describe('When clicking should add stuff', function () {
    var ptor;
    beforeEach(function () {
        browser.get('https://localhost/myApp');
        ptor = protractor.getInstance();
    });
    it('add stuff', function () {
        // If I comment this, the test pass.
        element(by.id('add-stuff-button')).click();
        // This does not matter fails on the line above..
        expect(browser.getTitle()).toBeDefined();
    });
});

The error:

UnknownError: unknown error: Element is not clickable at point (720, 881). Other element would         receive the click:
...

(Session info: chrome=37.0.2062.124)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)

Thoughts

The chromedriver do find the button, because if I change the id it complains that no element is found. So I think the problem is that the button moves from its initial position. As the element(***)  function should wait for angular to be done, I suspect that its the third party plugins that might interfere as they might not use angular api's fetching data etc. So angular think its done but then the third party plug populates and moves stuff around.

Any ideas what to do?
If the third party plugs is the problem, can I somehow tell angular that third party stuff is going on and then later tell it when its done?

Thx
Br
Twd


问:
How Enumerable.Zip works with LinQ
I would like to Zip multiple List of integer and don't know how to do that in LinQ.

Here's my List :

```<code>List<KeyValuePair<Guid, List<int>>> totals = Totals.Where(x => x.Key == myGuid).ToList();
//where Totals is a List<KeyValuePair<Guid, List<int>>>

List<List<int>> totalsValue = totals.Select(s => s.Value).ToList();
//I want to Zip all my List<int> in totalsValue and put it into listToReturn

List<int> listToReturn = new List<int>();
</code>```

I want something like that : http://linqsamples.com/linq-to-objects/other/Zip-lambda-csharp but in this exemple, lists are separeted.
Mine is a List>
Where listToReturn represents the list to return.

Can someone help me ?

Result :
Where adventest is a List and agiltest also
enter image description here

答:
I think you are looking for SelectMany:

```<code>List<int> listToReturn= totals = Totals.Where(x => x.Key == myGuid)
                                       .SelectMany(s => s.Value)
                                       .ToList();
</code>```

What you are trying to do is flatten all the lists into one sequence and that is what SelectMany extension method do. Zip, in the other side, merges each element of the first sequence with an element that has the same index in the second sequence, in other words, it allows you to project from two sequences of the same length.

Update

Now I understand what you are trying to achieve:

```<code>var lists= Totals.Where(x => x.Key == myGuid).Select(e=>Value).ToList();// Select the lists
if(lists.Count>0)
  var result=  Enumerable.Range(0, lists[0].Count).Select(i=> lists.Sum(l=>l[i]));
</code>```

The thing with this solution you need to make sure that all the selected lists have the same size. I'm pretty sure there is a more elegant solution but this was that come to my mind now. If I think in something better I will update my answer

Title: How Enumerable.Zip works with LinQ

Body:
I would like to Zip multiple List of integer and don't know how to do that in LinQ.

Here's my List :

List<KeyValuePair<Guid, List<int>>> totals = Totals.Where(x => x.Key == myGuid).ToList();
//where Totals is a List<KeyValuePair<Guid, List<int>>>

List<List<int>> totalsValue = totals.Select(s => s.Value).ToList();
//I want to Zip all my List<int> in totalsValue and put it into listToReturn

List<int> listToReturn = new List<int>();

I want something like that : http://linqsamples.com/linq-to-objects/other/Zip-lambda-csharp but in this exemple, lists are separeted.
Mine is a List>
Where listToReturn represents the list to return.

Can someone help me ?

Result :
Where adventest is a List and agiltest also
enter image description here

Body:
I think you are looking for SelectMany:

List<int> listToReturn= totals = Totals.Where(x => x.Key == myGuid)
                                       .SelectMany(s => s.Value)
                                       .ToList();

What you are trying to do is flatten all the lists into one sequence and that is what SelectMany extension method do. Zip, in the other side, merges each element of the first sequence with an element that has the same index in the second sequence, in other words, it allows you to project from two sequences of the same length.

Update

Now I understand what you are trying to achieve:

var lists= Totals.Where(x => x.Key == myGuid).Select(e=>Value).ToList();// Select the lists
if(lists.Count>0)
  var result=  Enumerable.Range(0, lists[0].Count).Select(i=> lists.Sum(l=>l[i]));

The thing with this solution you need to make sure that all the selected lists have the same size. I'm pretty sure there is a more elegant solution but this was that come to my mind now. If I think in something better I will update my answer


问:
Any way to have double->float conversion regarded as "widening"?
Is there any way to tell vb.net (2010) to allow expressions of type Double to be passed to parameters expecting Float, without having to use an explicit CSng() calls, other than by turning off all complaints related to narrowing conversions?  Given that a Double->Single conversion will never throw an exception, and given that precision loss does not seem to be a criterion for regarding a conversion as "Narrowing" (Long->Double is considered "Widening" despite the fact that it involves an inexact conversion from an "exact-value" type to an "approximate-value" type; a Double->Single conversion merely goes from an "approximate-value" type to a "somewhat-more-approximate-value" type, so it is in some sense less lossy).

I know turning off Option Strict would eliminate squawks about Double->Single conversion, but that is incredibly massively overkill.  Is there any way to stifle all complaints about Double->Single, without stifling other possibly-useful squawks?

Edit

If Microsoft isn't going to allow code to be written in the most logical fashion, would it be preferable to litter the code with CSng() every time I call graphics methods, or define NewRectF and NewPointF methods which accept doubles and then use the RectF/PointF overloads for the graphics methods, or would something else be better still?

答:
I believe not, and (more importantly) if you can, I advise to not do it. In the best case, your tests will find the faulty data that members of your team might create by such a sorry compiler flag. In the worst case, your application's faulty data will go completely unnoticed.

Argument:

I'm afraid your logic is fallacious. While it's true that long accurately represents integers (in the range of longs), while double is an approximation of real numbers, it's not true that the conversion from long to double is inexact. (If unsure about this, check it out yourself with the program below.) No data will be lost when casting from long to double, so it's by definition non-narrowing. Such casts are thus not going to introduce errors on their own (although various errors may be introduced by treating double as real numbers).

This is certainly not true when casting from doubles to floats. If that wouldn't introduce data loss, we would always use floats, as they use less memory). It may be OK in some cases to cast a double to float, but the programmer should "vouch" for it. This he does by explicitly casting (using CSng).

```<code>Function DataLostWhenCasting(ByVal l As Long)
    Dim d As Double
    Dim e As Double

    d = l ' The cast (implicit)
    ' Check for lost data:
    e = d - l
    If e > 0 Then
        Return True
    End If

    Return False
End Function

Sub Main()
    Console.WriteLine(DataLostWhenCasting(Long.MinValue))
    Console.WriteLine(DataLostWhenCasting(Long.MaxValue))
End Sub
</code>```

Body:
I believe not, and (more importantly) if you can, I advise to not do it. In the best case, your tests will find the faulty data that members of your team might create by such a sorry compiler flag. In the worst case, your application's faulty data will go completely unnoticed.

Argument:

I'm afraid your logic is fallacious. While it's true that long accurately represents integers (in the range of longs), while double is an approximation of real numbers, it's not true that the conversion from long to double is inexact. (If unsure about this, check it out yourself with the program below.) No data will be lost when casting from long to double, so it's by definition non-narrowing. Such casts are thus not going to introduce errors on their own (although various errors may be introduced by treating double as real numbers).

This is certainly not true when casting from doubles to floats. If that wouldn't introduce data loss, we would always use floats, as they use less memory). It may be OK in some cases to cast a double to float, but the programmer should "vouch" for it. This he does by explicitly casting (using CSng).

Function DataLostWhenCasting(ByVal l As Long)
    Dim d As Double
    Dim e As Double

    d = l ' The cast (implicit)
    ' Check for lost data:
    e = d - l
    If e > 0 Then
        Return True
    End If

    Return False
End Function

Sub Main()
    Console.WriteLine(DataLostWhenCasting(Long.MinValue))
    Console.WriteLine(DataLostWhenCasting(Long.MaxValue))
End Sub


问:
how to make a value between parentheses in a text file
How can i get value contained in a text file in parentheses?

Example Input:

```<code>Today is a beautiful {day}
</code>```

I want to get the value of day.

答:
Sadly, your question is not very exact, so I try my best to answer, what you asked for, assuming there is just one line and there is exactly one {...} part and it's not at the very beginning of the string:

```<code>set "string=Today is a beautiful {day}"
for /f "tokens=2 delims={}" %%a in ("%string%") do set "var=%%a"
echo %var%
</code>```

Body:
How can i get value contained in a text file in parentheses?

Example Input:

Today is a beautiful {day}

I want to get the value of day.

Body:
Sadly, your question is not very exact, so I try my best to answer, what you asked for, assuming there is just one line and there is exactly one {...} part and it's not at the very beginning of the string:

set "string=Today is a beautiful {day}"
for /f "tokens=2 delims={}" %%a in ("%string%") do set "var=%%a"
echo %var%


问:
Run external OneClick app from ASP.net Website
When attempting to run a .application OneClick deployment application from debug mode it runs with the following examples:

Use a  reference around the clickable image that launches the application

Other attempt was a start process

```<code>Dim p As New Process()
p.StartInfo.FileName = "\\server\SharedFolder\MainFolder\ExternalApp.application"
p.Start()
</code>```

VB.net Javascript call:

VB.NET

```<code>ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Pop", "LaunchApp();", True)
</code>```

JAVASCRIPT

```<code><script type = "text/javascript">
function LaunchApp() {
    var ws = new ActiveXObject("WScript.Shell");
    ws.Exec("\\server\SharedFolder\MainFolder\ExternalApp.application");
}
</code>```

Both options worked [aside option 3] when I was debugging. When I ran this outside the debugger it didn't work. Any suggestions as to why?

I read the following links but no luck:

href="https://stackoverflow.com/questions/16245273/run-windows-form-app-from-asp-net-page">Run windows form app from asp.net page

答:
What I ended up doing was using the publish build file that runs it in a generic html file. This is generated when you build the application. I ended up opening this with a windows popup and reformatted the design to match my website.

Simple workaround.

Body:
When attempting to run a .application OneClick deployment application from debug mode it runs with the following examples:

Use a  reference around the clickable image that launches the application

<a href="\\server\SharedFolder\MainFolder\ExternalApp.application"

Other attempt was a start process

Dim p As New Process()
p.StartInfo.FileName = "\\server\SharedFolder\MainFolder\ExternalApp.application"
p.Start()

VB.net Javascript call:

VB.NET

ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Pop", "LaunchApp();", True)

JAVASCRIPT


问:
How to add my own software to a Buildroot Linux package?
I am trying to add my own program to a small linux, created with Buildroot.
What I've done so far:

I've created a new directory inside my 'buildroot/package/'  called 'HelloWorld'.
Inside 'buildroot/package/HelloWorld' I have : a Config.in, HelloWorld.mk and HelloWorld directory.
Config.in holds this:

```<code>     config BR2_PACKAGE_HELLOWORLD
     bool "helloworld"
     default y
     help
             Hello world component.
</code>```

HelloWorld.mk holds this:

```<code>HELLOWORLD_VERSION:= 1.0.0
HELLOWORLD_SITE:= /home/userpc/Downloads/helloworld/
HELLOWORLD_SITE_METHOD:=local
HELLOWORLD_INSTALL_TARGET:=YES

define HELLOWORLD_BUILD_CMDS
        $(MAKE) CC="$(TARGET_CC)" LD="$(TARGET_LD)" -C $(@D) all
endef

define HELLOWORLD_INSTALL_TARGET_CMDS
        $(INSTALL) -D -m 0755 $(@D)/helloworld $(TARGET_DIR)/bin
endef

define HELLOWORLD_PERMISSIONS
       /bin/helloworld f 4755 0 0 - - - - -
endef

$(eval $(generic-package))
</code>```

(inspiration source)
The HelloWorld directory contains: main.c & Makefile:

main.c :

```<code>#include <stdio.h>

int main()
{
        printf("\nMain entry.\n");
        return 0;
}
</code>```

Makefile:

```<code>CC=gcc
CFLAGS=-I.

all: *.c
        $(CC) -Os -Wall  *.c -o helloworld
#       $(STRIP) helloworld

clean:
        rm -f a.out helloworld
        rm -f *.o
</code>```

Edit: And I have also added source "package/HelloWorld/Config.in" to 'package/Config.in'
But when I mount my rootfs.ext2 partition I can't find my HelloWorld executable inside /usr/bin .., I am really new to this and don't have any prior knowledge, so could you please explain to me, what am I missing from this, because I'm sure I'm doing something wrong.

UPDATE: The program builds and install at the desired location but when I try to run it like so: ./helloworld, I get: bash: ./helloworld: No such file or directory It has execution rights. What is the matter with it? (I try to run it after I mount the rootfs.ext2 into a ubuntu directory, the target arch for buildroot is i386, so it should be ok, right?)

After building and installing the HelloWorld program, and eventually running it, I'd like to add to init.d so it starts after booting, and replace the HelloWorld with a Qt Window that doesn't need a X server, like this thing here.

The main source of inspiration here.

答:
Minimal tested example on top of 2016.05

GitHub upstream:
https://github.com/cirosantilli/buildroot/tree/in-tree-package-2016.05

This example adds the package source in-tree, which is simple for educational purposes and the way to go if you want to merge back (kudos!),

If you do not intend on merging back (booooh!), it is more likely that you will want to use Buildroot as a git submodule and either:

an out of tree package with BR2_EXTERNAL as shown at: https://github.com/cirosantilli/buildroot/tree/out-of-tree-2016.05

*_OVERRIDE_SRCDIR + other git submodules as explained at: How to modify the source of Buildroot packages for package development?

Files modified:

package/Config.in

```<code>menu "Misc"
    source "package/hello/Config.in"
endmenu
</code>```

package/hello/Config.in

```<code>config BR2_PACKAGE_HELLO
    bool "hello"
    help
        Hello world package.

        http://example.com
</code>```

package/hello/hello.mk

```<code>################################################################################
#
# hello
#
################################################################################

HELLO_VERSION = 1.0
HELLO_SITE = ./package/hello/src
HELLO_SITE_METHOD = local

define HELLO_BUILD_CMDS
    $(MAKE) CC="$(TARGET_CC)" LD="$(TARGET_LD)" -C $(@D)
endef

define HELLO_INSTALL_TARGET_CMDS
    $(INSTALL) -D -m 0755 $(@D)/hello $(TARGET_DIR)/usr/bin
endef

$(eval $(generic-package))
</code>```

package/hello/src/.gitignore

```<code>hello
</code>```

package/hello/src/Makefile

```<code>CC = gcc

.PHONY: clean

hello: hello.c
    $(CC) -o '$@' '$<'

clean:
    rm hello
</code>```

package/hello/src/hello.c

```<code>#include <stdio.h>

int main(void) {
    puts("hello");
}
</code>```

Usage:

```<code>make qemu_x86_64_defconfig
echo 'BR2_PACKAGE_HELLO=y' >> .config
make BR2_JLEVEL=2
qemu-system-x86_64 -M pc -kernel output/images/bzImage -drive file=output/images/rootfs.ext2,if=virtio,format=raw -append root=/dev/vda -net nic,model=virtio -net user
</code>```

From inside qemu:

```<code>hello
</code>```

Expected output:

```<code>hello
</code>```

Tested in Ubuntu 16.04.

Body:
I am trying to add my own program to a small linux, created with Buildroot.
What I've done so far:

I've created a new directory inside my 'buildroot/package/'  called 'HelloWorld'.
Inside 'buildroot/package/HelloWorld' I have : a Config.in, HelloWorld.mk and HelloWorld directory.
Config.in holds this:

     config BR2_PACKAGE_HELLOWORLD
     bool "helloworld"
     default y
     help
             Hello world component.

HelloWorld.mk holds this:

HELLOWORLD_VERSION:= 1.0.0
HELLOWORLD_SITE:= /home/userpc/Downloads/helloworld/
HELLOWORLD_SITE_METHOD:=local
HELLOWORLD_INSTALL_TARGET:=YES

define HELLOWORLD_BUILD_CMDS
        $(MAKE) CC="$(TARGET_CC)" LD="$(TARGET_LD)" -C $(@D) all
endef

define HELLOWORLD_INSTALL_TARGET_CMDS
        $(INSTALL) -D -m 0755 $(@D)/helloworld $(TARGET_DIR)/bin
endef

define HELLOWORLD_PERMISSIONS
       /bin/helloworld f 4755 0 0 - - - - -
endef

$(eval $(generic-package))

(inspiration source)
The HelloWorld directory contains: main.c & Makefile:

main.c :

#include <stdio.h>

int main()
{
        printf("\nMain entry.\n");
        return 0;
}

Makefile:

CC=gcc
CFLAGS=-I.

all: *.c
        $(CC) -Os -Wall  *.c -o helloworld
#       $(STRIP) helloworld

clean:
        rm -f a.out helloworld
        rm -f *.o

Edit: And I have also added source "package/HelloWorld/Config.in" to 'package/Config.in'
But when I mount my rootfs.ext2 partition I can't find my HelloWorld executable inside /usr/bin .., I am really new to this and don't have any prior knowledge, so could you please explain to me, what am I missing from this, because I'm sure I'm doing something wrong.

UPDATE: The program builds and install at the desired location but when I try to run it like so: ./helloworld, I get: bash: ./helloworld: No such file or directory It has execution rights. What is the matter with it? (I try to run it after I mount the rootfs.ext2 into a ubuntu directory, the target arch for buildroot is i386, so it should be ok, right?)

After building and installing the HelloWorld program, and eventually running it, I'd like to add to init.d so it starts after booting, and replace the HelloWorld with a Qt Window that doesn't need a X server, like this thing here.

The main source of inspiration here.

Body:
Minimal tested example on top of 2016.05

GitHub upstream:
https://github.com/cirosantilli/buildroot/tree/in-tree-package-2016.05

This example adds the package source in-tree, which is simple for educational purposes and the way to go if you want to merge back (kudos!),

If you do not intend on merging back (booooh!), it is more likely that you will want to use Buildroot as a git submodule and either:

an out of tree package with BR2_EXTERNAL as shown at: https://github.com/cirosantilli/buildroot/tree/out-of-tree-2016.05

*_OVERRIDE_SRCDIR + other git submodules as explained at: How to modify the source of Buildroot packages for package development?

Files modified:

package/Config.in

menu "Misc"
    source "package/hello/Config.in"
endmenu

package/hello/Config.in

config BR2_PACKAGE_HELLO
    bool "hello"
    help
        Hello world package.

        http://example.com

package/hello/hello.mk

################################################################################
#
# hello
#
################################################################################

HELLO_VERSION = 1.0
HELLO_SITE = ./package/hello/src
HELLO_SITE_METHOD = local

define HELLO_BUILD_CMDS
    $(MAKE) CC="$(TARGET_CC)" LD="$(TARGET_LD)" -C $(@D)
endef

define HELLO_INSTALL_TARGET_CMDS
    $(INSTALL) -D -m 0755 $(@D)/hello $(TARGET_DIR)/usr/bin
endef

$(eval $(generic-package))

package/hello/src/.gitignore

hello

package/hello/src/Makefile

CC = gcc

.PHONY: clean

hello: hello.c
    $(CC) -o '$@' '$<'

clean:
    rm hello

package/hello/src/hello.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

Usage:

make qemu_x86_64_defconfig
echo 'BR2_PACKAGE_HELLO=y' >> .config
make BR2_JLEVEL=2
qemu-system-x86_64 -M pc -kernel output/images/bzImage -drive file=output/images/rootfs.ext2,if=virtio,format=raw -append root=/dev/vda -net nic,model=virtio -net user

From inside qemu:

hello

Expected output:

hello

Tested in Ubuntu 16.04.


问:
Testrunner/framework for both .Net and Javascript?
My team develops software using multiple languages.  We have a server app in .Net and much of our client code is written in JavaScript.  (The client code is actually for xulrunner applications, which don't have good testing tools right now, but I hope that is overcome someday.)

I like the idea, though, of having one testing tool that can run tests for all of our code.  Throwing out the xulrunner problem right now, and just considering .net and Javascript - are there any options for testing and automation to cover both of these areas?  Most of the popular testing tools I have seen seem to be .Net-focused.

Or should I drop my desire to have one testing tool to rule them all, and simply choose the best of breed for each?

答:
I'm using a single testing framework in a somewhat similar scenario - using NUnit to test both .Net and unmanaged C++ code. I just write the tests for the later in managed C++. This was nicer than using CppUnit IMO.

But in your case, there isn't a similar bridge between the .Net and JavaScript worlds that you could use. So you are likely better off using dedicated test frameworks for each platform.

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: oefe


问:
LINQ .ToList() fails on single result
It could be that its late Friday evening and I want to go home, or more likely I just can't see the problem...

I have the fallowing LINQ code:

```<code>mthumbs = itm.Elements(nsr + "thumbnail") != null ?
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null
</code>```

The MediaThumbnail Class looks like:

```<code>public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}
</code>```

and resides in the MediaOptElement class which looks like:

```<code>public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}
</code>```

Some Sample XML:

```<code>   <?xml version="1.0" encoding="UTF-8" ?>
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title>
        <link>http://www.wdbj7.com/sports/?track=rss</link>
        <description>Headlines from wdbj7.com</description>
        <language>en</language>
        <copyright>©2011, wdbj7.com</copyright>
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate>
        <item>
          <title>Brookville improves to 15-0</title>
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link>
          <description><p>The Brookville girls' basketball team graduated two college basketball players last year. That was the last time they lost anything.</p> <p>The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.</p> <p>The Minettes playing at home, had just three wins on the year.  Haley Comer gets two for the home team. Liberty takes the 2-0 lead.  That is when it becomes the Katie Deacon show.</p> <p>The four-year varsity player starts it with the defense.  She gets the steal on one end and a basket on the other.</p> <p>Deacon takes her game behind the three point arc!  That beats the buzzer at the end of the first quarter!</p> <p>Deacon still not done.  She gets another steal and feeds George Mason signee Talisha Watts.<br /><br />Brookville improves to 15-0 with the 57-34 win. <br /><br /></p></description>
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate>
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" />
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" />
       </item>
     </channel>
  </rss>
</code>```

When I run my code, I get the following error:

```<code>   Object reference not set to an instance of an object.
</code>```

The stack trace is:

```<code>   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666
</code>```

I could be wrong, but I think the problem happens when the LINQ query only returns a single result.  However, I need to be able to handle cases when there might only be one media:thumbnail node or many media:thumbnail nodes. Any ideas?!  Thanks!

答:
Your problem is in the following line of code:

```<code>mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
</code>```

Note that it differs from the other 3 in that you use .Value here. This fails if the element does not have attribute "time" - in this case .Attribute() will return null, and accessing a property on that gives you NullReferenceException.

Title: LINQ .ToList() fails on single result

Body:
It could be that its late Friday evening and I want to go home, or more likely I just can't see the problem...

I have the fallowing LINQ code:

mthumbs = itm.Elements(nsr + "thumbnail") != null ?
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null

The MediaThumbnail Class looks like:

public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}

and resides in the MediaOptElement class which looks like:

public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}

Some Sample XML:

   <?xml version="1.0" encoding="UTF-8" ?>
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title>
        <link>http://www.wdbj7.com/sports/?track=rss</link>
        <description>Headlines from wdbj7.com</description>
        <language>en</language>
        <copyright>©2011, wdbj7.com</copyright>
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate>
        <item>
          <title>Brookville improves to 15-0</title>
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link>
          <description>
The Brookville girls' basketball team graduated two college basketball players last year. That was the last time they lost anything.

The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.

The Minettes playing at home, had just three wins on the year.  Haley Comer gets two for the home team. Liberty takes the 2-0 lead.  That is when it becomes the Katie Deacon show.

The four-year varsity player starts it with the defense.  She gets the steal on one end and a basket on the other.

Deacon takes her game behind the three point arc!  That beats the buzzer at the end of the first quarter!

Deacon still not done.  She gets another steal and feeds George Mason signee Talisha Watts.

Brookville improves to 15-0 with the 57-34 win.

</description>
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate>
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" />
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" />
       </item>
     </channel>
  </rss>

When I run my code, I get the following error:

   Object reference not set to an instance of an object.

The stack trace is:

   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666

I could be wrong, but I think the problem happens when the LINQ query only returns a single result.  However, I need to be able to handle cases when there might only be one media:thumbnail node or many media:thumbnail nodes. Any ideas?!  Thanks!

Body:
Your problem is in the following line of code:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

Note that it differs from the other 3 in that you use .Value here. This fails if the element does not have attribute "time" - in this case .Attribute() will return null, and accessing a property on that gives you NullReferenceException.


问:
bootstrap form helper phone wont work
I m trying to make a website using form Bootstrap framework. As part of my code I have

```<code><div class="control-group">
<label class="control-label" for="inputTell">Telephone</label>
<div class="controls">
<input type="text" id="inputTell" class="bfh-phone" data-format="(ddd) ddd-dddd">
</div>
</div>
</code>```

This is the image:

It shouldnt be like that. It shouldn't accept any strings and it should give me the phone format like this:

I already have the necessary JS files in my directory but I am not sure why it is not working.

答:
I've try use type tel and another class</p>

```<code><div class="control-group">
   <input type="tel" class="form-control bfh-phone" data-format="(ddd) ddd-dddd" name="number" required>
</div>
</code>```

Title: bootstrap form helper phone wont work

Body:
I m trying to make a website using form Bootstrap framework. As part of my code I have

Telephone

<input type="text" id="inputTell" class="bfh-phone" data-format="(ddd) ddd-dddd">

This is the image:

It shouldnt be like that. It shouldn't accept any strings and it should give me the phone format like this:

I already have the necessary JS files in my directory but I am not sure why it is not working.

Body:
I've try use type tel and another class

<div class="control-group">
   <input type="tel" class="form-control bfh-phone" data-format="(ddd) ddd-dddd" name="number" required>
</div>