问:
How to update the time every second using "setInterval()" without the time flashing in and out every second?
I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.

Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.

Is there a way to accomplish this and still use the setInterval of 1second?

Here is my code...

```<code><div>
    <li>
        <ul>
        <li id="tmz1">est</li>
        <li id="tmz2">central</li>
        <li>pacific</li>
        </ul>
   </li>

   <div id="output1"></div>
   <div id="output2"></div>
</div>

$(document).ready(function(){

    var output1 = document.getElementById('output1');
    var output2 = document.getElementById('output2');

    document.getElementById('tmz1').onclick = function updateTime(){

        output2.style.display = "none";
        output1.style.display = "block";

        var now = moment();
        var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');

        output1.textContent = humanReadable;
        setInterval(updateTime, 1000);

    }

    updateTime();

});

$(document).ready(function(){

    var output2 = document.getElementById('output2');
    var output1 = document.getElementById('output1');

    document.getElementById('tmz2').onclick = function updateTimeX(){

        output1.style.display = "none";
        output2.style.display = "block";

        var now = moment();
        var humanReadable =
        now.tz("America/New_York").format('hh:mm:ssA');

        output2.textContent = humanReadable;
        setInterval(updateTimeX, 1000);

    }

    updateTimeX();

});
</code>```

答:
Perhaps this will help. I believe you've overcomplicated this just a bit. I've provided comments in the code for you to review.

Note: I did not use moment.js as it is unecessary for your task.

You need:

a time from a Date object

a timezone reference that will
change upon click

an interval that will publish the time (with
the changing TZ)

Someplace to put the output

// place to put the output
const output = document.getElementById('output');
// starting timezone
var tz = 'America/New_York';
// Capture click event on the UL (not the li)
document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);

function changeTZ(e) {
  // e.target is the LI that was clicked upon
  tz = e.target.innerText;
  // toggle highlighted selection
  this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
  e.target.classList.add('selected');
}

