Show GPX traces in Ubuntu Touch

Question: Do you know if there is a map app that allows to show GPX traces?
I have downloaded the GPX file of a hiking route and I would like to follow it on the OSMscout map or something similar.
Answer: I expect you have tried Bike maps although it is very limited? I am still awaiting for someone to make foxtrotGPS work on touch devices; so far not impressed with Osmscout or uNav.
Comment: I tried all the gps related apps but in the end I gave up and installed android. Of course not just for that but also. I found the ubuntu phone too limited to be used as main (only) phone
Comment: I tend to agree - Ubuntu touch has still got a long way to go to compete with the commercial alternatives. It is still pretty much a beta at best. I am going to persevere as I really want it to work.

Show GPX traces in Ubuntu Touch


2 Approaches on Google Maps not working

Question: I have tried two approaches to implement Google maps on android and both are not working.
1st Approach - I implemented maps using fragments (com.google.android.gms.maps.MapFragment). In this approach I get an error and the it asks me to UPDATE GOOGLE PLAY store.
2nd approach - I implemented maps using MapView (com.google.android.maps.MapView). I get a server 3 error in this approach and display shows me a blank grid.
I even generated a new api key, but it was of no use.
Thanks in advance
Comment: I have tested it on both - device and emulator
Comment: It was updated with latest version.
Answer: you can use map v2 with :
        <fragment
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

with extends FragmentActivity
https://developers.google.com/maps/documentation/android/start
I went to the
Settings -> Software updates -> Check now

in Phone downloaded and installed some updates.
This time when i clicked on
Get Google Play Services (In the application )

Market automatically got updated to Google Play.
Map is getting displayed properly.
Comment: I tried this also and getting the same Update error. I could not find the software updates in settings.
Comment: Here are the logs:

`
09-02 06:39:01.339: W/GooglePlayServicesUtil(1053): Google Play services out of date.  Requires 3225100 but found 3136130

09-02 06:39:01.619: D/dalvikvm(1053): GC_CONCURRENT freed 248K, 14% free 2522K/2912K, paused 13ms+26ms, total 153ms

09-02 06:39:01.719: D/gralloc_goldfish(1053): Emulator without GPU emulation detected.

09-02 06:39:15.439: I/jdwp(1053): Ignoring second debugger -- accepting and dropping`
Comment: Blank map most of the times is problem with the API key, try to follow the given link here in the answer

2 Approaches on Google Maps not working


Icon for cancel action to distinguish from delete icon

Question: I'm dealing with a space sensitive environment where I have a Save/Cancel actions that need to be icons.  In the same area the user can also delete items, using something similar to the one in this link (this can't be changed unfortunately - I would like a trash can).
What are some good options for a cancel icon that is easily distinguishable from the delete icon?
Answer: Any actionable icon without descriptive text is probably a bad idea, just because it leads to confusion like this. Though, the most common icon I've seen for "cancel", besides the red X, is the "No" symbol:

(Source: http://iconfinder.net/data/icons/c9d/cancel.png)
Comment: Often on Mac the delete icon used in toolbars are a circle with a slash through. Using it for cancel may confuse Mac users if they are used to it meaning delete.
Comment: @neoneye: I think this is bound to confuse some users in any case...
Comment: Agreed. Alas I cannot fit text on the screen in this case.  I'll use different shades of red, and have a tooltip, so I'll call that good enough.  Thanks!
Answer: The only things that I can think of given your constraints are either a circle with a slash through it (a la no smoking signs) or a back arrow if something like that makes sense in your UI.
Comment: This is what I ended up doing, but Russell's linked pic has the same idea, and he answered first - so I accepted his.
Answer: Can your save/cancel actions be translated as commit/abort? If so, you could pick some icons that are further away from the traditional save/cancel iconography.
Comment: Not really.  Good thought though. I'll keep it in mind for future reference.
Answer: A trashcan might be unambiguously "delete" instead of "cancel".
Answer: If the "cancelling" action could reasonable be reframed as a "closing" action, then you may have a few more choices. There are some very familiar icons used to "Close" parts of a user interface, including on the browser window you're using now.
Answer: Use the file icon and overlay the cancel button suggested by RussellUresti on top.


my Python mini game. It confuses me :-(

Question: I am using Python 2.7 and learning Python The Hard Way book.
However, I got some creative ideas and I want to make some changes in this exercise: http://learnpythonthehardway.org/book/ex35.html
So I wrote my own code:
from sys import exit

times_in_exchange_path = 0
asked_for_help = 0

def exchange_path():
    print "Hola! You are about to get to the very dangerous point, kid!"
    print "You are independent from now. With luck..."

    action = raw_input('...')

    if 'what' in action:
        print 'I said you are on your own now. No one is gonna help you',
        print "with anything..."
        exchange_path()
    elif 'creepy' in action:
        print "I found it creepy, too. Kid. Take me out of here with you."
        print "Is that OK?"
        haunted = False

        decision = raw_input()

        if decision == 'agree':
            print "Finally. I'm free!"
            haunted = True
            times_in_exchange_path = times_in_exchange_path + 1
            start()
        else:
            dead("I will make you know what pain really is!!?! >:(")

    else:
        dead("A shadow barged into you, and you broke your neck.")

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    try:
        how_much = int(choice)
    except:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"

        if haunted:
            print "\nHowever... I can't just let you get away easily like this."
            print '"Why??" - I asked'
            print "You belong to the gold mine now!!"
            print '"What do you mean??" - I replied in fear'
            print "Power requires sacrifice. Muhahahhaha!"
            dead(" ")
        else:
            exit(0)

    else:
        dead("You greedy bastard! It's a trap for you!")

def bear_room():
    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?\n"
    bear_moved = False

    if haunted:
        print "...Wait. The bear suddenly shouts at you, break the window",
        print "and runs far far away."
        print "Let's go to the door, kid...\n\n"
        gold_room()
    else:
        while True:
            choice = raw_input("> ")

            if choice == "take honey":
                dead("The bear looks at you then slaps your face off.")
            elif choice == "taunt bear" and not bear_moved:
                print "The bear has moved from the door. You can go through",
                print "it now."
                bear_moved = True
            elif choice == "taunt bear" and bear_moved:
                dead("The bear gets pissed off and chews your leg off.")
            elif choice == "open door" and bear_moved:
                gold_room()
            else:
                print "I got no idea what that means."

def cthulhu_room():
    print "Here you see the great evil Cthulhu."
    print "He, it, whatever stares at you and goes insane."
    print "Do you flee for your life or he eats your head?"
    cthulhu_dead = False

    choice = raw_input("> ")

    if cthulhu_dead:
        print "There's nothing here, kid. Except of the light and a dead body."
        print "Let's go!\n...\n\n"
        start()
    else:

        if "flee" in choice:
            start()
        elif "head" in choice:
            dead("Well that was tasty!")
        elif "fight" in choice:

            if haunted:
                print "With mysterious distraction, the Cthulhu turns his back",
                print "at you. You use the shiny magical spear nearby to kill",
                print "the monster."
                cthulhu_dead = True
                print "\n...\n"
                start()
            else:
                dead("Awesome tasty head you have!")

        else:
            cthulhu_room()

def dead(why):
    print why, "\n\nGood job! You died."
    exit(0)

def first_assist():
    asked_for_help += 1

    if asked_for_help in range(4, 6):
        print "Stop! You are attracting them!"
        print "A portal shows up and you are walking into it...\n\n"
    elif asked_for_help > 5:
        dead("Those demons rise from the ground. And burn you down!")
    else:
        print "Hi! I am your beautiful assistance."
        print "As you got lost in here, I will show you the way."
        print "You have to know that all three paths are dangerous, and there",
        print "is no way out of here.\nSo, try to survive with glory."
        print '"left", "right" and "front" are the first three spells you use.'
        print "There's a mighty power near here. Have a pure heart, and know",
        print "that you will never have to touch that evil power..."
        print "Good luck from here... Be wise."
    start()

def start():
    print "You are in a dark room."
    print "There is a door to your right and left."
    print 'And a middle path, full of darkness, in front of you.'
    print "Which one do you dare to take?"

    choice = raw_input("> ")

    if choice == "left":
        bear_room()
    elif choice == "right":
        cthulhu_room()
    elif choice == "front":

        if times_in_exchange_path == 0:
            exchange_path()
        else:
            print "You feel something stopping you from entering this place. \n"
            start()

    elif "help" in choice:
        first_assist()
    else:
        dead("You stumble around the room until you starve.")

start()

But for some reasons, my code doesn't work properly.
It first prints out to the screen the lines like this:

You are in a dark room.
There is a door to your right and left
And a middle path, full of darkness
Which one do you dare to take?

And then, whatever I type in, the program rises errors. I don't know why.
Please help me fix this game.
Thank you very very much. :-)
Comment: In what way does it not work properly? Does it give you an error message? Is it hanging? Is it causing general mayhem and raising of the dead?
Comment: Ah, yes. the old `cause('mayhem')` and `dead.raise()` situation. Hate when that happens.
Answer: Firstly, when you're asking a question, you should include the error messages.
Traceback (most recent call last):
  File "game.py", line 174, in <module>
    start()
  File "game.py", line 159, in start
    cthulhu_room()
  File "game.py", line 120, in cthulhu_room
    cthulhu_room()
  File "game.py", line 104, in cthulhu_room
    start()
  File "game.py", line 159, in start
    cthulhu_room()
  File "game.py", line 104, in cthulhu_room
    start()
  File "game.py", line 157, in start
    bear_room()
  File "game.py", line 66, in bear_room
    if haunted:
NameError: global name 'haunted' is not defined

This is the error that is got when I took a right after fleeing Cthulhu.
The issue here is that haunted is defined inside of the function exchange_path. The problems is that variables defined inside functions are local to that function, and can't be used inside other functions. Doing so results in two unqiue variables (albeit having the same name).
The simple solution (although not recommended) is to define haunted in the outer most scope, at the very start of the script along with asked_for_help and times_in_exchange_path, and then use the keyword global to tell python that the variable haunted is actually a global variable and not a local variable.
...
asked_for_help = 0
haunted = False    # Or False, whatever you choose

def exchange_path():
    global haunted
    ...
    if haunted:
        ...

Generally, global variable are discouraged and you should instead pass variables as parameters instead.

my Python mini game. It confuses me :-(


Probability proof and graphs

Question: Let $G = (V, E)$ be a graph with vertex set $V$ and edge set $E$. A subset $I$ of $V$ is called an independent set if for any two distinct vertices $u$ and $v$ in $I$, $(u, v)$ is not an edge in $E$.
Let $n$ and $m$ denote the number of vertices and edges in $G$, respectively, and assume that $m ≥ n/2$.
Consider the following algorithm, in which all random choices made are mutually independent:

Algorithm IndepSet(G):
Step 1: Set $H = G$.
Step 2: Let $d = 2m/n$. For each vertex $v$ of $H$, with probability $1−1/d$,
delete the vertex $v$, together with its incident edges, from $H$.
Step 3: As long as the graph $H$ contains edges, do the following: Pick
an arbitrary edge $(u, v)$ in $H$, and remove the vertex $u$, together with
its incident edges, from $H$.
Step 4: Let $I$ be the vertex set of the graph $H$. Return $I$.

• Argue that the set $I$ that is returned by this algorithm is an independent set in G.
Any help appreciated. Have thought of anything even to get the question started over the past 6 hours.
Answer: The argument follows from Step 3. You need only to argue that none of the vertices in $I$ are adjacent, but if they were, then you would not have completed Step 3 - "As long as the graph $H$ contains edges..." - which only terminates when $H$ is completely disconnected. Note also that it removes edges by removing vertices (rather than just the edge itself), therefore given vertices $u$ and $v$ in $V(H)$, if $(u,v)$ is not in $E(H)$, it was not in $E(G)$ to begin with.
Therefore for every distinct pair of vertices $u$ and $v$ in $I$, the edge $(u,v)$ is not in $G$, hence $I$ is an independent set.
Note that Step 2 is performing a similar task to Step 3, it just picks some vertices at random, regardless of whether it has an incident edges, but the same argument as above holds.

Probability proof and graphs


Varnish removes Public IP from X-Forwarded-for

Question: I am facing an issue where varnish is not sending Intermediary proxy IP or Public IP in a particular case.
Scenario is as below :

Some Hotel / Company has squid proxy configured and all traffic for Internet is routed via Squid.
User accessing my company's site first hits the Load Balancer then Varnish  & then Apache
Apache is configured with mod_geoip. The code on my site does the Country redirection based on the IP address.

Problem :

When an user (Behind that squid proxy) accessing my company's website behind Load Balancer -> VARNISH -> Apache  - Here apache gets only Internal IP (His Private IP) & Load Balancer Internal IP as X-forwarded-for and Hence the IP based redirection FAILS!

In Apache logs (Configured to log X-Forwarded-IP) I see that Users Private IP & then My Load Balancers Private IP.
18.104.22.168, LoadBalancerIP - - [.......]

The same user when accesses another site which does NOT have Varnish, hits Load Balancer -> Apache - Here apache gets Users Private IP & Users Public IP as X-forwarded-for and IP based country redirection works fine.

In Apache logs (Configured to log X-Forwarded-IP) I see that Users Private IP and then his Public IP is also logged.
184.108.40.206, PublicIP - - [.......]
My Varnish Config is as below.
       if (req.restarts == 0) {
                   if (req.http.x-forwarded-for) {
                 set req.http.X-Forwarded-For =
                     req.http.X-Forwarded-For + ", " + client.ip;
                   } else {
                 set req.http.X-Forwarded-For = client.ip;
                   }
           }

PS: I've already Google'd all links I could find and every link gives the following Varnish Config
For now to get this issue resolved, I had to bypass varnish and now website traffic is directly hitting Apache but I need to get Varnish back in place to server content from Cache and Speedy delivery.
Will appreciate if someone can guide me to how resolve this issue.
Thanks!
Comment: Hello, I've gathered Varnish logs for the above mentioned issue and have pasted @ http://pastebin.ca/2353444
Answer: The above mentioned issue has been resolved. Credit goes to Mithrandir @ Varnish IRC Channel. Thanks!
Below mentioned changes were required to resolve the issue.
At the start of the default.vcl add :
import std;

Below  " if (req.http.x-forwarded-for) " add :
std.collect(req.http.x-forwarded-for);

Do varnish configtest & reload. This should start showing the Public IP.
Below is the explanation from the documentation of vmod_std :

collect
   Prototype
          collect(HEADER header)

   Return value
          Void

   Description
          Collapses the header, joining the headers into one.

   Example
          std.collect(req.http.cookie); This will collapse several Cookie:
          headers into one, long cookie header.

Answer: In Varnish 4 this is not needed anymore, see upgrade info here


Have anyone done research on cinemagraphs?

Question: I've been toying with the idea of using cinemagraphs in my web design for a while. On one hand I love the aesthetics of full-screen video backdrops and I think they can become key in giving my users a "memorable experience", improving retention, but on the other hand they are very hard to implement without becoming a distraction from the content on the site.
So I started experimenting with videos where the visuals are mostly static videography - either a cinemagraph where the video has been edited so it is basically a still with just a tiny portion of the image being "live", or by taking a short segment of video, slowing it down and looping it seemlesly so there is only very subtle movement.
I think these approaches works really well. Besides reducing the distractions and risk of motion-sickness, they are generally smaller file-size wise (and I make sure that videos have a fallback image and are loaded asynchronously). But I still have not made any tests besides asking people about their general opinions.
Does any of you know of some larger-scale research investigating this problem or do you have some practical experiences that I may draw on?
The general opinion seems to be that videos look good but kill engagement and conversion. I think the truth is a little more complex than that. What do you think?
Comment: This is a really interesting approach. However, depending on how images are used, I feel like they will be really distracting and nobody will pay attention to anything else. Anyways, it's worth testing! (I 'm not aware of  any research on the subject. )
Answer: This technique is used in film to provide cognitive and emotive time and space for reflection and consideration by the audience. As such, it's a very good idea for any kind of website confident about its content and the context within which it will be visited.
Give up on research in this area. You will have to do your own. It comes down to making creative decisions based on the emotive and reflective load you'd like to place on your audience. Effectiveness of communication starts with someone caring to communicate and isn't a purely numbers game, yet.
Boil it down to success and reverence, if you like. Gauge, for yourself, how significant the cinematic "pauses" are to the film, its story, reputation, reach and reverence of the European and Japanese grand masters of slow paced films. Then watch other films that do this from other cultures. The Russians make some extremely pared back films. Then begin to notice that even films like those by Michael Bay use these same techniques, too.
You have a good idea. Matching it with your content, messages and purposes will be art, not science.
Comment: I certainly plan to make my own research and I agree it is not all about the numbers. You would need a more qualitative approach. But I'm still curious to know about the experiences of others who have tread this path before me. But thanks for pointing me towards cinemagraphy in movies - that was not something I had thought about and a great place to look for inspiration.


UITextField - (void)drawPlaceholderInRect:(CGRect)rect returns different CGRect height in iOS 7

Question: I tried to subclass UITextField to draw custom placehoder. In iOS 6 this works fine but in iOS 7 I got a different CGRect height.
The UITextField frame is (0, 0, 500, 45). I added a left padding of 20 by overriding
- (CGRect)editingRectForBounds:(CGRect)bounds;
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
- (CGRect)textRectForBounds:(CGRect)bounds;
Calling the method below to do so:
- (CGRect)makeRectFromBounds:(CGRect)bounds
              withTopPadding:(CGFloat)topPadding
              andLeftPadding:(CGFloat)leftPadding
{
    return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(topPadding, leftPadding, 0, 0));

}