// set the output to the time based upon the changing TZ
// Since this is an entire datetime, remove the date with split()[1] and trim it
setInterval(() => {
  output.textContent = new Date(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
  background-color: lightblue;
}</code>```

America/New_York

America/Chicago

America/Los_Angeles

```

Body:
I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.

Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.

Is there a way to accomplish this and still use the setInterval of 1second?

Here is my code...

est

central

pacific

$(document).ready(function(){

    var output1 = document.getElementById('output1');
    var output2 = document.getElementById('output2');

    document.getElementById('tmz1').onclick = function updateTime(){

        output2.style.display = "none";
        output1.style.display = "block";

        var now = moment();
        var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');

        output1.textContent = humanReadable;
        setInterval(updateTime, 1000);

    }

    updateTime();

});

$(document).ready(function(){

    var output2 = document.getElementById('output2');
    var output1 = document.getElementById('output1');

    document.getElementById('tmz2').onclick = function updateTimeX(){

        output1.style.display = "none";
        output2.style.display = "block";

        var now = moment();
        var humanReadable =
        now.tz("America/New_York").format('hh:mm:ssA');

        output2.textContent = humanReadable;
        setInterval(updateTimeX, 1000);

    }

    updateTimeX();

});

Body:
Perhaps this will help. I believe you've overcomplicated this just a bit. I've provided comments in the code for you to review.

Note: I did not use moment.js as it is unecessary for your task.

You need:

a time from a Date object

a timezone reference that will
change upon click

an interval that will publish the time (with
the changing TZ)

Someplace to put the output

// place to put the output
const output = document.getElementById('output');
// starting timezone
var tz = 'America/New_York';
// Capture click event on the UL (not the li)
document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);

function changeTZ(e) {
  // e.target is the LI that was clicked upon
  tz = e.target.innerText;
  // toggle highlighted selection
  this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
  e.target.classList.add('selected');
}

// set the output to the time based upon the changing TZ
// Since this is an entire datetime, remove the date with split()[1] and trim it
setInterval(() => {
  output.textContent = new Date(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);

.selected {
  background-color: lightblue;
}

<div>
  <ul>
    <li class="selected">America/New_York</li>
    <li>America/Chicago</li>
    <li>America/Los_Angeles</li>
  </ul>

  <div id="output"></div>
</div>


来源: stackexchange

问:
Gspread. Move to next column for cell entry if first column is full. How can I do this?
When column A fills up, I want to move to B. I'm able to enter in either A or B but I can't switch between the two if one fails.

Edit: I've determined that the code works when there's no try/except thrown at it.

```<code>def next_available_row(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(1, 2)))
        return str(len(str_list2)+1)
    except:
        str_list2 = list(filter(None, wks.col_values(2, 1)))
        return str(len(str_list2)+1)
##        try:
##            wks.update_acell("A{}".format(next_row), tInput3)
##        except:
        wks.update_acell("B{}".format(next_row), tInput3)
</code>```

So if I block out column A, column B will populate properly. What gives? :|

答:
Got it.  ugly but it works. </p>

```<code>def next_available_row(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(1, 2)))
        return str(len(str_list2)+1)
    except:
        print("unable to do 'A'")

def next_available_rowB(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(2, 1)))
        return str(len(str_list2)+1)
    except:
        print("unable to do 'B'")

        try:
            wks.update_acell("A{}".format(next_row), tInput3)
        except:
            wks.update_acell("B{}".format(next_rowB), tInput3)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When column A fills up, I want to move to B. I'm able to enter in either A or B but I can't switch between the two if one fails.

Edit: I've determined that the code works when there's no try/except thrown at it.

def next_available_row(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(1, 2)))
        return str(len(str_list2)+1)
    except:
        str_list2 = list(filter(None, wks.col_values(2, 1)))
        return str(len(str_list2)+1)
##        try:
##            wks.update_acell("A{}".format(next_row), tInput3)
##        except:
        wks.update_acell("B{}".format(next_row), tInput3)

So if I block out column A, column B will populate properly. What gives? :|

Body:
Got it.  ugly but it works.

def next_available_row(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(1, 2)))
        return str(len(str_list2)+1)
    except:
        print("unable to do 'A'")

def next_available_rowB(wks):
    try:
        str_list2 = list(filter(None, wks.col_values(2, 1)))
        return str(len(str_list2)+1)
    except:
        print("unable to do 'B'")

        try:
            wks.update_acell("A{}".format(next_row), tInput3)
        except:
            wks.update_acell("B{}".format(next_rowB), tInput3)


问:
How to make drop-down menu view as vertical?

site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="site-nav">
            <ul>
                <li>PAVEIKTIE DARBI</li>
                <li class="pakalp">PAKALPOJUMI
                    <ul class="drop-down">
                        <li>ĢENERĀLUZŅĒMĒJS</li>
                        <li>PROJEKTU VADĪBA</li>
                        <li>PROJEKTĒŠANA</li>
                        <li>BŪVDARBU VADĪBA</li>
                        <li>MONTĀŽA</li>
                    </ul>
                </li>
                <li>INŽENIERTEHNISKĀS SISTĒMAS</li>
                <li>KONTAKTI</li>
            </ul>
        </nav></code>```

I've been making this web-page for my new business, and I'm stuck with navigation bar - I can't make it drop as a vertical list. Instead it shows as flex. I wrota a lot of code and clearly messed up somewhere, but I can't find where exactly. Tried everything I could find on the internet (didn't check the dark web though), but I can't fix it.

Here is my CSS

```<code>.site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;
</code>```

Here is my HTML

```<code><nav class="site-nav">
            <ul>
                <li><a href="#">PAVEIKTIE DARBI</a></li>
                <li class="pakalp"><a href="#">PAKALPOJUMI</a>
                    <ul class="drop-down">
                        <li><a href="#">ĢENERĀLUZŅĒMĒJS</a></li>
                        <li><a href="#">PROJEKTU VADĪBA</a></li>
                        <li><a href="#">PROJEKTĒŠANA</a></li>
                        <li><a href="#">BŪVDARBU VADĪBA</a></li>
                        <li><a href="#">MONTĀŽA</a></li>
                    </ul>
                </li>
                <li><a href="#">INŽENIERTEHNISKĀS SISTĒMAS</a></li>
                <li><a href="#">KONTAKTI</a></li>
            </ul>
        </nav>
</code>```

答:
You must not make your
 inline block display.

```<code>.site-nav > ul > li{
   /* This makes the outer ul li elements  horizontal*/
   .display: inline-block;
}

 ul.drop-down li {
    /* This makes the inside ul li to be stacked*/
    display: block;
  }
</code>```

Body:
site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;

PAVEIKTIE DARBI

PAKALPOJUMI

ĢENERĀLUZŅĒMĒJS

PROJEKTU VADĪBA

PROJEKTĒŠANA

BŪVDARBU VADĪBA

MONTĀŽA

INŽENIERTEHNISKĀS SISTĒMAS

KONTAKTI

I've been making this web-page for my new business, and I'm stuck with navigation bar - I can't make it drop as a vertical list. Instead it shows as flex. I wrota a lot of code and clearly messed up somewhere, but I can't find where exactly. Tried everything I could find on the internet (didn't check the dark web though), but I can't fix it.

Here is my CSS

.site-nav {
    position: relative;
    top: 0.5em;
    left: 0;
    display: block;
    width: 80%;
    padding: 0.8em 2em 0 0;
    opacity: .95;
    background: none;
  }

 .site-nav ul li {
    display: inline-block;
    margin-left: 1.5em;
    margin-bottom: 0;
  }

 .drop-down {
    display: none;
  }

 ul li:hover ul {
    display:block;
    position: absolute;
    float: none;
    background-color: rgba(1,80,114,0.50);
    height: 9em;

Here is my HTML

PAVEIKTIE DARBI

PAKALPOJUMI

ĢENERĀLUZŅĒMĒJS

PROJEKTU VADĪBA

PROJEKTĒŠANA

BŪVDARBU VADĪBA

MONTĀŽA

INŽENIERTEHNISKĀS SISTĒMAS

KONTAKTI

Body:
You must not make your <li> inline block display.

.site-nav > ul > li{
   /* This makes the outer ul li elements  horizontal*/
   .display: inline-block;
}

 ul.drop-down li {
    /* This makes the inside ul li to be stacked*/
    display: block;
  }


问:
Is HTTPServerUtility.Transfer is more userful  than Response.Redirect in performance of website in asp.net?
Right now I am reading about .net website performance and scalability.

I read many blog posts and microsoft book about performance and scalability.

In last blog, linked here.

In this blog poing no.6 talking about
 "Use HTTPServerUtility.Transfer instead of Response.Redirect"..

Is it more useful in performance of website and to the point as in the blog that,

"They should only be used when you are transferring people to another physical web server.  For any transfers within your server, use .transfer!  You will save a lot of needless HTTP requests."

Anyone help me how it is more useful in performance than response.redirect?

答:
You should not just blindly start using Server.Transfer instead of Response.Redirect; they are not simply drop-in replacements.

Server.Transfer has another page 'take up' execution where the current one leaves off, giving its output. This saves the Redirect step - A redirect issues a 302 - Moved response to the client, with the new URL to load, then the browser makes that new request. That is what is being 'saved' when you use Server.Transfer instead.

But you can also lose things; Like, your user can become confused when they try to bookmark a page that loaded with a Server.Transfer involved, and find something totally unexpected showing up because Server.Transfer was not used with that eventuality in mind.

You also have to do a little bit of work to make sure you get your request values marshalled over to the 'new' page properly; query string, form values, and the values of server-side controls.

I would call Server.Transfer something to consider when you are more advanced and knowledgeable of the ASP.NET pipeline and the HTTP protocol, and basically... you don't have any question at all when/why you would want to use it.

EDIT: Also; I would not take anything you read on that web site you link too seriously at all. The writer says that you should avoid server-side validation and instead only do it on the client. That, and many of their own recommendations show an extremely limited knowledge of ASP.NET/HTTP. Don't let someone like that make you spend so much time on something so unimportant.

ContentLicense: CC BY-SA 3.0


问:
storing data in state when data is fetched using graphql and apollo client
I have been using react and redux and everytime ,I make a call to some rest api in ComponentDidMount ,I can set a state with it and pass that state onto my child or change that state and play with it .
I can keep that data in my redux too and do all what i want .
I recently started using graphql and I see that as one fetches data inside render using a query , we render the data that we want to and so on .
But I am concerned as how instead of rendering it ,I can store it in some state ,play with it and then pass it down to the child .
I came acroos this link state in apollo but couldn't have a clear understanding of it as what it basically does ?
How to solve this issue of state management and playing with that state which is set by the data coming from the apollo .
I am really missing out this feature of </p>

```<code>this.setState({
  data:(some api data )
)}
</code>```

答:
Suppose I made a query and I want three of my Child Components to share the same data .How will you achieve this with graphql ?

1st method

Data read from api is accessible via the cache - default policy is cache first. Each of children can access data from cache using graphql (HOCs or components). Each of them can use a different query to get data the component really needs. If all of queries fields are subset of parent query - you can use cache-only policy.

2nd method

You can manipulate api data using getDerivedStateFromProps(). You can pass these values directly as props to the childs (w/o using graphql cache access).

3rd method

React classic (pass props down the tree): simply pass data prop (unmodified) to child rendering <Child data={this.props.data} /> (parent inside HOC) or <Child data={data} /> (render prop within <Query/> component)

Body:
I have been using react and redux and everytime ,I make a call to some rest api in ComponentDidMount ,I can set a state with it and pass that state onto my child or change that state and play with it .
I can keep that data in my redux too and do all what i want .
I recently started using graphql and I see that as one fetches data inside render using a query , we render the data that we want to and so on .
But I am concerned as how instead of rendering it ,I can store it in some state ,play with it and then pass it down to the child .
I came acroos this link state in apollo but couldn't have a clear understanding of it as what it basically does ?
How to solve this issue of state management and playing with that state which is set by the data coming from the apollo .
I am really missing out this feature of

this.setState({
  data:(some api data )
)}


问:
Replacing images on mouseover with only childnodes and javascript
I have to place three images side by side, and onmouseover function, when the user moves the mouse over an image , that particular image will be duplicate on the other two images. When the use moves the mouse out from the image, the image will restore as in initial page.
But I have to use childnodes for this. I'm not able to figure this out.

I've tried this following code, but it doesn't do anything.
I tried to paste the code here, but it was getting out onto the body of the message so I made this codepen where you can see it.
So far I'm only to get index[1] and index[2] pic to show up on index[0], but no other changes are happening.
https://codepen.io/anon/pen/xNjezN

```<code>function heroes(q){
    if(q.src == imgArray[0])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[0];
        }
    }
    else if(q.src == imgArray[1])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[1];
        }
    }
    else if(q.src == imgArray[2])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[2];
        }
    }
}
</code>```

If someone can please suggest something.

答:
You're almost there. There are two things to note. One, child nodes is actually a "NodeList", which is only "array-like". It can be converted to an array with Array.from(nodeList).
Second is the line break was being read as a "text" node, so actually showing 7 childNodes. You can filter them out with the Array.prototype.filter() method.

Then once you're working with the actual DOM elements, you can set and reset the src: https://codepen.io/anon/pen/vwjwXm?editors=1010

Body:
I have to place three images side by side, and onmouseover function, when the user moves the mouse over an image , that particular image will be duplicate on the other two images. When the use moves the mouse out from the image, the image will restore as in initial page.
But I have to use childnodes for this. I'm not able to figure this out.

I've tried this following code, but it doesn't do anything.
I tried to paste the code here, but it was getting out onto the body of the message so I made this codepen where you can see it.
So far I'm only to get index[1] and index[2] pic to show up on index[0], but no other changes are happening.
https://codepen.io/anon/pen/xNjezN

function heroes(q){
    if(q.src == imgArray[0])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[0];
        }
    }
    else if(q.src == imgArray[1])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[1];
        }
    }
    else if(q.src == imgArray[2])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[2];
        }
    }
}

If someone can please suggest something.


问:
Is it possible to do epoll on accept event?
Let's suppose I've created a listening socket:

```<code>sock = socket(...);
bind(sock,...);
listen(sock, ...);
</code>```

Is it possible to do epoll_wait on sock to wait for incoming connection? And how do I get client's socket fd after that?

The thing is on the platform I'm writing for sockets cannot be non-blocking, but there is working epoll implementation with timeouts, and I need to accept connection and work with it in a single thread so that it doesn't hang if something goes wrong and connection doesn't come.

答:
Since this answer is the first up in the results in duckduckgo. I will just chime in to say that under GNU/Linux 4.18.0-18-generic (Ubuntu 18.10).

The asynchronously accept an incoming connection using one has to watch for errno value EWOULDBLOCK (11) and then add the socket to epoll read set.

Here is a small shot of scheme code that achieves that:

```<code>(define (accept fd)
  (let ((out (socket:%accept fd 0 0)))
    (if (= out -1)
        (let ((code (socket:errno)))
          (if (= code EWOULDBLOCK)
              (begin
                (abort-to-prompt fd 'read)
                (accept fd))
              (error 'accept (socket:strerror code))))
        out)))
</code>```

In the above (abort-to-prompt fd 'read) will pause the coroutine and add fd to epoll read set, done as follow:

```<code>(epoll-ctl epoll EPOLL-CTL-ADD fd (make-epoll-event-in fd)))
</code>```

When the coroutine is unpaused, the code proceed after the abort to call itself recursively (in tail-call position)

In the code I am working in Scheme, it is a bit more involving since I rely on call/cc to avoid callbacks. The full code is at source hut.

That is all.

Body:
Let's suppose I've created a listening socket:

sock = socket(...);
bind(sock,...);
listen(sock, ...);

Is it possible to do epoll_wait on sock to wait for incoming connection? And how do I get client's socket fd after that?

The thing is on the platform I'm writing for sockets cannot be non-blocking, but there is working epoll implementation with timeouts, and I need to accept connection and work with it in a single thread so that it doesn't hang if something goes wrong and connection doesn't come.

Body:
Since this answer is the first up in the results in duckduckgo. I will just chime in to say that under GNU/Linux 4.18.0-18-generic (Ubuntu 18.10).

The asynchronously accept an incoming connection using one has to watch for errno value EWOULDBLOCK (11) and then add the socket to epoll read set.

Here is a small shot of scheme code that achieves that:

(define (accept fd)
  (let ((out (socket:%accept fd 0 0)))
    (if (= out -1)
        (let ((code (socket:errno)))
          (if (= code EWOULDBLOCK)
              (begin
                (abort-to-prompt fd 'read)
                (accept fd))
              (error 'accept (socket:strerror code))))
        out)))

In the above (abort-to-prompt fd 'read) will pause the coroutine and add fd to epoll read set, done as follow:

(epoll-ctl epoll EPOLL-CTL-ADD fd (make-epoll-event-in fd)))

When the coroutine is unpaused, the code proceed after the abort to call itself recursively (in tail-call position)

In the code I am working in Scheme, it is a bit more involving since I rely on call/cc to avoid callbacks. The full code is at source hut.

That is all.


问:
dart pub version conflicts
I am trying to learn angulardart. I followed starter guide and using IDE intellij.

After I have cloned the repo and then opened index.html in browser directly from intellij I am getting this error

```<code>/usr/local/opt/dart/libexec/bin/pub global run webdev serve web:53322
webdev could not run for this project.
The `build_runner` version – 1.2.3 – is not within the allowed constraint – >=1.3.0 <2.0.0.
The `build_web_compilers` version – 0.4.4+3 – is not within the allowed constraint – >=1.2.0 <3.0.0.
Dart Webdev terminated
</code>```

I have not done any change in any file and everything is as present in the repo. Can someone please help me to understand what is missing or what I am doing wrong?

答:
It seems to me that I asked a noob question. So I went and updated pubspec.yml file and changed dependencies version for build_runner and build_web_compilers to what is shown in error.

This has solved my problem. Leaving the question here in case someone face the same issue in future.

EDITED

Sharing the updated pubspec.yml file here

```<code>name: angular_app
description: A web app that uses AngularDart
version: 0.0.1

environment:
  sdk: '>=2.0.0 <3.0.0'

dependencies:
  angular: ^5.0.0

dev_dependencies:
  angular_test: ^2.0.0
  build_runner: '>=1.3.0 <2.0.0'
  build_test: ^0.10.2
  build_web_compilers: ' >=1.2.0 <3.0.0'
  test: ^1.0.0
</code>```

Title: dart pub version conflicts

Body:
I am trying to learn angulardart. I followed starter guide and using IDE intellij.

After I have cloned the repo and then opened index.html in browser directly from intellij I am getting this error

/usr/local/opt/dart/libexec/bin/pub global run webdev serve web:53322
webdev could not run for this project.
The `build_runner` version – 1.2.3 – is not within the allowed constraint – >=1.3.0 <2.0.0.
The `build_web_compilers` version – 0.4.4+3 – is not within the allowed constraint – >=1.2.0 <3.0.0.
Dart Webdev terminated

I have not done any change in any file and everything is as present in the repo. Can someone please help me to understand what is missing or what I am doing wrong?

Body:
It seems to me that I asked a noob question. So I went and updated pubspec.yml file and changed dependencies version for build_runner and build_web_compilers to what is shown in error.

This has solved my problem. Leaving the question here in case someone face the same issue in future.

EDITED

Sharing the updated pubspec.yml file here

name: angular_app
description: A web app that uses AngularDart
version: 0.0.1

environment:
  sdk: '>=2.0.0 <3.0.0'

dependencies:
  angular: ^5.0.0

dev_dependencies:
  angular_test: ^2.0.0
  build_runner: '>=1.3.0 <2.0.0'
  build_test: ^0.10.2
  build_web_compilers: ' >=1.2.0 <3.0.0'
  test: ^1.0.0


问:
Execute statement every N iterations in Python
I have a very long loop, and I would like to check the status every N iterations, in my specific case I have a loop of 10 million elements and I want to print a short report every millionth iteration.

So, currently I am doing just (n is the iteration counter):

```<code>if (n % 1000000==0):
    print('Progress report...')
</code>```

but I am worried I am slowing down the process by computing the modulus at each iteration, as one iteration lasts just few milliseconds.

Is there a better way to do this? Or shouldn't I worry at all about the modulus operation?

答:
This makes the inner loop lean, and m does not have to be divisible by interval.

```<code>m = 10000000
interval = 1000000
i = 0
while i < m:
    checkpoint = min(m, i+interval)
    for j in xrange(i, checkpoint):
        #do something
    i = checkpoint
    print "progress"
</code>```

Body:
I have a very long loop, and I would like to check the status every N iterations, in my specific case I have a loop of 10 million elements and I want to print a short report every millionth iteration.

So, currently I am doing just (n is the iteration counter):

if (n % 1000000==0):
    print('Progress report...')

but I am worried I am slowing down the process by computing the modulus at each iteration, as one iteration lasts just few milliseconds.

Is there a better way to do this? Or shouldn't I worry at all about the modulus operation?

Body:
This makes the inner loop lean, and m does not have to be divisible by interval.

m = 10000000
interval = 1000000
i = 0
while i < m:
    checkpoint = min(m, i+interval)
    for j in xrange(i, checkpoint):
        #do something
    i = checkpoint
    print "progress"


问:
How to remove the first n lines from multiple files to a single output file using any windows program E.g Python
I use the python script below to remove the first n lines of all text files in a folder.I want the deleted lines to be sent to a single output file.
Here is my code:</p>

```<code>import glob

myfiles = glob.glob("*.txt")

for file in myfiles:

  lines = open(file).readlines()

  open(file, 'w').writelines(lines[4:])
</code>```

答:
I'm not providing a full written programming answer, because there's plenty of those to be found on stackexchange if you look there. Instead here's some hints to get you to where you hopefully need to be.

First, select the lines you want (to keep) from the file after you open it.

```<code>for myline in lines:                # For each line, stored as myline,
                                    # It's upto you to figure out how to only do the first 4...
    mylines.append(myline)          # mylines now contains, the lines you want.

open(removed_lines, 'a').writelines(mylines) # Save the 'removed lines'.
</code>```

Body:
I use the python script below to remove the first n lines of all text files in a folder.I want the deleted lines to be sent to a single output file.
Here is my code:

import glob

myfiles = glob.glob("*.txt")

for file in myfiles:

  lines = open(file).readlines()

  open(file, 'w').writelines(lines[4:])

Body:
I'm not providing a full written programming answer, because there's plenty of those to be found on stackexchange if you look there. Instead here's some hints to get you to where you hopefully need to be.

First, select the lines you want (to keep) from the file after you open it.

for myline in lines:                # For each line, stored as myline,
                                    # It's upto you to figure out how to only do the first 4...
    mylines.append(myline)          # mylines now contains, the lines you want.

open(removed_lines, 'a').writelines(mylines) # Save the 'removed lines'.


问:
Observe LiveData from ListView current Item
Basically i want to retrieve a int(score) generated from the current ListViewItem and assign it back to concrete TextView in my ListView.I am using SharedViewModel with LiveData but when i observe nothing happens.I am using Nav Architecture Component with Single activity.I'll be glad if someone helps.Thank u , here's some code.

public class ListFrag extends Fragment {

```<code>@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

    model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer s) {

            for (int i = 0; i < myListView.getAdapter().getCount(); i++) {

                v =  myListView.getAdapter().getView(i,null, myListView);

                finalScore = v.findViewById(R.id.finalScoreView);

                    if (s != null) {
    itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
                        myListView.setAdapter(itemAdapter);
                       finalScore.setText(String.valueOf(s));

                    }
      ((BaseAdapter)myListView.getAdapter()).notifyDataSetChanged();
            }
        }
    });
}
</code>```

public class SharedViewModel extends ViewModel
{

```<code>private MutableLiveData<Integer> currentScore = new MutableLiveData<>();

public LiveData<Integer> getCurrentScore(){
    return currentScore;
}

public void setCurrentScore(Integer finito) {
    currentScore.setValue(finito);

}
</code>```

}

public class ItemAdapter extends BaseAdapter {

```<code>LayoutInflater mInflater;
String[] items;
String[] bushido;
String[] description;
 TextView finalscorre;
Integer scr;

public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
    items = i;
    bushido = p;
    description = d;
    finalscorre = sc;
    scr = scc;
    mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return items.length;
}

@Override
public Object getItem(int i) {
    return items[i];
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View convertView, ViewGroup parent) {
    View v = mInflater.inflate(R.layout.my_listview_detail, null);
    TextView nameTextView = v.findViewById(R.id.NameTextView);
    TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
    TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
    finalscorre = v.findViewById(R.id.finalScoreView);

    String name = items[i];
    String desc = description[i];
    String bush = bushido[i];

    finalscorre.setText("Waat");
    nameTextView.setText(name);
    descriptionTextView.setText(desc);
    bushidoTextView.setText(bush);

    ItemAdapter.this.notifyDataSetChanged();

    return v;
}
</code>```

}

When i try to assign the LiveData in TextView out of the ListView it works.But when i try this ,nothings happen (no errors and no result).

答:
Adapters act as a bridge between the data (in your case, the string array you pass into the adapter), and the ListView (in your case, myListView). Any change to the ListView needs to be follow these steps:

make desired changes to the data itself

pass this new data to the adapter

adapter updates the list view

I have wrote some example code:

ItemAdapter

```<code>public class ItemAdapter extends BaseAdapter {

    LayoutInflater mInflater;
    String[] items;
    String[] bushido;
    String[] description;
    // TextView finalscorre; // I commented out this TextView please see the comment below
    Integer scr;

    public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
        items = i;
        bushido = p;
        description = d;
        // finalscorre = sc;
        scr = scc;
        mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void updateItems(String[] i, String[] p, String[] d, Integer scc) {
        items = i;
        bushido = p;
        description = d;
        scr = scc;

        // notify the adapter to refresh the list view.
        notifyDataSetChanged()
    }

    @Override
    public int getCount() {
        return items.length;
    }

    @Override
    public Object getItem(int i) {
        return items[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        View v = mInflater.inflate(R.layout.my_listview_detail, null);
        TextView nameTextView = v.findViewById(R.id.NameTextView);
        TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
        TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
        //finalscorre = v.findViewById(R.id.finalScoreView);
        TextView finalscorre = v.findViewById(R.id.finalScoreView);

        String name = items[i];
        String desc = description[i];
        String bush = bushido[i];

        // finalscorre.setText("Waat");
        finalscorre.setText(scr);
        nameTextView.setText(name);
        descriptionTextView.setText(desc);
        bushidoTextView.setText(bush);

        // ItemAdapter.this.notifyDataSetChanged(); Do NOT call this method inside getView

        return v;
    }
}
</code>```

Fragment

```<code>public class ListFrag extends Fragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Create and set adapter just once. Do not create or set new adapter in observer, for loop, etc.
        itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
        myListView.setAdapter(itemAdapter);

        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

        model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer s) {
                itemAdapter.updateItems(items,bushido,description,s);
            }
        });
    }
}
</code>```

I wasn't able to figure out what finalscorre supposed to be so I assumed that this is the text view that stores the final score that you mentioned, and all list view items should have the same value. If this is not the case please clarify in your question.

Also note that while this solution is enough to solve the specific problem you mentioned, their are some other improvements that can be made:

Use RecyclerView instead of ListView.

Instead of maintaining multiple String[], define a POJO that represent the item, and have a single array.

Also, checking this adapter implementation in google sample will help.

Body:
Basically i want to retrieve a int(score) generated from the current ListViewItem and assign it back to concrete TextView in my ListView.I am using SharedViewModel with LiveData but when i observe nothing happens.I am using Nav Architecture Component with Single activity.I'll be glad if someone helps.Thank u , here's some code.

public class ListFrag extends Fragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

    model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer s) {

            for (int i = 0; i < myListView.getAdapter().getCount(); i++) {

                v =  myListView.getAdapter().getView(i,null, myListView);

                finalScore = v.findViewById(R.id.finalScoreView);

                    if (s != null) {
    itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
                        myListView.setAdapter(itemAdapter);
                       finalScore.setText(String.valueOf(s));

                    }
      ((BaseAdapter)myListView.getAdapter()).notifyDataSetChanged();
            }
        }
    });
}

public class SharedViewModel extends ViewModel
{

private MutableLiveData<Integer> currentScore = new MutableLiveData<>();

public LiveData<Integer> getCurrentScore(){
    return currentScore;
}

public void setCurrentScore(Integer finito) {
    currentScore.setValue(finito);

}

}

public class ItemAdapter extends BaseAdapter {

LayoutInflater mInflater;
String[] items;
String[] bushido;
String[] description;
 TextView finalscorre;
Integer scr;

public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
    items = i;
    bushido = p;
    description = d;
    finalscorre = sc;
    scr = scc;
    mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return items.length;
}

@Override
public Object getItem(int i) {
    return items[i];
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View convertView, ViewGroup parent) {
    View v = mInflater.inflate(R.layout.my_listview_detail, null);
    TextView nameTextView = v.findViewById(R.id.NameTextView);
    TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
    TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
    finalscorre = v.findViewById(R.id.finalScoreView);

    String name = items[i];
    String desc = description[i];
    String bush = bushido[i];

    finalscorre.setText("Waat");
    nameTextView.setText(name);
    descriptionTextView.setText(desc);
    bushidoTextView.setText(bush);

    ItemAdapter.this.notifyDataSetChanged();

    return v;
}

}

When i try to assign the LiveData in TextView out of the ListView it works.But when i try this ,nothings happen (no errors and no result).

Body:
Adapters act as a bridge between the data (in your case, the string array you pass into the adapter), and the ListView (in your case, myListView). Any change to the ListView needs to be follow these steps:

make desired changes to the data itself

pass this new data to the adapter

adapter updates the list view

I have wrote some example code:

ItemAdapter

public class ItemAdapter extends BaseAdapter {

    LayoutInflater mInflater;
    String[] items;
    String[] bushido;
    String[] description;
    // TextView finalscorre; // I commented out this TextView please see the comment below
    Integer scr;

    public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
        items = i;
        bushido = p;
        description = d;
        // finalscorre = sc;
        scr = scc;
        mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void updateItems(String[] i, String[] p, String[] d, Integer scc) {
        items = i;
        bushido = p;
        description = d;
        scr = scc;

        // notify the adapter to refresh the list view.
        notifyDataSetChanged()
    }

    @Override
    public int getCount() {
        return items.length;
    }

    @Override
    public Object getItem(int i) {
        return items[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        View v = mInflater.inflate(R.layout.my_listview_detail, null);
        TextView nameTextView = v.findViewById(R.id.NameTextView);
        TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
        TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
        //finalscorre = v.findViewById(R.id.finalScoreView);
        TextView finalscorre = v.findViewById(R.id.finalScoreView);

        String name = items[i];
        String desc = description[i];
        String bush = bushido[i];

        // finalscorre.setText("Waat");
        finalscorre.setText(scr);
        nameTextView.setText(name);
        descriptionTextView.setText(desc);
        bushidoTextView.setText(bush);

        // ItemAdapter.this.notifyDataSetChanged(); Do NOT call this method inside getView

        return v;
    }
}

Fragment

public class ListFrag extends Fragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Create and set adapter just once. Do not create or set new adapter in observer, for loop, etc.
        itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
        myListView.setAdapter(itemAdapter);

        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

        model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer s) {
                itemAdapter.updateItems(items,bushido,description,s);
            }
        });
    }
}