Because I want a different placeHolder text color, I override
- (void)drawPlaceholderInRect:(CGRect)rect
- (void)drawPlaceholderInRect:(CGRect)rect {

    [[UIColor colorWithRed:121.0/255.0
                     green:113.0/255.0
                      blue:107.0/255.0
                     alpha:1.0] setFill];

    [self printRect:rect from:__FUNCTION__];

    [[self placeholder] drawInRect:rect withFont:self.font];
}

The rectangle I'm printing is the following:
iOS 7: -Rect (X: 0.0, Y:0.0, W:480.0, H:44.0)

iOS 6: -Rect (X: 0.0, Y:0.0, W:480.0, H:26.0)

Any idea if this is a bug or am I doing something wrong?
Comment: I had the same problem and the best solution for me is: [Set custom color and draw placeholder vertically centered on iOS 5/6/7](http://stackoverflow.com/a/19220775/2243451)
Answer: Use the following instead:
[textfield setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

Comment: Sorry because I rushed in a couple of days ago by focusing on the problem (the different rect size) rather than changing the color and letting the system align it.
Comment: But stil, it's quite nasty to mingle with private API like that. But I guess it's an Objective-C "feature".
Comment: Is this app store safe?
Comment: Yes. No issues with this.
Comment: Pretty sure this broke with iOS 8
Comment: this is not safe because it use the private API
Answer: In iOS 7 the default value for contentVerticalAlignment changed from "top" to "center" (with no documentation that I could see).  In "center" mode iOS adjusts the result of the rectForBounds methods before drawing into them.  You should probably set contentVerticalAlignment = UIControlContentVerticalAlignmentTop when overriding any of textRectForBounds methods so iOS will use the rect exactly as specified.
Comment: Tried it. In my case, I need it in the center, so I set it to UIControlContentVerticalAlignmentCenter and it's still aligned to the top.
Comment: Could you set contentVerticalAlignment to "top" and then center it yourself in textRectForBounds?  If it's top-aligned I think iOS will use whatever rect you give it; it only has to change things if it's center-aligned.
Comment: @Cyupa, I am facing the same issue. Did you get any work around?
Comment: @Roshni Hi, no. I wasn't able to find a logical, documented explanation to this behavior. The solution was a dirty if check on the systemVersion property on the UIDevice singleton. I am not pleased with it, but it will do until I find the real reason.
Answer: Since iOS7 is new nowadays, so many people faces framing issue with iOS7.
To all of them, I just want say that it is so easy and there isn't any issue with iOS7. It's just because you don't know how to take benefits from the latest OS feature provided by Apple.
@Cyupa : You just need to apply autosizing and mask your textfield.
it could be one or more from following.

UIViewAutoresizingFlexibleBottomMargin
UIViewAutoresizingFlexibleTopMargin
UIViewAutoresizingFlexibleLeftMargin
UIViewAutoresizingFlexibleRightMargin
UIViewAutoresizingFlexibleHeight
UIViewAutoresizingFlexibleWidth

if you apply proper autosizingmask to your textfield, you will get your desired frame for your view (Here textfield)
Comment: Thanks for the suggestion but it has no effect. I do appreciate your idea and haven't taught of it in the first place. Sadly, it doesn't help.
Answer: I also met this problem, not found why yet, but if you want to have the same behavior on both iOS6 and iOS7, you can try this:
- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect rect = [super textRectForBounds:bounds];
    rect = CGRectMake(20, rect.origin.y-4, rect.size.width-20, rect.size.height);
    return rect;
}

and you may need to set:
theLabel.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;

Answer: check the system version and return the UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(topPadding, leftPadding, 0, 0));
you can check device version as
if(([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0))
{

}

Comment: Yes, I know about this but I wouldn't call it a solution because the OS returns different values. I'm looking for the logical explanation of why that CGRect differs in iOS 7. Thanks anyway.
Comment: Likewise, I would like to know the real underlying issue as well and avoid fragmented fixes throughout the code like this.
Comment: Rick's suggestion was correct but I rushed in by focusing on the problem rather than what I expected from the UITextField. It's still weird, but it solves my problem, changing the placeholder text color.
Answer: i solved issue by using this property
textField.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;

It's working for both iOS6 and iOS7.
Answer: Ricky's solution worked for me with the addition this value has to be set each time AFTER placeholder text changed. I overwrote setPlaceholder to do that.
It replaces the need to overwrite drawPlaceholderInRect, if you want another placeholder color, therefore vertical alignment will be correct automatically. Of course this does not answer the question, why IOS 7.0 behaves like that, but it might solve your actual problem.
- (void) setPlaceholder: (NSString*)placeholderText {

    [super setPlaceholder:placeholderText];

    [self setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}

It should be mentioned, that some people discourage this bypassing of public interfaces, so do it on your own risk!
See also:
Change UITextField's placeholder text color programmatically
Comment: As you wrote yourself: "Because I want a different placeHolder text color, I override drawPlaceholderInRect". This is the connection. If you do NOT overwrite it, vertical alignment will be correct, regardless of contentVerticalAlignment - at least as long as you don't overwrite other functions, that might mess up the rect (e.g. for your left padding). Please vote this down, too, if you think, I lie to you, by saying it worked for me, and / or I dont know what I'm talking about.
Comment: No, it does not work, I have tried it, even tough I did not believed it would actually work. What does the placeholder color has to do with the placeholder frame?
Comment: Oh, I see now. Sorry about that. I got confused, I focused on the problem (the rect size) rather than what I was looking after in the first place: changing the placeholder text color. So I'll give you the bounty for the explanation and I'll have to apologize. Thanks for the help. But I'll have to give Ricky the correct answer because he was first and I rushed in like a fool with him too.


Number of keys that match a string

Question: I have the following hash:
{
  "day_mon"=>"on", "day_tue"=>"on", "day_wed"=>"on", "day_thu"=>"on",
  "day_fri"=>"on", "day_sat"=>"on", "day_sun"=>"on"
}

How can I count the number of keys in the hash that match the string "day"?
Answer: There's no need to create a temporary array:
h.count { |k,_| k.start_with?("day") }
  #=> 7

I've assumed that the key must begin with "day", but if not:
h.count { |k,_| k =~ /day/ }
  #=> 7

Answer: Like this:
h.keys.grep(/day/).count

EDIT: Because Cary Swoveland is completely correct,
h.each_key.lazy.grep(/day/).count

TIMTOWTDI :D
Answer:
Hash.keys returns an array of the keys in hash
Array.select filters that array based on the regex /day/
Array.count counts the number of elements in the filtered array:
hash.keys.select { |key| key =~ /day/ }.count

Number of keys that match a string


PHP:: Get POST Request Content

Question: I'm sending a POST request using WebClient.UploadData() method (C#) to my webserver. The packet sent to my webserver looks like so:
POST / HTTP/1.1
Host: {ip}
Content-Length: {length}
Expect: 100-continue
Connection: Keep-Alive

{buffer_content}

As the {buffer_content} is nowhere assigned in the $_POST array, I have the following question...
Question: How do I read the {buffer_content} with PHP?
I've stumbled upon file_get_contents('php://input'), but I'm unsure whether that is recommended to do.
Comment: Have you tried having a `var_dump($_POST);` ?
Comment: There is nothing wrong with php://input. It's the raw, unparsed body of the request and sometimes the best option (if the body is not a set of key-value pairs for example). However, keep in mind that the stream was read-once until php 5.6.
Comment: What is the status code of the POST request?
Comment: @Rangad Thank you guys. It seems I will be using php://input after all.
Answer: Use the php://input stream:
$requestBody = file_get_contents('php://input');

This is the recommended way to do this and, in PHP 7.0, the only way. Previously, there was sometimes a global variable called $HTTP_RAW_POST_DATA, but whether it existed would depend on an INI setting, and creating it hurt performance. That variable was deprecated and removed.
Beware that prior to PHP 5.6, you can only read php://input once, so make sure you store it.
Once you have your body, you can then decode it from JSON or whatever, if you need that:
$requestBody = json_decode($requestBody) or die("Could not decode JSON");

PHP:: Get POST Request Content


Heroku database configuration specifies nonexistent mysql adapter

Question: I can't seem to overcome the above error on heroku. I am running rails 3 with the mysql2 gem locally just fine, but this seems to break when moving to heroku.
First, I am using ClearDB.
Second, when I deploy and try to run heroku run rake db:migrate, heroku tells me I need to add the mysql gem and the activerecord-mysql-adapter. Why on earth would this happen when I am using mysql2?
Third, when I add mysql and the adapter to my project, and I get past the issue of heroku telling me I need those gems in my project. So, I run rake db:migrate again, and, now I get different error...
rake aborted!
database configuration specifies nonexistent mysql adapter
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.9/lib/active_record/connection_adapters/abstract/connection_specification.rb:133:in `establish_connection'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.9/lib/active_record/railtie.rb:82:in `block (2 levels) in <class:Railtie>'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/lazy_load_hooks.rb:25:in `each'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/lazy_load_hooks.rb:25:in `on_load'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.9/lib/active_record/railtie.rb:74:in `block in <class:Railtie>'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/initializable.rb:30:in `instance_exec'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/initializable.rb:30:in `run'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/initializable.rb:55:in `block in run_initializers'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/initializable.rb:54:in `each'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/initializable.rb:54:in `run_initializers'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/application.rb:136:in `initialize!'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/railtie/configurable.rb:30:in `method_missing'
/app/config/environment.rb:5:in `<top (required)>'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/dependencies.rb:251:in `require'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/dependencies.rb:251:in `block in require'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/dependencies.rb:236:in `load_dependency'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/dependencies.rb:251:in `require'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/application.rb:103:in `require_environment!'
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/application.rb:297:in `block (2 levels) in initialize_tasks'

When I check out my database.yml, I see that heroku has injected postgresql as the adapter, however the error outputed clearly states mysql...  If anybody can help me on this issue I would really appreciate it. I don't know what to do with heroku...
Answer: Heroku injected postgresql because you failed to specify the heroku config property DATABASE_URL.
I give detailed instructions in this post - https://stackoverflow.com/a/17815729/1626020
But in a nutshell you need to set it using something like this:
heroku config:set DATABASE_URL=mysql2://bb06ca765fb123:email@example.com/heroku_703eded6aebc123?reconnect=true

Remember your database.yml is completely ignored by Heroku.  That's right, ignored.  The DATABASE_URL is all that matters.
Comment: `mysql2://` was the solution, by default cleardb uses `mysql://`
Answer: Heroku uses Postgresql.
You could use mysql2 in your dev/test environments and postgresql in production (i.e. on Heroku).
group :development, :test do
  gem 'mysql2'
end

group :production do
  gem 'pg'
end


Integration of $(\tan x\sec x)^3$

Question: How do you integrate the following function? I've been struggling with this one for quite a while now. Any help would be very much appreciated.
$$\int(\tan(x)\sec(x))^3dx$$
Answer: The key facts for tangent and secant product integrals are that the derivative of $\tan(x)$ is $\sec(x)^2$ and the derivative of $\sec(x)$ is $\sec(x) \tan(x)$. So the situation is good if you have only one factor of tangent or if you have two factors of secant. Here you will achieve the first one by making two of the factors of tangent into secants:
$$\int \tan(x)^3 \sec(x)^3 dx = \int \sec(x)^5 \tan(x) dx - \int \sec(x)^3 \tan(x).$$
Now each of these have some number of powers of secant and one power of tangent, which makes them approachable with $u=\sec(x)$.
Answer: differentiate this with respect to $x$
$$\frac{\sec ^5(x)}{5}-\frac{\sec ^3(x)}{3}$$
Answer: Hint: $\tan'x=1+\tan^2x=\sec^2x$. The integrand then becomes $t^3\sqrt{t^2+1}$, which begs for a substitution of the form $u=t^2+1$, since $t^3=t\cdot t^2=\dfrac{\big(t^2+1\big)'}2\cdot\Big[\big(t^2+1\big)-1\Big]$.
Answer: First notice that $\sec(x)\tan(x)$ is the derivative of $\sec(x)$. We will peel one off and hold it in reserve for $u$-substitution later.
$$\int (\sec(x)\tan(x))^2 (\sec(x)\tan(x))dx$$
Now we have the wonderful Pythagorean identities: $$\tan^2(x)+1 =\sec^2(x)$$ so replacing $\tan^2(x)$ with $\sec^2(x)-1$ we arrive at:
$$\int \sec^2(x) (\sec^2(x) - 1) (\sec(x)\tan(x)) dx.$$ Now let $u=\sec(x)$, and we have:
$$\int u^2 (u^2-1) du$$ and you can take it from here.
Answer: \begin{align}
\int{\tan^3x\sec^3x}
& =\int{(\tan{x}sec{x})^2(\tan{x}\sec{x})dx}\\
& =\int{(\tan^2{x}sec^2{x})d\sec{x}}\\
& =\int{(\sin^2{x}\sec^4{x})d\sec{x}}\\
& =\int{(1-\cos^2{x})(\sec^4{x})d\sec{x}}\\
& =\int{(\sec^4{x}-\sec^2{x})d\sec{x}}\\
& =\frac{\sec^5x}{5}-\frac{\sec^3x}3+C
\end{align}

Integration of $(\tan x\sec x)^3$


What kind of salvage do Rogue Drones drop (if any)?

Question: Just wondering if it's worth to salvage missions like Rogue Drone Harassment and similar ones.
Answer: Rogue Drones have all Salvage Parts in their loot table, except Damaged Artificial Neural Network. Therefore it is worth salvaging.


ubuntu - when try to install solana - get error

Question: I am trying to install Solana:

sh -c "$(curl -sSfL https://release.solana.com/v1.7.12/install)"

I am getting:
downloading v1.7.12 installer

/tmp/tmp.uKtHJnlk2o/solana-install-init: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory

please help me
Answer: maybe apt-get update followed by apt-get install openssl can help.
root@53794cb0b15a:/# apt info libssl1.1
Package: libssl1.1
Version: 1.1.1f-1ubuntu2.8
Priority: important
Section: libs
Source: openssl
Origin: Ubuntu
Maintainer: Ubuntu Developers <email@example.com>
Homepage: https://www.openssl.org/
[...]
Packages
**Description: Secure Sockets Layer toolkit - shared libraries**

Comment: thanks for replying
i have an old version, because when typing openssl version, i got OpenSSL 1.0.2g  1 Mar 2016
ubuntu@ubuntu-vbox:/usr/local/openssl-1.1.0l$ which openssl
/usr/bin/openssl
Comment: Your distribution may be too old, but as the answerer mentioned you can try to install version 1.1 using `apt-get install libssl1.1`


C# generic function applicable on Linq objects in a json server application

Question: I need to execute CRUD operations on LINQ objects from a customized JSON command in a web server application written in C#.
For instance, I receive a select command and I produce a JSON dataset; next my web rich client produces a customized json command for a transaction that I need to execute on server database.
I cannot change json client format so I can't use WebApi.
I receive a structured json where I receive some data and operation required (for instance, Insert).
I would like to write a generic method that receive the operation and
data and execute right Linq Object save command.
public genericInsert(<T> linqObj, string opJsonRequired) {
    linqObj.LoadFromJson(opJsonRequired);
    linqObj.save(dbContext);
}

I would like to write the SpecificInsert (update, delete) method in the  partial class generated by visual studio.
Can you point in the correct and productive way to do this in C# (I'm using MS VS2010). I tryed with delegate without success.
Comment: Could you provide a JSON Example?
Comment: I receive in a POST request a json structure with 4 elements, one of them indicate CRUD operation, one is a conventional TableName and 2 are table record before and after modify. I haven't problem in deserialize and serialize with Json.net tools. My problem is centralize management of input json and call right Linq object containing record data...
Answer: You are probably looking for an extension method with a deserializer
public genericInsert<T>(T linqObj, string opJsonRequired) {
     linqObj.LoadFromJson(opJsonRequired);
     linqObj.save(dbContext);
}

public static class LinqObjectExtensions
{
   public static T LoadFromJson(this T source, string opJsonRequired) where T : 'SomeType' {
       JsonSerializer serializer = new JsonSerializer();
       var operation = ('SomeType')serializer.Deserialize(opJsonRequired);
       ...do operation to T
       return T;
}


threeJS jsonLoader - "Cannot read property 'length' of undefined"

Question: I'm creating a scene, which can be saved and then loaded.
To save the scene,I serialize all the objects (and their data). For the meshes this works simply like this:
var json = {};
json.objectsInScene = [];
for (var i = 0; i < collectionOfObjects.length; i++)
{

    json.objectsInScene.push(collectionOfObjects[i].toJSON();
}

Then, I try to load them back in which works like this:
var jsonObject = JSON.parse(json);

for (var i = 0; i < jsonObject.objectsInScene.length;i++){

    var loader = new THREE.JSONLoader();
    var geometry = loader.parse(jsonObject.objectsInScene[i]);

    var mesh = new THREE.Mesh(geometry.geometry, new THREE.MeshBasicMaterial());

    this.scene.add(mesh);
}

When I execute this code. I get the following error:

Cannot read property 'length' of undefined
Line 14990 of three.js.

Which is this line:
zLength = vertices.length;

And when checking it in the dev tools, I have to agree: vertices.length is undefined. In fact, it gets assigned a couple of lines above that:
var vertices = json.vertices;

But the json-object only contains the following properties:
geometries: Array[15]
materials: Array[15]
metadata: Object
object: Object

What am I doing wrong? Where does it go wrong, or what can I do to work around this issue?
R73
Comment: are any of your JSON call asynchronous?
Comment: @gaitat no, they are called one after each other, without any async options.
Comment: after your `loader.parse()` call, is `geometry.geometry.vertices` defined?
Comment: @gaitat It gets stuck on that line: the error I get are inside the `loader.parse()` call. (which leads to line 14990 of three.js)
Comment: so then there is a problem with your `jsonObject.objectsInScene[i]` object(s). Maybe you need to create a fiddle. We cannot see the objects otherwise.
Comment: I will look to make a jsFiddle, but the objects in the array are created by just doing  `collectionOfObjects[i].toJSON()` for each object in my scene.
Comment: yes I have seen that but there is no way to debug the posted code.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/101410/discussion-between-jordumus-and-gaitat).
Comment: I wish you had posted the answer to this. I have the exact same problem but am using R105 and The now LegacyJSONLoader!
Answer: maybe you should use THREE.ObjectLoader
for (var i = 0; i < jsonObject.objectsInScene.length;i++){

    var loader = new THREE.ObjectLoader();
    var obj= loader.parse(jsonObject.objectsInScene[i]);

    this.scene.add(obj);
}


Borel functional calculus and point evaluation

Question: Suppose $x\geq 0$ is positive operator. Let $\sigma(x)$ denote the spectrum. If $0\in\sigma(x)$ denote $1_{\{0\}}$ to be the characteristic function. Is it true that $1_{\{0\}}(x)=0$? using the Borel functional calculus.
Denote $1_{\{0\}}(x)=a$. It is enough to show that $a=0$. I can see that for any polynomial $P$ holds $P(x)a=aP(x)=P(0)$. So $P(0)=0$ implies $P(x)a=aP(x)=0$. But I can't proceed further.
Comment: Denote $1_{\{0\}}(x)=a.$ It is enough to show that $a=0.$ I can see that for any polynomial $P$ $P(x)a=aP(x)=P(0).$ So $P(0)=0$ implies $aP(x)=P(x)a=0.$ But I cant proceed further.
Comment: what have you tried so far?
Comment: Hi @SamyaKumarRay, please add what you have tried so far to the question for others to assist you better.
Answer: For any normal operator $x$, it is true that for any $z\in\sigma(x)$, $1 _{\{z\}}(x)=0$ if and only if $z$ is not an eigenvalue of $x$. The question therefore is, can we find a positive, non-invertible operator that is $1-1$? Yes, we can.
Consider for example $x:\ell^2\to\ell^2$ that maps $(a_n)\mapsto(a_n/n)$. It is obviously a bounded, linear and $1-1$ operator and it is also positive: we have $$\langle x(a_n)_n, (a_n)_n\rangle_{\ell^2}=\sum_{n}\frac{|a_n|^2}{n}\geq0$$ but this operator is not invertible, since it is not bounded below: the canonical orthonormal basis $(e_n)$ of $\ell^2$ is a sequence of unit vectors such that $x(e_n)\to0$.
Since we can find such an operator, that means that what you are asking is not necessarily true.


How Do I Pass a Function Through A React Component For Data Sharing Between Parent and Child?

Question: I have followed this tutorial (https://www.freecodecamp.org/news/pass-data-between-components-in-react/) to the best of my ability but I am still having trouble
I am getting the following error:
Uncaught TypeError: childToParent is not a function"

Here is the parent function:
function App() {
const childToParent =(value) => {console.log(value)}
...
return (
...
  <SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

and the child function:
export default function SelectHours(selectedHours, childToParent) {
....
return (
<Select
  labelId="select-demo"
  id='select-demo'
  defaultValue=""
  //onChange={event => handleChange(event.target.value, true)}
  value={workHours[0] ? workHours[0] : ""}
>
  {
    workHours.map((value, index) => {
      return (
        <MenuItem
          value={value ? value : ""}
          key={index}
          onClick={() => childToParent(value)}
        >
          {value}
        </MenuItem>
      )
    })
  }
</Select>
)
....
}

Answer: You need to add your curly braces so react can tell its a prop.
export default function SelectHours({selectedHours, childToParent}) {
....
return (
<Select
  labelId="select-demo"
  id='select-demo'
  defaultValue=""
  //onChange={event => handleChange(event.target.value, true)}
  value={workHours[0] ? workHours[0] : ""}
>
  {
    workHours.map((value, index) => {
      return (
        <MenuItem
          value={value ? value : ""}
          key={index}
          onClick={() => childToParent(value)}
        >
          {value}
        </MenuItem>
      )
    })
  }
</Select>
)
....
}

Comment: Did you assign a data to the value variable via state or just as a variable, I mean before you returned the jsx ?
Comment: We posted 2 seconds apart. :)
Comment: I had the wrong name in the components argument
Comment: Awesome glad I could help, you can give this answer the green tick to help others, cheers!
Comment: shoot! it happens, happy coding!
Answer: must destruct props like this.
export default function SelectHours({selectedHours, childToParent})

or use props like this
    export default function SelectHours(props)
      ...
    onClick={() => props.childToParent(value)}

read about object destructuring in this article
https://dmitripavlutin.com/javascript-object-destructuring/
Comment: God bless you sir.
Answer: You need to have a handler for ChildToParent inside

function App() {
...
const childToParent =(value) => {console.log(value)}
return (
...
  <SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

the App component
Comment: I do have that. Sorry, I forgot to add that part. (doing it now)


Central limit theorem

Question: At first glance you would think this question was easy. It's not. Maybe the answer in the back of the book is wrong. But nobody, not even my maths teacher can explain it to me.
Here is the question: an unbiased 6 sided dice is thrown 70 times. Find the probability that the mean score is less than 3.3
Answer: 0.155
My working.
Mean of one dice is 3.5 variance is 35/12
Therefore the mean of 70 throws is distributed normally ~N(3.5,(35/12)/70)
P(Xmean<3.3)=P(z<-0.2/0.204)
1-p(z<0.98039)
1-0.83655
0.16345
NOT THE ANSWER???
I know this isn't the most intellectually stimulating question out there but to anyone reading this it would help me out a lot if I could have this question explained to me. Thanks
Update: Maybe I am being silly and missing something very obvious. Here is the original question.
Comment: @DougM as in the question, the book's answer is 0.155
Comment: 0.155 is the answer
Answer: If the result of one throw has mean $\mu$ and variance $\sigma^2$,  the sum of $70$ independent throws has mean $70 \mu$ and variance $70 \sigma^2$, and the average $X$ of these $70$ throws has mean $\mu$ and variance $\sigma^2/70$.  It is wrong to say $X$ is distributed normally, but because of the CLT you can say it is distributed approximately normally.  Thus
$$ P(X < 3.3) \approx P\left(Z < \frac{3.3 - \mu}{\sigma/\sqrt{70}} \approx -0.9798\right) \approx .16359 $$
However, we might improve the result with the "continuity correction".  An average $< 3.3$ means a sum $< 70 \times 3.3 = 231$, and this sum is an integer; since the $<$ means we don't want to include cases where the sum is exactly $231$, we might replace $231$ by $230.5$, and thus replace $3.3$ by $230.5/70$.  This makes the
$z$ score
$$ \frac{230.5/70 - \mu}{\sigma/\sqrt{70}} \approx -1.01479$$
and now indeed $$P(X < 3.3) \approx 0.155103 $$
By the way, the exact answer (not using any approximation) turns out to be
$$ \frac{229642652203521128605439312834749816684648611425676955}{1477602207273840622329353829895227690835664661525823488} \approx .1554157479$$
Comment: Right it's an approximation yes. But the answer is apparently 0.155 and I get 0.16345 so I must be doing Something wrong
Comment: Holy crap it was just a continuity correction. What a difference it makes thank you very much
Answer: When we use the normal distribution we are assuming that distributions are continuous.
If the average on 70 rolls is 3.3 then the sum is 231
P(average < 3.3) = P(sum < 231)
We need to make an adjustment for the possibility that the sum exactly equals 231
$P(x \le 231) - P(x = 231 \pm 0.5)\\
N( \frac {(230.5-245)}{\sqrt {70\cdot \frac {35}{12}}}) \approx N(-1.0148)  \approx 0.155$

Central limit theorem


Where can I find the command line?

Question: A basic question: Where do I find the command line?
There is a lot of information about commands and using the command line, but I'm an absolutely new Ubuntu user: I can't find find the command line.
Comment: possible duplicate of [What is the terminal?](http://askubuntu.com/questions/38162/what-is-the-terminal)
Answer: You can open a terminal in Unity (the default desktop enviroment when you install Ubuntu 11.10) by pressing Ctrl + Alt + T or by:
Open the dash by pressing the top button in the launcher. You will see a screen similar to this:

In the search box, type in "terminal". Click the icon for terminal, or, if it is the first result, which I am assuming it is, press the enter key on your keyboard. Terminal will open. You can close it like any other program by pressing the red X in the upper right hand corner of the window. Hope that helps!
Comment: @bri Your'e Welcome! Could you please either my or enzotib's answer as answer? You can do this by clicking the checkmark underneath the up and down vote buttons. The checkmark will turn green when clicked.
Answer: The key combination Ctrl-Alt-t should start a terminal emulator, that is substantially what you call command line.
Alternatively, from the Dash search for terminal and launch it.
Comment: [This](http://vic.gedris.org/Manual-ShellIntro/1.2/ShellIntro.pdf) could be really helpful for learning Linux Commands from very basics.
Comment: `Ctrl-Alt-t` only works in Unity, but I imagine @bri *is* using that.
Answer: One more alternative to launch the terminal in Ubuntu is to press  CTRL + ALT  and then type gnome-terminal in the pop up text box.

Where can I find the command line?


Display video stream chunks on page (node.js)

Question: I'm still new in Node.js and trying to figure out things so excuse me if I sound incoherent.
So I've read some beginner notes on streams and I'm testing it out at the moment.
I got these Seinfeld episodes (.mkv files) in my project files (public/images/videos/Seinfeld.S09E07.720p.WebRip.ReEnc-DeeJayAhmed.mkv) that I would like to show on a page. Now, the easy choice would be to just put it in the 'src' of the video tag in my ejs file.
However, I would like to stream the video parts so that it doesn't have to wait for the whole file to be ready to display the episode. I thought I could use .createReadStream for this. However, I don't know how I can transfer those little chunks of video data that are ready into my webpage to display them in my video player.
index.js server-side
var express = require('express');
var router = express.Router();
var fs = require('fs');

    /* GET home page. */
router.get('/', function(req, res, next) {
    var myReadStream = fs.createReadStream(__dirname + '/../images/videos/Seinfeld.S09E07.720p.WebRip.ReEnc-DeeJayAhmed.mkv');

    myReadStream.on('data', function (chunk) {
        // no idea what to do from here
    })
    res.render('index', {
        title: 'Express'
        });
});

module.exports = router;

EJS file
<!DOCTYPE html>

    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />

<%= title %>

    <video src="" type="video/mkv" autoplay controls></video>

Welcome to <%= title %>

Comment: You probably need to pipe the stream to the user: e.g. `myReadStream.pipe(res)`
Comment: And then how do I access the chunks?
Comment: through using what the answer below suggests...
Comment: Ok, I'll study it. Thanks for the response!
Answer: You can use fetch(), Response.getReader() which returns a ReadableStream and MediaSource at client to read the stream of response from server and append one or more ArrayBuffers representing chunks of one or more media resources which can be rendered at <video> element, see HTML5 audio streaming: precisely measure latency?.
Comment: Ok, for now I don't understand what all that means, but I have a starting point for research with the things you mentioned. Thanks for the response!
Comment: @TijlDeclerck See [Media Source Extensions™](https://w3c.github.io/media-source/)


Leveling wood floor for laminate wood floor

Question: I am laying down some laminate wood floor this week in my house over some older wood plank flooring. I was just going to put roofing paper down and then some foam style underlayment Home Depot recommended. The issue is the floor, being old planks, is not very level spanning the room. The corners are pretty low, maybe 1/4" dip. Should I lay down some liquid floor leveler on this floor or just build up the underlayment to make it more level?
Thanks.
Comment: What direction will the new floor run?  Parallel or perpendicular to the subfloor boards?
Comment: @JPhi1618 it would run the opposite direction, or perpendicular, to the current floor.
Comment: Is that a 1/4" dip over the last 2 feet, 4 feet, etc?  Unless it's a pretty severe drop at the end, shouldn't be an issue, but a more seasoned floor installer might have a better idea.
Answer: Those planks look really cupped and separated. Floor leveler probably isn't a good choice; too many ways for it to go through the floor. It needs a overlay with plywood to make for a solid smooth base. Just ensure that the plywood is laminated and properly fastened to the subfloor. The thinner the plywood the flatter the subfloor needs to be, that means sanding and filling the cups in the wood before laminating to it. From there you can level it off easily.


Resume started activity from Service

Question: As I read in several stackoverflow answeres. To start activity from the service you have to use FLAG_ACTIVITY_NEW_TASK, but it will create new instance of activity in separate task. I want to reuse already started activity. Im trying to do it from IntentService that listen for c2dm notifications.
Answer: In the manifest for the Activity, you could set android:launchMode="singleInstance".
Here's what the docs say about singleInstance:

Only allow one instance of this activity to ever be running. This
  activity gets a unique task with only itself running in it; if it is
  ever launched again with the same Intent, then that task will be
  brought forward and its Activity.onNewIntent() method called. If this
  activity tries to start a new activity, that new activity will be
  launched in a separate task. See the Tasks and Back Stack document for
  more details about tasks.

And here is where I got my info.
Comment: Can I do it with combination of activity flags? I don't want to change launching mode.
Comment: I believe you can, but I have not personally tested it. To find out, just add the `FLAG_ACTIVITY_NEW_TASK` flag, then add `FLAG_ACTIVITY_REORDER_TO_FRONT`. I don't know for sure if it will work or not, but it will take you only about 5 or 10 minutes to set up and test.
Answer: You must use this flag with your Intent:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

IF you don't want a new instance of your Activity, set launchMode for your Activity in the AndroidManifest file:
android:launchMode="singleTask"

Resume started activity from Service


Setup CUDA and Pytorch for Faster-RCNN

Question: I setup cuda and pytorch with conda install pytorch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 cudatoolkit=11.3 -c pytorch -c conda-forge. But when I run a git code it tells me that: RuntimeError: Not compiled with GPU support.

import torch
print(torch.version.cuda)
11.3
torch.cuda.is_available()
True

output nvidia-smi
conda list --show-channel-urls
My $CUDA_HOME is not set but I don't know what I should set it to. Can someone help me what I can do? I've never worked with cuda before and therefore don't find a solution for my problem..
Thank you!!
Answer: Your screenshot shows that you have 12.2 as your CUDA version, but you are installing PyTorch with an 11.3 CUDA version (by using the cudatoolkit=11.3 flag). Check this: https://discuss.pytorch.org/t/pytorch-for-cuda-12/169447

Setup CUDA and Pytorch for Faster-RCNN


Highlight area in highcharts

Question: I need select area near column.
How to make the region and column stand out when you click, as when you hover over it.
This is my example:
https://jsfiddle.net/alexserden/wq6j0tnp/9/
<code>$(function () {
    let chart = Highcharts.chart('bar', {
        tooltip: {
            shared: true,
            hideDelay:100,
            useHTML: true,
            outside: true,
            style: {
                fontSize: "13px",
                color: '#505050'
            }
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            column: {
                dataLabels: {
                    enabled: false,
                    style: {
                        fontSize: '13px',
                        fontWeight: 'bold',
                        textOutline: undefined,
                        color: '#505050'
                    }
                }
            },
            ...
        },
        ...
    }
});
</code>
Answer: You'll need to add an event handler for the click:
<code>                series: {
                    cursor: 'pointer',

                    marker: {
                        enabled: false
                    },
                    point: {
                      events: {
                          click: function () {
                              // Handle selection
                          }
                      },
                    }
                }
</code>
Inside this event you'll need to handle the area selection, there is a similar post here. The selected area is a category. (API reference)
API documentation for click event: https://api.highcharts.com/highcharts/plotOptions.area.point.events.click
Answer: You can render the plotBands as a crosshair and use the select for highlighting the point inside the click callback.
Demo: https://jsfiddle.net/BlackLabel/k4d9nrwf/
<code>point: {
  events: {
    click() {
      let chart = this.series.chart;

      chart.series.forEach(s => {
        s.points.forEach(p => {
          if(p.category === this.category) {
            p.select()
          }
        })
      })
      chart.xAxis[0].update({
        plotBands: [{
            from: this.x -0.5,
          to: this.x + 0.5,
        }]
      })
    }
  }
},
</code>
API: https://api.highcharts.com/highcharts/xAxis.plotBands
API to style the selected point: https://api.highcharts.com/highcharts/series.line.states.select

Highlight area in highcharts


Execution failed for task ':ofbiz --load-data' while running OfBiz

Question: FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':ofbiz --load-data'.

Process 'command 'C:\Program Files\Java\jdk-17.0.2\bin\java.exe'' finished with non-zero exit value 1

Try:

Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':ofbiz --load-data'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:147)
at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282)

when i am trying build using gradle facing issue, any help appreciated.
`
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Your issue is not clear. In windows devices try gradlew cleanAll loadAll ofbiz command to load data and run ofbiz. If your issue is due to java version, try Java 1.8 version.
Visit below link of OFBiz development guide for more help
https://cwiki.apache.org/confluence/display/OFBIZ/OFBiz+Tutorial+-+A+Beginners+Development+Guide


Changing a string in a list of strings

Question: So basically I have a huge list of strings, for example
list = ["hello", "my", "name", "is"]

etc...
and I want to ask the user a question, if the user responses with a word that is in my list I want to replace it with "yes". How would I do this, everything that I have tried has failed. Thanks!
Answer: List comprehension:
# user input in user_input
new_list = [item if item != user_input else "yes" for item in old_list]

This replaces anything that's equal to the user_input with "yes".
Tip: don't shadow the built-in list.
Output:
>>> old_list = ["hello", "my", "name", "is"]
>>> user_input = "hello"
>>> new_list = [item if item != user_input else "yes" for item in old_list]
>>> new_list
['yes', 'my', 'name', 'is']

Answer: Imagine this is your list
 INPUT_MATCH = 'yes'
 L = ["hello", "my", "name", "is"]

You are asking user to input
user_input = raw_input("Enter your input")

if user_input in set(L): #reason to convert list to set for less expensive search
    L[L.index(user_input)] = INPUT_MATCH

Changing a string in a list of strings


Can't install wine in Ubuntu

Question: sudo apt install --install-recommends winehq-stable
[sudo] password for krishanu:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 winehq-stable : Depends: wine-stable (= 5.0.3~groovy)
E: Unable to correct problems, you have held broken packages.

Comment: Does this answer your question? [can't install wine on ubuntu (actually lubuntu) 18.04](https://askubuntu.com/questions/1205550/cant-install-wine-on-ubuntu-actually-lubuntu-18-04) and [Wine: How to fix held broken packages?](https://askubuntu.com/q/1126578/)
Comment: Are you installing from the Wine upstream repositories?
Comment: from here https://wiki.winehq.org/Download
Comment: @KrishanuDev was Wine installed previously?  If so, do `sudo apt purge 'winehq-*' 'wine-*'` first, then attempt to install from scratch.  If that still doesn't work, then you need to contact WIneHQ upstream for support.
Comment: @Thomas Ward no bro it's the first time am installing wine
Answer: This wine installation procedure was tested for gaming purposes and is running on Xubuntu 20.04 LTS machines.
a) Go to: https://wiki.winehq.org/Ubuntu for aditional information
b) Open the app Terminal and execute the following commands:
su – administratoraccount and password
c) Activate 32 bits architecture:
sudo dpkg --add-architecture i386
d) Download repository key:
wget -nc https://dl.winehq.org/wine-builds/winehq.key and then sudo apt-key add winehq.key
e) Add the repository for ubuntu 20.04:
sudo add-apt-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ focal main'
f) Update packages:
sudo apt update
g) Install the wine package suitable for the needs. Please, see Wine FAQ under the section 2.2 Which version of Wine should I use? on https://wiki.winehq.org/FAQ#Which_version_of_Wine_should_I_use.3F In this case the Development branch is used.
sudo apt install --install-recommends winehq-devel
h) Install winetricks:
sudo apt install winetricks
i) Install dxvk package:
sudo apt install dxvk
Note:
Checking wine version installed: wine --version

Can't install wine in Ubuntu


java +simple Webserver +htmlform encoding

Question: As an assignment, I have ti implement a simple webserver in Java.
My Problem is:
There is a html-form that looks like this:
<code><form method="POST" action="dummy" accept-charset="UTF-8">
<input name="in1" type="text"/>
<input type="submit" value="GO"/>
</form>
</code>
i enter >dc=mydomain.com< (without ><), press GO.
the webserver reads the post from the socket, but the parameter suddenly is
"dc%3Dmydomain.com"
ps. i am running java 1.7.0-b147, 64bit
how can i avoid the html-form escaping characters like "=" and "," to %3D and %2C? Or make java reconstruct the original string from the textbox?
Answer: In the web server code you will need to use java.net.URLDecoder.decode on it. The default enctype for a form is urlencoded.
HTH
Comment: neither application/x-www-form-urlencoded, nor x-www-form-urlencoded are supported encodings (UnsupportedEncodingException), i cannot find a list of supported encodings^^
Comment: string a = URLDecoder.decode(a, "UTF-8"), not just URLDecoder.decode(a, "UTF-8")... it's late^^, thank you


Changing AVPlayerItem's videoComposition property (AVMutableVideoComposition) during playback

Question: I am trying to change a video composition's layout (i.e. its component frames' transforms) during playback. It seems that sometimes this works, and the video composition seamlessly changes to the new set of transforms, but other times it just freezes up and stays with the current transforms. There is no status code change on the AVPlayer instance, and there are no errors on either the player or the player item.
Has anybody experienced this before? Any suggestions on why this is happening, or how to get around it, would be appreciated.
Some code is shown below. The important bit is 'playerItem.videoComposition = videoComposition', which here is triggered on tapping the video (for testing purposes).
Another solution to this problem would be to display the videos on separate layers, but it is imperative that the videos are in sync so a composition seems the only way to achieve this.
<code>@implementation VideoView
{
    CGSize _videoSize;
    CMTimeRange _videoFullRange;

    AVMutableCompositionTrack * _compositionTrackVideoA;
    AVMutableCompositionTrack * _compositionTrackVideoB;
}

+ (Class)layerClass
{
    return [AVPlayerLayer class];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if ( self )
    {
        NSString * videoAPath = [[NSBundle mainBundle] pathForResource:@"cam09v2" ofType:@"mp4"];
        NSString * videoBPath = [[NSBundle mainBundle] pathForResource:@"cam10v2_b" ofType:@"mp4"];
        AVURLAsset * videoAAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoAPath] options:nil];
        AVURLAsset * videoBAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoBPath] options:nil];

        AVAssetTrack * videoATrack = [[videoAAsset tracksWithMediaType:AVMediaTypeVideo] lastObject];
        AVAssetTrack * videoBTrack = [[videoBAsset tracksWithMediaType:AVMediaTypeVideo] lastObject];
        AVAssetTrack * audioTrack = [[videoAAsset tracksWithMediaType:AVMediaTypeAudio] lastObject];

        _videoSize = [videoATrack naturalSize];
        CMTime videoDuration = videoAAsset.duration;
        _videoFullRange = CMTimeRangeMake(kCMTimeZero, videoDuration);

        AVMutableComposition *composition = [AVMutableComposition composition];
        AVMutableCompositionTrack * compositionTrackVideoA = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        AVMutableCompositionTrack * compositionTrackVideoB = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        AVMutableCompositionTrack * compositionTrackAudio = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

        compositionTrackVideoA.preferredTransform = videoATrack.preferredTransform;

        NSError * error = nil;
        if ( ! [compositionTrackVideoA insertTimeRange:_videoFullRange ofTrack:videoATrack atTime:kCMTimeZero error:&error] )
            NSLog(@"%@", error);

        if ( ! [compositionTrackVideoB insertTimeRange:_videoFullRange ofTrack:videoBTrack atTime:kCMTimeZero error:&error] )
            NSLog(@"%@", error);

        if ( ! [compositionTrackAudio insertTimeRange:_videoFullRange ofTrack:audioTrack atTime:kCMTimeZero error:&error] )
            NSLog(@"%@", error);

        _compositionTrackVideoA = [compositionTrackVideoA copy];
        _compositionTrackVideoB = [compositionTrackVideoB copy];

        AVPlayerItem * playerItem = [AVPlayerItem playerItemWithAsset:composition];

        AVPlayer * player = [AVPlayer playerWithPlayerItem:playerItem];

        [(AVPlayerLayer *)self.layer setPlayer:player];

        [player play];

        [player addObserver:self forKeyPath:@"status" options:0 context:0];

        [self updateCompositionForPlayerItem:playerItem];

        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
        [self addGestureRecognizer:tapGesture];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ( [keyPath isEqualToString:@"status"] )
        NSLog(@"STATUS %d", ((AVPlayer *)object).status );
}

- (void)updateCompositionForPlayerItem:(AVPlayerItem *)playerItem
{

    AVMutableVideoComposition * videoComposition = [AVMutableVideoComposition videoComposition];

    AVMutableVideoCompositionInstruction *videoInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    videoInstruction.enablePostProcessing = NO;
    videoInstruction.timeRange = _videoFullRange;

    AVMutableVideoCompositionLayerInstruction * layerInstructionA = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:_compositionTrackVideoA];
    CGAffineTransform transformA = CGAffineTransformMakeScale(0.5, 0.5);
    [layerInstructionA setTransform:transformA atTime:kCMTimeZero];
    AVMutableVideoCompositionLayerInstruction * layerInstructionB = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:_compositionTrackVideoB];
    CGAffineTransform transformB = CGAffineTransformMakeScale(0.5, 0.5);
    static int i = 0;
    transformB = CGAffineTransformTranslate(transformB, (i++ % 2 == 0) ? _videoSize.width : 0, _videoSize.height);
    [layerInstructionB setTransform:transformB atTime:kCMTimeZero];

    videoInstruction.layerInstructions = [NSArray arrayWithObjects:layerInstructionA, layerInstructionB, nil];

    videoComposition.instructions = [NSArray arrayWithObject:videoInstruction];

    videoComposition.frameDuration = CMTimeMake(1, 30); // 30 fps
    videoComposition.renderSize = _videoSize;

    playerItem.videoComposition = videoComposition;

}

- (void)didTap:(UITapGestureRecognizer *)tapGesture
{
    [self updateCompositionForPlayerItem:((AVPlayerLayer *)self.layer).player.currentItem];
}

@end
</code>
Comment: Did you solved this dang issue?
Answer: You can save the time where you want to change it and replace the player item with a new video composition and start the player again with the new player item from the time where you stoped playing.
Comment: It's an obvious workaround but it has a visual "hiccup". It just won't go properly.


(Hall's Theorem) Existence of two subfamilies of sets containing the same elements

Question: I came across the following claim in a textbook on combinatorics [1].

Claim (Lindström, Tverberg): Let $A_1, . . . , A_m \subseteq [n]$ be non-empty with $m > n$. There are non-empty, disjoint $I, J \subseteq [m]$, such
that $$\bigcup_{i \in I} A_i = \bigcup_{j \in J} A_j.$$

The book provides a very nice proof of this claim, using characteristic vectors of the sets $A_1, . . . , A_m$ and some linear algebra basics.
It also includes a remark that says this claim can be proved using Hall's theorem. This second approach is not obvious to me but I would like to understand how you can use Hall's theorem here (it's really bugging me). If anyone could provide a solution, a hint, or a reference to a proof, I would really appreciate it.
Reference:
[1] B. Sudakov, "Algebraic Methods in Combinatorics", 2023

Original Proof: Let $v_1, . . . , v_m$ be the characteristic vectors of $A_1, . . . , A_m$. Since $m>n$, they are linearly dependent over $\mathbb{R}$. So, there is a nonzero $\alpha \in \mathbb{R}^m$ with $$\sum_{i=1}^m \alpha_i v_i = 0.$$ Let $$I = \{i : \alpha_i > 0\},$$
$$J=\{j : \alpha_j < 0\}.$$ The nonzero coordinates of $\sum\limits_{i \in I} \alpha_i v_i$ correspond to the
elements of $\bigcup\limits_{i \in I} A_i$, which are the same as the nonzero coordinates of $\sum\limits_{j \in J} \alpha_j v_j$ corresponding to $\bigcup\limits_{j \in J} A_j$, completing the proof.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/151891/discussion-on-question-by-matth-halls-theorem-existence-of-two-subfamilies-of); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: As a partial response, here is a proof of the claim based on a possible proof of Hall's theorem. Maybe it will inspire further progress.
The graph we consider is the usual graph for the system-of-representatives view of the theorem: let $X = \{x_1, x_2, \dots, x_m\}$, $Y = \{y_1, y_2, \dots, y_n\}$, and put an edge $x_i y_j$ whenever $j \in A_i$. It will be important that because the $A_i$ are all nonempty, $X$ has no isolated vertices.
Pick a maximum matching $M$ in this graph. Of course, since $m>n$, this matching does not cover all of $X$. We are going to start by letting $U_0$ be the set of all vertices in $X$ not covered by $M$, and then repeat the following procedure:

After $U_i$ has been defined, let $V_i = N(U_i) - N(U_0 \cup \dots \cup U_{i-1})$: the set of "new" vertices in $Y$, which are adjacent to $U_i$ that we haven't found previously.
Let $U_{i+1}$ be the set of all vertices in $X$ matched to $V_i$ by $M$.

We stop when no new vertices get added to $U_0, U_1, U_2, \dots$ or $V_0, V_1, V_2, \dots$.
How is this related to Hall's theorem? Well, every vertex in $V_i$ has a path to it from $U_0$, a path zigzagging between the sets $$U_0 - V_0 - U_1 - V_1 \dots - U_i - V_i$$ in which every $V-U$ type edge is an edge of the matching. So if we ever find an unmatched vertex in $V_i$, this zigzagging path is an augmenting path that could be used to improve $M$. Since $M$ is assumed to be a maximum matching, no such augmenting path exists. Therefore every vertex in $V_i$ is matched by $M$; it follows that $|V_i| = |U_{i+1}|$. The procedure can only stop by having $V_i = \varnothing$ at some stage, and it must stop since our graph is finite.
At this point, we normally say that $S = U_0 \cup U_1 \cup \dots \cup U_{i+1}$ is a subset of $X$ with $N(S) = V_1 \cup V_2 \cup \dots \cup V_i$, and $|S| = |U_0| + |N(S)|$, so $S$ is a set violating Hall's condition. This proves the hard direction of Hall's theorem.
What we'll say here instead is that if we take $S_0 = U_0 \cup U_2 \cup U_4 \cup \dots$ and $S_1 = U_1 \cup U_3 \cup U_5 \cup \dots$ (even-numbered sets in $S_0$, and odd-numbered sets in $S_1$), then $N(S_0) = N(S_1) = N(S)$. That's because each vertex in $V_i$ has a neighbor in $U_i$ (that's how we got it) and a neighbor in $U_{i+1}$ (which it was matched to by $M$). The sets $S_0$ and $S_1$ are exactly what we're looking for in this question. (To relate them back to the theorem we want, we let $I = \{i \in [m] : x_i \in S_0\}$ and $J = \{j \in [m] : x_j \in S_1\}$.)
Unfortunately, I don't see how to use just the statement of Hall's theorem (and not the proof) to make this deduction. It's not clear a priori why a set $S \subseteq X$ with $|N(S)|<|S|$ must split into disjoint sets $S_0, S_1$ with $N(S_0) = N(S_1) = N(S)$, even though we see it happening here.
We still learn one useful thing from this argument: the existence of $S_0$ and $S_1$ follows not just if $m>n$, but whenever the graph has no perfect matching. And this useful fact is a consequence of Hall's theorem (as well as the theorem in the question): if we find a set $S$ with $|N(S)|<|S|$, we can apply the theorem in the question to just the sets $A_i$ with $x_i \in S$, and just the elements $j \in [n]$ with $y_j \in N(S)$.
Comment: Here's a way you could use Hall's theorem in your proof. Make it a proof by induction on $n$. You can assume that $|N(A)|\ge|A|$ whenever $A\subseteq[m]$ and $|A|\le n$, as otherwise you can use the inductive hypothesis with $A$ and $N(A)$ replacing $X$ and $Y$. Then by Hall's theorem your matching $M$ covers $Y$, so you don't need the augmenting path.


Microsoft Visual Studio Environment

Question: When I installed Microsoft Visual Studio I told it to optimize for C#.  That is, when asked, I indicated that I would be programming in C# most of the time.  Is there a way to change the environment, so that it is optimized for working with C++ without uninstalling/reinstalling Visual Studio?  Could I do another install of Visual Studio on top of the current install without uninstalling it first?  Thanks.
Comment: Note that VS is referring mainly to the keybindings and possibly initial window layout/default template options with this choice. It's not a performance thing for the application itself.
Answer: have a look at this post
How can you change the Visual Studio IDE profile?
Comment: If you chose Reset all settings you should be re-prompted
Answer: You can use the command line option /resetsettings to reset visual studio settings
devenv.exe /ResetSettings
This will enable Visual Studio to bring up the environment dialog again.

Microsoft Visual Studio Environment


How to resolve this error: "Error: node_modules/@angular/core/index.d.ts:X:X - error NG1010: Value"

Question: Whenever I run my angular project file with the help of ng serve -o in command prompt, it gives an error.
Here's the error I observed:

Error: node_modules/@angular/core/index.d.ts:5501:22 - error NG1010:
Value
** Angular Live Development Server is listening on localhost:50302, open your browser on http://localhost:50302/ **
× Failed to compile.

I reinstalled both angular and node. I installed node packages several time with the help of NPM install. I create new angular project and paste my source folder of previous project in new project file.
Angular cli version :
Comment: Some code would be useful. A compilation error indicates some issue with your code.
Comment: [Here](https://stackoverflow.com/questions/57331779/typescript-duplicate-identifier-iteratorresult) looks like someone had a problem like you (sorry if not help)
Answer: You can try following steps

Delete the node_modules folder from your project directory.
Open the command prompt or terminal and run npm install to install
all the required packages for your project.
After the packages are installed, try running the project again with
the command ng serve -o.