I wasn't able to figure out what finalscorre supposed to be so I assumed that this is the text view that stores the final score that you mentioned, and all list view items should have the same value. If this is not the case please clarify in your question.

Also note that while this solution is enough to solve the specific problem you mentioned, their are some other improvements that can be made:

Use RecyclerView instead of ListView.

Instead of maintaining multiple String[], define a POJO that represent the item, and have a single array.

Also, checking this adapter implementation in google sample will help.


问:
Refactoring problem from class to function with hooks
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

```<code>//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts
</code>```

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
          console.log('-+- showing data1 -+-')
          console.log(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
          console.log('-+- showing data2 -+-')
          console.log(data)
        }
      })
  },[])

That shows '-+- showing data2 -+- with
(5) [{…}, {…}, {…}, {…}, {…}]0: {id: 14, title: "qsdf", body: "qsdf", created_at: "2019-05-26T13:07:58.006Z", updated_at: "2019-05-26T13:07:58.006Z"}1: {id: 15, title: "qsdf", body: "egg", created_at: "2019-05-26T17:47:48.323Z", updated_at: "2019-05-26T17:47:48.323Z"}2: {id: 16, title: "qdf", body: "qdf", created_at: "2019-05-26T17:48:52.257Z", updated_at: "2019-05-26T17:48:52.257Z"}3: {id: 17, title: "qsdf", body: "h", created_at: "2019-05-26T19:49:41.108Z", updated_at: "2019-05-26T19:49:41.108Z"}4: {id: 18, title: "qsdf", body: "123", created_at: "2019-05-26T19:59:38.002Z", updated_at: "2019-05-26T19:59:38.002Z"}length: 5__proto__: Array(0)


问:
Compression for ActiveMQ to ActiveMQ
I do have two ActiveMQ brokers connected and do forward messages from broker one to broker two automatically. This is done by following configuration:

```<code><networkConnectors>
    <networkConnector name="linkToRemote" uri="static(tcp://172.19.63.3:61616)?jms.useCompression=true" staticBridge="true">
        <staticallyIncludedDestinations>
           <queue physicalName="xyz.queue"/>
        </staticallyIncludedDestinations>
    </networkConnector>
</networkConnectors>
</code>```

Everything except the compression is working fine. My messages are 180KB in size. I have seen that the traffic is not compressed at all. Is jms.useCompression=true not functional? Has someone any alternatives to compress the traffic between two brokers? What about ssh tunnels if compression in ActiveMQ this is not working? My ActiveMQ version is 5.14.13.

答: I am now using autossh and compression. This combination works great. Active MQ does not compress the messages well if we use many small messages as it does not share a common compression dictionary.</p>

Title: Compression for ActiveMQ to ActiveMQ

Body:
I do have two ActiveMQ brokers connected and do forward messages from broker one to broker two automatically. This is done by following configuration:

<networkConnectors>
    <networkConnector name="linkToRemote" uri="static(tcp://172.19.63.3:61616)?jms.useCompression=true" staticBridge="true">
        <staticallyIncludedDestinations>
           <queue physicalName="xyz.queue"/>
        </staticallyIncludedDestinations>
    </networkConnector>
</networkConnectors>

Everything except the compression is working fine. My messages are 180KB in size. I have seen that the traffic is not compressed at all. Is jms.useCompression=true not functional? Has someone any alternatives to compress the traffic between two brokers? What about ssh tunnels if compression in ActiveMQ this is not working? My ActiveMQ version is 5.14.13.


问:
How to bind function to object property?
There is a class with methods:

```<code>public add() {}
public delete(item: Ivoice) {}
</code>```

And method for mapping these methods inside object:

```<code>    this.invoices = data.map(item => {
            item.add = this.add;
            item.edit = this.delete;
            return item;
   });
</code>```

Then in template I tried to call method as:

```<code><div *ngFor="let item of items; let i = index">
  <span (click)="item.add(item)">
</div>
</code>```

But it does not work.

答:
Well, The Simplest Way would be:
Have a Method:

```<code>public void executeClickOrSomething(YourType type){
    type.add(type)
}
</code>```

And Then you can do this in the template:

```<code><div *ngFor="let item of invoices; let i = index">
  <span (click)="executeClickOrSomething(item)">
</div>
</code>```

An Advice:
Always have separate methods for Complex scenarios. Although This doesn't Sound that complex but still, Angular is still under development so maybe they'll fix it in the Future...

NOTE:
If You are thinking of changing the Original DataSource/Array(In this case), then you should overwrite that element in that DataSource/Array as Well..

Body:
There is a class with methods:

public add() {}
public delete(item: Ivoice) {}

And method for mapping these methods inside object:

    this.invoices = data.map(item => {
            item.add = this.add;
            item.edit = this.delete;
            return item;
   });

Then in template I tried to call method as:

But it does not work.

Body:
Well, The Simplest Way would be:
Have a Method:

public void executeClickOrSomething(YourType type){
    type.add(type)
}

And Then you can do this in the template:

<div *ngFor="let item of invoices; let i = index">
  <span (click)="executeClickOrSomething(item)">
</div>

An Advice:
Always have separate methods for Complex scenarios. Although This doesn't Sound that complex but still, Angular is still under development so maybe they'll fix it in the Future...

NOTE:
If You are thinking of changing the Original DataSource/Array(In this case), then you should overwrite that element in that DataSource/Array as Well..


问:
How do I achieve negative padding in CSS?
I am looking for a way to effectively achieve negative padding in CSS.

The Problem

I have an h1 element on my web page that currently has the following code associated with it:

h1 {
  background-color: #375E97;
  color: #FFFFFF;
  font-size: 50px;
  font-family: 'Righteous', cursive;
  text-transform: uppercase;
  text-align: center;
  padding: 0;
  margin: 0 auto;
  height: 49px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link href="https://fonts.googleapis.com/css?family=Righteous|Roboto:400,700,400i" rel="stylesheet">
</head>

<body>
  <h1>Lorem Ipsun Al</h1>
</body></code>```

You can see that since I have added: height: 49px;, the text looks as if it is flowing into the rest of the page. I want to achieve this look, but also for the top of the text, not just the bottom.

What I Have Tried

I have tried:

Setting both padding and margin to 0 for the h1 element.

Playing with various values for vertical-align.

Setting height to many different values.

Setting all the h1's parent elements' padding and margin to 0.

I believe that the problem I am facing is that the top of the font I am using (and most fonts) has some space. This is why I want to be able to achieve a negative padding, to move the text up on the screen without moving the content box.

答: Use a negative margin on the inner content to achieve the same thing as negative padding would.</p>

Body:
I am looking for a way to effectively achieve negative padding in CSS.

The Problem

I have an h1 element on my web page that currently has the following code associated with it:

h1 {
  background-color: #375E97;
  color: #FFFFFF;
  font-size: 50px;
  font-family: 'Righteous', cursive;
  text-transform: uppercase;
  text-align: center;
  padding: 0;
  margin: 0 auto;
  height: 49px;
}

  <link href="https://fonts.googleapis.com/css?family=Righteous|Roboto:400,700,400i" rel="stylesheet">

Lorem Ipsun Al

You can see that since I have added: height: 49px;, the text looks as if it is flowing into the rest of the page. I want to achieve this look, but also for the top of the text, not just the bottom.

What I Have Tried

I have tried:

Setting both padding and margin to 0 for the h1 element.

Playing with various values for vertical-align.

Setting height to many different values.

Setting all the h1's parent elements' padding and margin to 0.

I believe that the problem I am facing is that the top of the font I am using (and most fonts) has some space. This is why I want to be able to achieve a negative padding, to move the text up on the screen without moving the content box.


问:
SEO, Paging in DataList, How to add all the URLs
I am using a DataList along with paging with the help of a PagedDataSource. The user moves through pages with the help of next and previous button.

Now, because of that, I am able to create sitemap for the first list of data in all pages and because of it, I am not able to create XML sitemap for it.

How to sort this matter out.

Please note that I am also using URL rewriting using Intelligencia URL Reqriter to change the url from www.mywebsite.com/subject.aspx?subject=NICE-SUBJECT to www.mywebsite.com/subjects/NICE-SUBJECT.aspx.

In this page, there is paging to show the various data, say tutorials, so I am able to create sitemap for the first page only.

答:
Well, I followed this tutorial. It had some problems (When you click page 1, page 2 is displayed and if you click pg 2, page 3 is displayed).But it gave me nice starting point.

What I did was to use a page query string and use it set the page index of the PagedDataSource.


问:
How to use parameters in query in several places?
I'm using java PreparedStatement to set two parameters in a query begin time and end time. But in my query, I need to use it in two places. Can I make some query variables or make my request shorter?

```<code>SELECT * FROM publicutilities.orders
WHERE (works_begin between '2019-05-26 09:00:00' and '2019-05-26 14:00:00' OR works_end between '2019-05-26 09:00:00' and '2019-05-26 14:00:00')
</code>```

Something like this:

```<code>SELECT * FROM publicutilities.orders
VARIABLE begin_time = ?
VARIABLE end_time = ?
WHERE (works_begin between begin_time and end_time OR works_end between begin_time and end_time)
</code>```

答:
Following this tutorial http://www.mysqltutorial.org/mysql-variables/

I think your SQL query should look like:

```<code>SET @begin_time := '2013-01-17 00:00:00';
SET @end_time := '2013-01-17 00:00:00';
SELECT * FROM publicutilities.orders
WHERE (works_begin between @begin_time and @end_time OR works_end between @begin_time and @end_time)
</code>```

I tried it on my mysql server and it works. Hope it does on yours too.

Body:
I'm using java PreparedStatement to set two parameters in a query begin time and end time. But in my query, I need to use it in two places. Can I make some query variables or make my request shorter?

SELECT * FROM publicutilities.orders
WHERE (works_begin between '2019-05-26 09:00:00' and '2019-05-26 14:00:00' OR works_end between '2019-05-26 09:00:00' and '2019-05-26 14:00:00')

Something like this:

SELECT * FROM publicutilities.orders
VARIABLE begin_time = ?
VARIABLE end_time = ?
WHERE (works_begin between begin_time and end_time OR works_end between begin_time and end_time)

Body:
Following this tutorial http://www.mysqltutorial.org/mysql-variables/

I think your SQL query should look like:

SET @begin_time := '2013-01-17 00:00:00';
SET @end_time := '2013-01-17 00:00:00';
SELECT * FROM publicutilities.orders
WHERE (works_begin between @begin_time and @end_time OR works_end between @begin_time and @end_time)

I tried it on my mysql server and it works. Hope it does on yours too.


问:
Add rows to pandas dataframe using column of dictionaries
I have a dataframe like this:

```<code>matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])
</code>```

```<code>   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}
</code>```

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

```<code>ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1
</code>```

Any help would be much appreciated :)

答:
Expand the dictionary by using apply with pd.Series and use concat to concatenate that to your other column (ordernum). See below for your in-between result of df2.
Now to turn every column into a row, use melt, then use query to drop all the 0-rows and finally assign the cumcount to get the index (after ordering) and add 1 to start counting from 1, not 0.

```<code>df2 = pd.concat([df[['ordernum']], df['dict_of item_counts'].apply(pd.Series)], axis=1)
(df2.melt(id_vars='ordernum', var_name='key')
.query('value != 0')
.sort_values(['ordernum', 'key'])
.assign(ordernum_index = lambda df: df.groupby('ordernum').cumcount().add(1)))
#   ordernum key  value  ordernum_index
#0       222   a      1               1
#2       222   b      3               2
#4       222   c      2               3
#6       222   d      1               4
#1       333   a      1               1
#7       333   d      1               2
</code>```

Now df2 looks like:

```<code>#   ordernum  a  b  c  d
#0       222  1  3  2  1
#1       333  1  0  0  1
</code>```

Body:
I have a dataframe like this:

matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])

   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1

Any help would be much appreciated :)

Body:
Expand the dictionary by using apply with pd.Series and use concat to concatenate that to your other column (ordernum). See below for your in-between result of df2.
Now to turn every column into a row, use melt, then use query to drop all the 0-rows and finally assign the cumcount to get the index (after ordering) and add 1 to start counting from 1, not 0.

df2 = pd.concat([df[['ordernum']], df['dict_of item_counts'].apply(pd.Series)], axis=1)
(df2.melt(id_vars='ordernum', var_name='key')
.query('value != 0')
.sort_values(['ordernum', 'key'])
.assign(ordernum_index = lambda df: df.groupby('ordernum').cumcount().add(1)))
#   ordernum key  value  ordernum_index
#0       222   a      1               1
#2       222   b      3               2
#4       222   c      2               3
#6       222   d      1               4
#1       333   a      1               1
#7       333   d      1               2

Now df2 looks like:

#   ordernum  a  b  c  d
#0       222  1  3  2  1
#1       333  1  0  0  1


问:
defining global const string variable to be accessed by threads in function calls
Allow a constant string to be globally accessed by various threads calling a function.

I have the following code which chooses a random char from a list of chars (the permitted alphabet) and appends it to form a random word. I am using this for a genetic algorithm but when I am trying to parallelize it to make it faster (homework assignment) but it ends up going slower. After asking my professor and fixing most of the problems, the last detail is that my alphabet doesn't allow multiple threads to read at the same time.

I have tried defining GENES then using #pragma omp threadprivate(GENES) which is the command that my professor said would work.

I tried

```<code>const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ"
#pragma omp threadprivate(GENES)
</code>```

Which returns this when compiled.

```<code>error: ‘GENES’ declared ‘threadprivate’ after first use
</code>```

I also tried

```<code>string GENES;
#pragma omp threadprivate(GENES)
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ;
</code>```

which returns:

```<code>error: ‘GENES’ declared ‘threadprivate’ after first use
#pragma omp threadprivate(GENES)
                             ^
error: ‘GENES’ does not name a type
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
</code>```

Finally I tried defining GENES in the threads and passing them as a parameter or hard encoding them into the function. All of these make the program slower.

I expected the program to go faster, but it actually goes slower, from 0.5 sec to 1-3 sec after adding threads. I checked and this is not due to the time in creating the threads.

This should be fixed by making the string accessible by all threads but I can't seem to compile and run any solutions I have found successfully.

答:
So I finally got it to compile with #pragma omp threadprivate(GENES) using the following code thanks to a friend:

```<code>extern const string GENES;
#pragma omp threadprivate(GENES)
const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ";
</code>```

Body:
Allow a constant string to be globally accessed by various threads calling a function.

I have the following code which chooses a random char from a list of chars (the permitted alphabet) and appends it to form a random word. I am using this for a genetic algorithm but when I am trying to parallelize it to make it faster (homework assignment) but it ends up going slower. After asking my professor and fixing most of the problems, the last detail is that my alphabet doesn't allow multiple threads to read at the same time.

I have tried defining GENES then using #pragma omp threadprivate(GENES) which is the command that my professor said would work.

I tried

const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ"
#pragma omp threadprivate(GENES)

Which returns this when compiled.

error: ‘GENES’ declared ‘threadprivate’ after first use

I also tried

string GENES;
#pragma omp threadprivate(GENES)
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ;

which returns:

error: ‘GENES’ declared ‘threadprivate’ after first use
#pragma omp threadprivate(GENES)
                             ^
error: ‘GENES’ does not name a type
GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";

Finally I tried defining GENES in the threads and passing them as a parameter or hard encoding them into the function. All of these make the program slower.

I expected the program to go faster, but it actually goes slower, from 0.5 sec to 1-3 sec after adding threads. I checked and this is not due to the time in creating the threads.

This should be fixed by making the string accessible by all threads but I can't seem to compile and run any solutions I have found successfully.

Body:
So I finally got it to compile with #pragma omp threadprivate(GENES) using the following code thanks to a friend:

extern const string GENES;
#pragma omp threadprivate(GENES)
const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ";


问:
Generic Interface with composed interfaces and multiple concrete implementations
I want to use a generic interface, that can take other interfaces as properties, that use a concrete implementation. How do I create the pattern, if possible, and how do I resolve the implementation in the service collection. This is going to be used alongside a unit of work and the repository pattern.

I've been trying different techniques and implementations through code. Some have been able to compile, but at runtime they have not been able to get resolved. Part of the question is - can the approach be done, the other have I not resolved this correctly.

```<code>public class GenericInterface<T, U> : IGenericInterface<T, U>
{
    public T InterfaceOne { get; set; }     // IInterfaceOne
    public U InterfaceTwo { get; set; }     // IInterfaceTwo
}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteImplementation : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        throw new System.NotImplementedException();
    }

    public void DoTwo()
    {
        throw new System.NotImplementedException();
    }

    public void DoThree()
    {
        throw new System.NotImplementedException();
    }

    public void DoFour()
    {
        throw new System.NotImplementedException();
    }
}

public class Resolver {

    public void Resolve() {

        // Should be able to use the interfaces and reference the ConcreteImplementation....!?
        // How to resolve in a service collection?
        var genericComposedInterfaces = new GenericInterface<IInterfaceOne, IInterfaceTwo>();
    }
}
</code>```

The desired result is that it should first serve the purpose and secondly get resolved within the service collection / when it is called.

Update

Thanks for the help. So I think I was caught between two minds of what I was trying to achieve. All I really wanted was one backing class that was exposed via two interfaces that could be combined into one generic interface. I think the following works.

Generic Interface takes two or several interfaces.

```<code>public interface ITestGenericInterface<T, U>
{
    T InterfaceOne { get; }
    U InterfaceTwo { get; }
}

public class TestGenericInterface<T, U> : ITestGenericInterface<T, U>
{
    public TestGenericInterface(T interfaceOne, U interfaceTwo)
    {
        InterfaceOne = interfaceOne;
        InterfaceTwo = interfaceTwo;
    }

    public T InterfaceOne { get; }
    public U InterfaceTwo { get; }
}
</code>```

The interfaces with a class that might be used with the above interface.

```<code>public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteClass : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        Console.WriteLine("DoOne()");
    }
    public void DoTwo()
    {
        Console.WriteLine("DoTwo()");
    }

    public void DoThree()
    {
        Console.WriteLine("DoDoThreeOne()");
    }

    public void DoFour()
    {
        Console.WriteLine("DoFour()");
    }
}
</code>```

Registering in the service collection. I don't think I was registering the interface / implementation correctly before which could have been an issue.

```<code>  services.AddScoped<IInterfaceOne, ConcreteClass>();
  services.AddScoped<IInterfaceTwo, ConcreteClass>();
  services.AddScoped(typeof(ITestGenericInterface<,>), typeof(TestGenericInterface<,>));
</code>```

Trying it out

```<code>public interface ITestRunner
{
    void Start();
}

public class TestRunner : ITestRunner
{
    private readonly ITestGenericInterface<IInterfaceOne, IInterfaceTwo> _genericTest;

    public TestRunner(
        ITestGenericInterface<IInterfaceOne, IInterfaceTwo> genericTest
        )
    {
        _genericTest = genericTest;
    }

    public void Start()
    {
        // Interface One
        _genericTest.InterfaceOne.DoOne();
        _genericTest.InterfaceOne.DoTwo();

        // Interface Two
        _genericTest.InterfaceTwo.DoThree();
        _genericTest.InterfaceTwo.DoFour();
    }
}
</code>```

I appreciate that this was probably simpler than it sounded in my initial question. As Flavio Francisco put me on the right track with his first answer, I will up vote it and mark as the answer. Hopefully this will help someone else. Many thanks.

答:
Looks that what you are trying to do is something like this:

```<code>public interface IGeneric<T, U>
{
    T InterfaceOne { get; }

    U InterfaceTwo { get; }
}

public class GenericClass : IGeneric<IInterfaceOne, IInterfaceTwo>
{
    private readonly IInterfaceOne interfaceOne;
    private readonly IInterfaceTwo interfaceTwo;

    public GenericClass(IInterfaceOne interfaceOne, IInterfaceTwo interfaceTwo)
    {
        this.interfaceOne = interfaceOne;
        this.interfaceTwo = interfaceTwo;
    }

    public IInterfaceOne InterfaceOne { get { return this.interfaceOne; } }
    public IInterfaceTwo InterfaceTwo { get { return this.interfaceTwo; } }
}

public class ClassOne : IInterfaceOne
{
    public void DoOne()
    {
        throw new NotImplementedException();
    }

    public void DoTwo()
    {
        throw new NotImplementedException();
    }
}

public class ClassTwo : IInterfaceTwo
{
    public void DoFour()
    {
        throw new NotImplementedException();
    }

    public void DoThree()
    {
        throw new NotImplementedException();
    }
}
</code>```

Resolver:

```<code>       IGeneric<IInterfaceOne, IInterfaceTwo> genericClass = new GenericClass(new ClassOne(), new ClassTwo());

       genericClass.InterfaceOne.DoOne();
</code>```

Hope that what you want is it.

Body:
I want to use a generic interface, that can take other interfaces as properties, that use a concrete implementation. How do I create the pattern, if possible, and how do I resolve the implementation in the service collection. This is going to be used alongside a unit of work and the repository pattern.

I've been trying different techniques and implementations through code. Some have been able to compile, but at runtime they have not been able to get resolved. Part of the question is - can the approach be done, the other have I not resolved this correctly.

public class GenericInterface<T, U> : IGenericInterface<T, U>
{
    public T InterfaceOne { get; set; }     // IInterfaceOne
    public U InterfaceTwo { get; set; }     // IInterfaceTwo
}

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteImplementation : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        throw new System.NotImplementedException();
    }

    public void DoTwo()
    {
        throw new System.NotImplementedException();
    }

    public void DoThree()
    {
        throw new System.NotImplementedException();
    }

    public void DoFour()
    {
        throw new System.NotImplementedException();
    }
}

public class Resolver {

    public void Resolve() {

        // Should be able to use the interfaces and reference the ConcreteImplementation....!?
        // How to resolve in a service collection?
        var genericComposedInterfaces = new GenericInterface<IInterfaceOne, IInterfaceTwo>();
    }
}

The desired result is that it should first serve the purpose and secondly get resolved within the service collection / when it is called.

Update

Thanks for the help. So I think I was caught between two minds of what I was trying to achieve. All I really wanted was one backing class that was exposed via two interfaces that could be combined into one generic interface. I think the following works.

Generic Interface takes two or several interfaces.

public interface ITestGenericInterface<T, U>
{
    T InterfaceOne { get; }
    U InterfaceTwo { get; }
}

public class TestGenericInterface<T, U> : ITestGenericInterface<T, U>
{
    public TestGenericInterface(T interfaceOne, U interfaceTwo)
    {
        InterfaceOne = interfaceOne;
        InterfaceTwo = interfaceTwo;
    }

    public T InterfaceOne { get; }
    public U InterfaceTwo { get; }
}

The interfaces with a class that might be used with the above interface.

public interface IInterfaceOne
{
    void DoOne();
    void DoTwo();
}

public interface IInterfaceTwo
{
    void DoThree();
    void DoFour();
}

public class ConcreteClass : IInterfaceOne, IInterfaceTwo
{
    public void DoOne()
    {
        Console.WriteLine("DoOne()");
    }
    public void DoTwo()
    {
        Console.WriteLine("DoTwo()");
    }

    public void DoThree()
    {
        Console.WriteLine("DoDoThreeOne()");
    }

    public void DoFour()
    {
        Console.WriteLine("DoFour()");
    }
}

Registering in the service collection. I don't think I was registering the interface / implementation correctly before which could have been an issue.

  services.AddScoped<IInterfaceOne, ConcreteClass>();
  services.AddScoped<IInterfaceTwo, ConcreteClass>();
  services.AddScoped(typeof(ITestGenericInterface<,>), typeof(TestGenericInterface<,>));

Trying it out

public interface ITestRunner
{
    void Start();
}

public class TestRunner : ITestRunner
{
    private readonly ITestGenericInterface<IInterfaceOne, IInterfaceTwo> _genericTest;

    public TestRunner(
        ITestGenericInterface<IInterfaceOne, IInterfaceTwo> genericTest
        )
    {
        _genericTest = genericTest;
    }

    public void Start()
    {
        // Interface One
        _genericTest.InterfaceOne.DoOne();
        _genericTest.InterfaceOne.DoTwo();

        // Interface Two
        _genericTest.InterfaceTwo.DoThree();
        _genericTest.InterfaceTwo.DoFour();
    }
}

I appreciate that this was probably simpler than it sounded in my initial question. As Flavio Francisco put me on the right track with his first answer, I will up vote it and mark as the answer. Hopefully this will help someone else. Many thanks.

Body:
Looks that what you are trying to do is something like this:

public interface IGeneric<T, U>
{
    T InterfaceOne { get; }

    U InterfaceTwo { get; }
}

public class GenericClass : IGeneric<IInterfaceOne, IInterfaceTwo>
{
    private readonly IInterfaceOne interfaceOne;
    private readonly IInterfaceTwo interfaceTwo;

    public GenericClass(IInterfaceOne interfaceOne, IInterfaceTwo interfaceTwo)
    {
        this.interfaceOne = interfaceOne;
        this.interfaceTwo = interfaceTwo;
    }

    public IInterfaceOne InterfaceOne { get { return this.interfaceOne; } }
    public IInterfaceTwo InterfaceTwo { get { return this.interfaceTwo; } }
}

public class ClassOne : IInterfaceOne
{
    public void DoOne()
    {
        throw new NotImplementedException();
    }

    public void DoTwo()
    {
        throw new NotImplementedException();
    }
}

public class ClassTwo : IInterfaceTwo
{
    public void DoFour()
    {
        throw new NotImplementedException();
    }

    public void DoThree()
    {
        throw new NotImplementedException();
    }
}

Resolver:

       IGeneric<IInterfaceOne, IInterfaceTwo> genericClass = new GenericClass(new ClassOne(), new ClassTwo());

       genericClass.InterfaceOne.DoOne();

Hope that what you want is it.


问:
How to get elementById in Nativescript?
I'm using nativescript with vue.js and I'm trying to do something like DOM operation. This is sample code from my template:

```<code><Label textWrap="true">
    <FormattedString id="formString"
      backgroundColor="yellow"
      effectiveHeight="100"
      effectiveWidth="100%">
      <Span text="This text has a " />
    </FormattedString>
 </Label>
</code>```

I want to get tag element FormattedString by his id - formString
 In javascript is like this:

let fs = doument.getElementById('formString');

How can I do this in Nativescript-Vue?
I know that there is library nativescript-dom, but I don't want to use whole library for simple getById.

答:
Use Label.getViewById("formString") to access the attributes of FormattedString.

getViewById is the nearest equivalent to the javascript getElementById

Hope this helps

Title: How to get elementById in Nativescript?

Body:
I'm using nativescript with vue.js and I'm trying to do something like DOM operation. This is sample code from my template:

    <FormattedString id="formString"
      backgroundColor="yellow"
      effectiveHeight="100"
      effectiveWidth="100%">

    </FormattedString>

I want to get tag element FormattedString by his id - formString
 In javascript is like this:

let fs = doument.getElementById('formString');

How can I do this in Nativescript-Vue?
I know that there is library nativescript-dom, but I don't want to use whole library for simple getById.


问:
How to run openwrt image as a docker image
I'm new to docker. What I want to do is run an openwrt bin file inside a docker container and compile socketman source inside that docker image.
this is the image file
http://download.gl-inet.com.s3.amazonaws.com/firmware/b1300/v1/qsdk-b1300-2.272.bin</p>

答:
I wanted to compile some source(socketman) to openwrt. Here is my work around.

I downloaded the sdk for appropriate firmware. (There is the bin file and also the SDK.)

If you have sdk then you dont have to build the toolchain. tools are already there. (If you get SDK then the build process faster other than compiling whole firmware)

Then cd into the sdk directory. place your source code inside the package directory.

then in the terminal (inside the appropriate SDK folder) type make menuconfig

Then star the package you want to build
save and exit

then type make if you want to log out the debug info type make -j4 V=s
-j4 means the available # of cors, you can put the # of cores that you have on your computer.nproc

If you want to build inside a docker container.

install docker

then clone ubuntu docker image

run the docker image with interactive shell

git clone or wget SDK folder into the docker container

then proceed all the above steps.


问:
Updating a dictionary privately?
I have a class object that receives some data. Based on a condition, I need that data to change, but only under that condition. Problem I'm running into is that when I call dict.update() , it updates the original variable too. So a subsequent request comes in, and now that original variable is "tainted" so to speak, and is using overridden information that it shouldn't have.

Assuming a dictionary like this:

```<code>my_attributes = {"test": True}
</code>```

And some logic like this:

```<code>class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes.update({"test": False})
</code>```

The end result:

```<code>>>> my_attributes
{'test': False}
</code>```

So, the next time MyClass is used, those root attributes are still overridden.

I've seemingly gotten around this problem by re-defining attributes:

```<code>class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes = {}
            attributes.update(my_attributes)
            attributes.update({"test": False})
</code>```

This has seemed to get around the problem, but I'm not entirely sure this is a good, or even the right, solution to the issue.

答:
Something like this:

```<code>class MyClass(object):
    @staticmethod
    def my_condition():
        return True

    def __init__(self, attributes):
        self.attributes = {**attributes}
        if MyClass.my_condition():
            self.attributes["test"] = False

my_attributes = {"test": True}
cls_obj = MyClass(my_attributes)
print("my_attributes:", my_attributes, "class.attributes:", cls_obj.attributes)
</code>```

Output:

```<code>my_attributes: {'test': True} class.attributes: {'test': False}
</code>```

Title: Updating a dictionary privately?

Body:
I have a class object that receives some data. Based on a condition, I need that data to change, but only under that condition. Problem I'm running into is that when I call dict.update() , it updates the original variable too. So a subsequent request comes in, and now that original variable is "tainted" so to speak, and is using overridden information that it shouldn't have.

Assuming a dictionary like this:

my_attributes = {"test": True}

And some logic like this:

class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes.update({"test": False})

The end result:

>>> my_attributes
{'test': False}

So, the next time MyClass is used, those root attributes are still overridden.

I've seemingly gotten around this problem by re-defining attributes:

class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes = {}
            attributes.update(my_attributes)
            attributes.update({"test": False})

This has seemed to get around the problem, but I'm not entirely sure this is a good, or even the right, solution to the issue.

Body:
Something like this:

class MyClass(object):
    @staticmethod
    def my_condition():
        return True

    def __init__(self, attributes):
        self.attributes = {**attributes}
        if MyClass.my_condition():
            self.attributes["test"] = False

my_attributes = {"test": True}
cls_obj = MyClass(my_attributes)
print("my_attributes:", my_attributes, "class.attributes:", cls_obj.attributes)

Output:

my_attributes: {'test': True} class.attributes: {'test': False}


问:
Set time to 00:00:00
I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.

This is my code :

```<code>/**
     * Resets milliseconds, seconds, minutes and hours from the provided date
     *
     * @param date
     * @return
     */
    public static Date trim(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);

        return calendar.getTime();
    }
</code>```

The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.

I know that 12:00:00 == 00:00:00!

I am using AppEngine. Is this an appengine bug, problem or some other issue?  Or does it depend on something else?

答:
tl;dr

```<code>myJavaUtilDate                                 // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant()                                   // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) )         // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate()                                 // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )   // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
</code>```

java.time

You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.

Date ➙ Instant

A java.util.Date represent a moment in UTC. Its replacement is Instant. Call the new conversion methods added to the old classes.

```<code>Instant instant = myJavaUtilDate.toInstant() ;
</code>```

Time zone

Specify the time zone in which you want your new time-of-day to make sense.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
</code>```

ZonedDateTime

Apply the ZoneId to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but different wall-clock time.

```<code>ZonedDateTime zdt = instant.atZone( z ) ;
</code>```

Changing time-of-day

You asked to change the time-of-day. Apply a LocalTime to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.

```<code>LocalTime lt = LocalTime.of( 15 , 30 ) ;  // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
</code>```

First moment of day

But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).

Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.

```<code>LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
</code>```

Adjust to UTC

If you need to go back to UTC, extract an Instant.

```<code>Instant instant = zdtFirstMomentOfDay.toInstant() ;
</code>```

Instant ➙ Date

If you need a java.util.Date to interoperate with old code not yet updated to java.time, convert.

```<code>java.util.Date d = java.util.Date.from( instant ) ;
</code>```

Title: Set time to 00:00:00

Body:
I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.

This is my code :

/**
     * Resets milliseconds, seconds, minutes and hours from the provided date
     *
     * @param date
     * @return
     */
    public static Date trim(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);

        return calendar.getTime();
    }

The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.

I know that 12:00:00 == 00:00:00!

I am using AppEngine. Is this an appengine bug, problem or some other issue?  Or does it depend on something else?

Body:
tl;dr

myJavaUtilDate                                 // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant()                                   // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) )         // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate()                                 // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )   // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.

java.time

You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.

Date ➙ Instant

A java.util.Date represent a moment in UTC. Its replacement is Instant. Call the new conversion methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

Time zone

Specify the time zone in which you want your new time-of-day to make sense.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

ZonedDateTime

Apply the ZoneId to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but different wall-clock time.

ZonedDateTime zdt = instant.atZone( z ) ;

Changing time-of-day

You asked to change the time-of-day. Apply a LocalTime to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.

LocalTime lt = LocalTime.of( 15 , 30 ) ;  // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;

First moment of day

But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).

Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.

LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;

Adjust to UTC

If you need to go back to UTC, extract an Instant.

Instant instant = zdtFirstMomentOfDay.toInstant() ;

Instant ➙ Date

If you need a java.util.Date to interoperate with old code not yet updated to java.time, convert.

java.util.Date d = java.util.Date.from( instant ) ;