Control line breaks writing yaml from Python

Question: I'm writing a YAML file using the yaml library in Python 3, and I'd like to choose where it puts the line breaks when writing a long block of text.
Here's a silly example of the kind of thing I'm trying to do. The days entry is a long block of text with several items separated by commas. I'd like to keep each item together on a line, but in this example, "9 Ladies Dancing" gets split.
from yaml import safe_load, safe_dump

s = """\
- title: 12 Days of Christmas
- days: A partridge in a pear tree,
    2 Turtle Doves,
    3 French Hens,
    4 Calling Birds,
    5 Gold Rings,
    6 Geese a-Laying,
    7 Swans a-Swimming,
    8 Maids a-Milking,
    9 Ladies Dancing,
    10 Lords a-Leaping,
    11 Pipers Piping,
    12 Drummers Drumming
"""
l = safe_load(s)

print(safe_dump(l, default_flow_style=False))

This prints out:
- title: 12 Days of Christmas
- days: A partridge in a pear tree, 2 Turtle Doves, 3 French Hens, 4 Calling Birds,
    5 Gold Rings, 6 Geese a-Laying, 7 Swans a-Swimming, 8 Maids a-Milking, 9 Ladies
    Dancing, 10 Lords a-Leaping, 11 Pipers Piping, 12 Drummers Drumming

I'd like to load the full text of days in as a single line, but I want to print it out as several lines up to 80 characters wide to make the items easier to review for correctness. I want several items on a line, but I'd like to split the lines at a comma so items don't get split across lines.
Answer: One simple solution is to set the width to something huge, but I don't want to do that.
Hopefully, there's a feature of the yaml library that I haven't found yet, but this is the best I've come up with:
from yaml import safe_load, safe_dump, SafeDumper, dump

s = """\
- title: 12 Days of Christmas
- days: A partridge in a pear tree,
    2 Turtle Doves,
    3 French Hens,
    4 Calling Birds,
    5 Gold Rings,
    6 Geese a-Laying,
    7 Swans a-Swimming,
    8 Maids a-Milking,
    9 Ladies Dancing,
    10 Lords a-Leaping,
    11 Pipers Piping,
    12 Drummers Drumming
"""
l = safe_load(s)

print(safe_dump(l, default_flow_style=False))

class SplitDumper(SafeDumper):
    def write_plain(self, text, split=True):
        delimiter = ','
        if split:
            pieces = text.split(delimiter)
        else:
            pieces = [text]
        buffer = ''
        for i, piece in enumerate(pieces):
            if i > 0:
                buffer += delimiter
            if self.column-1 + len(buffer) + len(piece) <= self.best_width:
                buffer += piece
            else:
                super(SplitDumper, self).write_plain(buffer, split)
                self.write_indent()
                buffer = piece
        super(SplitDumper, self).write_plain(buffer)

print(dump(l, default_flow_style=False, Dumper=SplitDumper))

The SplitDumper class overrides the write_plain() method to split it into chunks at the commas, and then detects how many chunks it can write on each line.
That prints out the default splitting, followed by the custom splitting:
- title: 12 Days of Christmas
- days: A partridge in a pear tree, 2 Turtle Doves, 3 French Hens, 4 Calling Birds,
    5 Gold Rings, 6 Geese a-Laying, 7 Swans a-Swimming, 8 Maids a-Milking, 9 Ladies
    Dancing, 10 Lords a-Leaping, 11 Pipers Piping, 12 Drummers Drumming

- title: 12 Days of Christmas
- days: A partridge in a pear tree, 2 Turtle Doves, 3 French Hens, 4 Calling Birds,
     5 Gold Rings, 6 Geese a-Laying, 7 Swans a-Swimming, 8 Maids a-Milking,
     9 Ladies Dancing, 10 Lords a-Leaping, 11 Pipers Piping, 12 Drummers Drumming

Answer: The string is already a single line after it's loaded:
>>> l
[{'title': '12 Days of Christmas'}, {'days': 'A partridge in a pear tree, 2 Turtle Doves, 3 French Hens, 4 Calling Birds, 5 Gold Rings, 6 Geese a-Laying, 7 Swans a-Swimming, 8 Maids a-Milking, 9 Ladies Dancing, 10 Lords a-Leaping, 11 Pipers Piping, 12 Drummers Drumming'}]

Have you considered using a block? See Preserve new lines in YAML
>>> s = """\
... - title: 12 Days of Christmas
... - days: |-
...     A partridge in a pear tree,
...     2 Turtle Doves,
...     3 French Hens,
...     4 Calling Birds,
...     5 Gold Rings,
...     6 Geese a-Laying,
...     7 Swans a-Swimming,
...     8 Maids a-Milking,
...     9 Ladies Dancing,
...     10 Lords a-Leaping,
...     11 Pipers Piping,
...     12 Drummers Drumming
... """
>>> safe_load(s)
[{'title': '12 Days of Christmas'}, {'days': 'A partridge in a pear tree,\n2 Turtle Doves,\n3 French Hens,\n4 Calling Birds,\n5 Gold Rings,\n6 Geese a-Laying,\n7 Swans a-Swimming,\n8 Maids a-Milking,\n9 Ladies Dancing,\n10 Lords a-Leaping,\n11 Pipers Piping,\n12 Drummers Drumming'}]

Comment: Yes, I want the text to be loaded into memory as a single line. I just want it to be written into a YAML file as multiple lines to make it easier to review for correctness. By splitting on the commas, each item to review will be kept together. I'll look at using a block, and see if that will work for me. Thanks for the suggestion.


How to transfer files between my Android device and my laptop via WiFi?

Question: Is there an application that I can install in my Ubuntu laptop and will allow me to transfer files via wifi to and from my Android device, which has Zapya installed?
Comment: @user68186 That requires internet access, which I don't have sometimes. Is there a way to set this up offline, through local wifi?
Answer: I have never used zapya and don't recommend it
When I tried to download the Zapya for PC, I got a warning from Chrome that the page may contain malware. In any case, their web page said nothing about a Linux/Ubuntu download.
Here is an alternate solution
From Google Play store install Web PC Suit app into your android device.
Open the App. You will see something like this:

Note there are two web addresses shown. The first will need internet connection and show a qrcode, that you can scan using the app. You don't need to do this if you are concerned that contents of your Android device will be exposed to the Internet!
Use the local IP address, the second line with http://. The second line looks like a bunch of numbers: 192.168.0.7:8080. Yours will be different. Don't copy the number (also known as IP address) from this answer.
Type the IP address shown in the app, into your PC's web browser such as Firefox. Make sure the dots .s and the : are in the right places.
You will see a notice in the android app telling your someone is trying to connect to your android device. That someone is you! touch the Accept button.
The rest should be easy.
What is going on?
The Android app is basically a small web server that exposes the content of your Android device in a web page via a local IP address. You access the web page by typing the IP address in your browser.
The same content is forwarded to the App maker's external web server when you scan the QRCode, as this allows the app to communicate to the external server.
Is it safe?
It has some safeguards, such as if anyone tries to connect to the App (the web server in your Android device) then the app asks you to accept or reject. You should not accept the connection if you did not initiate it from your own PC.
Beyond this, I can't say how safe it is. If you don't trust the App maker and Google's system of vetting apps, you should not use it.
There are other similar tools like AirDroid that do file transfers the same way as above, and more.
Hope this helps
Comment: port 8443 is for https that is ok it is in the settings
Comment: Is this safe? coz I was asked to scan a qrcode from the website and then it just did nothing other than taking me to a page where the buttons on the left panel were were not responding so I shut it down and uninstalled the app.
Comment: I had tried that before scanning, did nothing just opened a page with no interaction, no option to accept came to the phone, I used my own phones IP address and the correct port but that just kept showing an animation of accept in phone. I will install once more to try if this works in case you have additional information. Thanks for the quick reply and the solution seems good.
Comment: I feel the app may not be just sharing, it may be potentially harmful, I uninstalled it again, after testing it I realized it starts automatically, freezes the screen and this I am not comfortable with, so I think its not worth it. I personally had used snappea to connect my phone but that was in windows.
Comment: thanks for the quick update, what I get is this [Phone Screen](http://i.imgur.com/HprtCCM.jpg) and this [Browser Screen](http://i.imgur.com/SJoxazX.jpg) and no way to do anything, my phone freezes in that I just need to use the home key to go back, the back key does not work, I personally decided to uninstall this,though this may still be an option for others.
Comment: No problems, I was just checking to give this answer a vote, lets hope the app works for the OP, problems may be related to Android 5.1 that's running on this.
Comment: Thanks @Ads There are some other apps like AirDriod that works the same way. It will be great if you can try and let me know. I am using Android 5.1.1. See http://www.techrepublic.com/blog/tablets-in-the-enterprise/transfer-files-between-your-android-tablet-and-pc-using-wi-fi/ and http://www.talkandroid.com/guides/beginner/best-android-apps-for-transferring-files-over-wifi-june-2013/
Answer: You should install in your Android device a FTP server. Example:
FTP Server for Android
Then you must install a FTP client in your Ubuntu. You can use Filezilla.
Finally connect from your Ubuntu to your Android. You can copy, move, delete,...


PlotlyDash: How to change line color?

Question: I'm using plotly dash to create a line chart and want to change the lines to a specific color. You'll see this in my code, but it doesn't change the colors from the default. I'm guessing I'm doing this wrong. There is a way to change the color right? And if so, how do I fix this?
dcc.Graph(id='henry',
        figure={
            'data':[
                {'x':dates,'y':henrycases,'type':'line','name':'Cases','color':'red'},
                {'x':dates,'y':henrydf,'type':'line','name':'Wait Time','color':'black'}
                ],
            'layout':{
                'title':'Henry County Wait Time and New Cases per Day'
                }

Answer: You can specify the line colors like this
dcc.Graph(
    id='henry',
    figure={
        'data': [
            {'x':dates,'y':henrycases,'type':'line','name':'Cases','line':dict(color='red')},
            {'x':dates,'y':henrydf,'type':'line','name':'Wait Time','line':dict(color='black')}
        ],
        'layout': {
            'title':'Henry County Wait Time and New Cases per Day'
        }
    }
)

Alternatively like this
dcc.Graph(
    id='henry',
    figure={
        'data': [
            {'x':dates,'y':henrycases,'type':'line','name':'Cases','line_color':'red'},
            {'x':dates,'y':henrydf,'type':'line','name':'Wait Time','line_color':'black'}
        ],
        'layout': {
            'title':'Henry County Wait Time and New Cases per Day'
        }
    }
)

PlotlyDash: How to change line color?


Does the Orc's berserker ability work for spells?

Question: I tested this and my initial observation was that it doesn't.
However, I only used the starting destruction spell flames as I didnt want to progress too far before finding out my Orc Mage was not viable. Using flames made it difficult to see if a 2x bonus was occurring.
Am I correct in assuming the berserker ability does not affect spells?
Comment: It would surprise me. Magic is traditionally not an Orc's forte, and berserking shouldn't improve magic (nor damage dealt with magic).
Answer: The strategy guide confirms that it does not affect spells (emphasis mine):

Berserk: For 60 seconds, you take half damage, and inflict double damage in melee combat.

Melee combat consisting of one-handed and two-handed weapons, not spells or bows.
Answer: Berserk works with bows. I just tested it with a plain old not enchanted bow and a bear.
I do not know about berserk with magic, summon, or enchanted weapons.
Comment: This isn't really an answer to the question, which was about spells, not bows.
Answer: It works for Bows and any Melee Damage (Including Conjuration Weapons).
It increases your Physical Defense, but Magic resistance does not apply


How to design a "data usage calculator" for a brand new smartphone users

Question: What are some ways wireless carriers can help smart phone buyers visualize how much data they will need so they pick a suitable data plan option?
Various carriers provide data usage calculators: eg
https://my.ee.co.uk/data-calculator/
But this misses one very important criteria:  where do you use your smartphone ? - because if you use it on your home wireless network your data usage will be dramatically different from using just the mobile connection.
So what criteria actually matter in the design of the calculator ?
Comment: PS - the key criteria is how much you'll be using the phone away from your home wi-fi. If you use it mainly at home then you won't be using much of the mobile data.
Comment: I would suggest to get the lowest GB possible and simply use the phone however you please. Check the data usage once a week to make sure you do not suffer overages. You *should* be able to add more GB at a reasonable price if needed. The first few weeks of owning a smartphone seem to cost the most data because you end up playing with all of the features. If you plan on watching a lot of YouTube then expect to plow through your data limit and pay overages. Assuming you have WiFi then you should be able to mitigate your mobile data usage.
Comment: There's also data usage calculators offered by most wireless carriers if you want to do a rough estimate. Just google for "data usage calculator"
Comment: Currently you've written this as a 'consumer question' so it will get closed.  However if you re-word it as 'How do I demonstrate to users what 1GB of data actually looks like ?' its a useful question which mobile phone companies might want to take note of on their websites.
Comment: @PhillipW, would you be kind enough to rewrite it?
Comment: Re-written. Feel free to edit further.
Answer: Most users can relate to digital media
Sometimes I convert the cost of various items into NetFlix subscriptions to emphasize how much my wife doesn't need that new pair of shoes costing the same as 14 months of NetFlix.  Most users are aware of how much media they consume on their phone which is good since this also happens to be the main thing taking up data.
One major hurdle to using a number of pictures, songs, and movies is the wide range of formats used to shrink them down.  This means that two different people could view the same number of each item and one consumes 10GB while the other only consumes 1GB of data.
Similarly, the difference between standard and high definition (HD) video is so huge that it may even make sense to ask the user if they plan on streaming HD or standard video feeds.
Any data estimation calculator must clearly communicate this fact to the user.
The link to the sample calculator was a little too cumbersome.  Even if we only focus on digital media it has such a wide margin of error that is bigger than all the other types of data usage combined.
Only focus on non-wifi usage
Make it clear to the user that in order to correctly estimate the proper data usage plan they should only count the number of media files they consume while not connected to a wifi network at home or at work.  The demo calculator had slider positions for "a little", "medium", "a lot" which is bad!  This can mean different things to different people so ask for an actual count or number of hours they plan on streaming the different types of media.


How to set WebApi request header on server side

Question: I'm trying to use MVC to call a WebApi method according to HTTP. I need to send some info every time, like userID and app version. How can I add this info to the header? I want to do it as an ajax call, not by client side code like it is now):
      'beforeSend: function (req) {
                req.setRequestHeader("Accept", "version=1.00,requestTime=" + new Date());
            }'

But on server side, I can't set RequestHeader with string
This is my server code:
 HttpClient client = new HttpClient();
 var request = new HttpRequestMessage()
        {
            RequestUri = new Uri("http://localhost/WebAPIDemo/FilterAttribute-MVC"),
            Method = HttpMethod.Get,
        };

        request.Headers.Accept.Add(***);
        //request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        List<OfficeSupply> os=new List<OfficeSupply>();
        var task = client.SendAsync(request)
            .ContinueWith((taskwithmsg) =>
            {
                var response = taskwithmsg.Result;

                var jsonTask = response.Content.ReadAsAsync<List<OfficeSupply>>();
                jsonTask.Wait();
                var jsonObject = jsonTask.Result;
                os = jsonObject.ToList();
            });
        task.Wait();

*** needs to be a 'MediaTypeWithQualityHeaderValue' type value,but I just want to set it to custom, like the ajax call. How should I do it?
Also, I want to change Header Authorization parameter, but this code:
 'client.DefaultRequestHeaders.Add("Authorization", "12345");'

did not work and
  request.Headers.Authorization.Parameter

told me it is read-only.
How do I set it on the server side before sending?
Answer: You can specify a custom auth scheme by doing something like,
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("scheme","whatever parameters");

You can set a completely custom header with code like this:
request.Headers.TryAddWithoutValidation("foo", new List<string>() {"sdadads"});

Be careful though, the accept header example you showed above is completely invalid. There are very precise rules as to how the contents of an accept header should be formatted and your example is not valid.
Comment: Hi!I've tried your code, but it doesn't show on chrome request headers(F12 Network Headers),everything has not changed
Comment: How would Chrome be able to see the request if it is coming from a httpClient request?  Use fiddler to see the request.
Comment: Fiddler request headers only has:four accept param and a user agent?
Answer: I used to follow the below approach to set request header.  Please try it if works for you.
[Script]
 $("#Grid1").ajaxSuccess(function (evt, request, settings) {
    $('.Status').html(request.getResponseHeader("Status"));
  });

[View]

Status:

[Controller]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Order orders)
    {
        string status = string.Empty;

        if (orders != null)
        {
            OrderRepository.Update(orders);
            status = "Updated";
        }

        Response.AddHeader("Status", status);
        return data.GridActions<EditableOrder>();
    }

Comment: Sorry,I want to set request header,not the response,and for webapi,I need use HttpClient and HttpRequestMessage to send request,I just don't know how to set the object's property properly,by the way,which tool do you used to get the header?browser?
Comment: It is 'firebug' developer addon in Firefox browser.
Comment: @Ray You don't _need_ to use HttpClient to call Web API, you can use any software that can make a http request.


Manipulating exponents of prime factorizations

Question: Has work been done on looking at what happens to the exponents of the prime factorization of a number $n$ as compared to $n+1$? I am looking for published material or otherwise. For example, let $n=9=2^0\cdot{}3^2$, then,
$$
9 \;\xrightarrow{+1}\; 10
$$
$$
2^0\cdot{}3^2 \;\xrightarrow{+1}\; 2^1\cdot{}3^0\cdot{}5^1
$$
or looking just at the exponents,
$$
[0,2,0,0,...] \;\xrightarrow{+1}\; [1,0,1,0,...]
$$
I realize the canonical way of reaching the latter is generating the prime factorization of $n$ and of $n+1$ separately, but has there been any research into manipulating the exponents directly instead (short-cutting around the factorization)?
For anyone who can't answer but still wants to see something interesting, check out FRACTRAN.
Comment: As far as I know, the smart money is that there is essentially no relationship between the prime factorization of $n$ and the prime factorization of $n+1$ (other than the fact that the primes must be distinct). This can probably be made precise in various ways.
Comment: Any prime appearing in the factorization of $n$ doesn't appear in $n+1$, and vice versa.
Comment: I would guess the behavior to be too erratic for anything intelligible to be said.  As @Yuval points out, for every integer $n$, we have $\gcd(n,n+1) = 1$.  Even worse, if you start with (or end with) a prime $p$, then you can go from a prime $p$ to a number with $\approx \log(n)$ prime factors.
Comment: Apart from the disjointness of prime bases in factoring $n$ and $n+1$ pointed out by Yuval, the only general observation I can think of is that the map is cycle-free (because of the monotonicity of adding 1).  As a special case note that [Catalan's conjecture (now Mihăilescu's theorem)](http://en.wikipedia.org/wiki/Catalan's_conjecture) tells us that the only case of mapping from a single prime exponent greater than 1 to another is $2^3 + 1 = 3^2$.  Fermat and Mersenne primes are also special cases where argument and image both have single entry support (but one exponent is 1).
Comment: @DJC: is even that much known?  It's obviously plausible and widely believed that there are infinitely many Mersenne primes, or primes of the form $k^n\pm 1$, but AFAIK there aren't any specific instances where infinitely many primes are known...
Comment: @Steven: My comment did not intend to speak about Mersenne primes.  I was only (and not very precisely) saying that an "average" number had $\approx \log n$ factors.  To say anything inteligible about what information the prime factorization of $n$ has to do with the prime factorization of $n+1$, one would have to also deal with the extreme case of going from a prime to a prime plus one.
Comment: @DJC Ahhh - in that case, I think you're missing a log; average numbers have roughly $\log \log n$ factors.  I suspect that there _are_ infinitely many primes $p$ such that one of $p\pm 1$ has 'a lot' ($O(\log p)$) of factors, but that's a different and probably hard statement. :-)
Comment: @Steven: Thanks for letting me know!  That is probably a difficult statement if $n$ has on average $\log_2(n)$ factors.  Cheers!
Answer: If we could deduce the prime factorization of a number $n+1$ from the prime factorization of the number $n$, then by induction we could in particular arrive at the prime factorization of all numbers. By the way, this would allow us to find new prime numbers. Since prime numbers seem to appear at random in the set of integers, I doubt this method would work.
Comment: It has wide implications, that is why I am interested in any work that has been done in this area.
Comment: This would carry more force without the second and third sentences! Finding new prime numbers is easy compared to factorising.
Comment: this would be a $O(n)$ factorization algorithm, worse even than trial division. There are good reasons why you can't expect to learn much about the factorization of $n+1$ from that of $n$, but I don't think the domino theory is one of them - too many dominoes!
Answer: I found this on MO which is relevant to the question:
https://mathoverflow.net/questions/55010/prime-factorization-of-n1


Android - is it possible to open a database file that download from web services using "sqlite asset helper"?

Question: This is the logic I am trying to achieve:

Download the database from web services
unzip it
load the database using SQLite asset helper
delete the zip file

I am wondering if it is possible to achieve using SQLite asset helper, or I should use other method?
Answer: SQLiteAssetHelp is designed to copy the database file from the assets folder, which is part of the shipped app package.
You already have the file; copying is not necessary.
Just open your file through SQLiteDatabase.
Comment: Thank, very clear.

Just a wondering If you can help me out here
where should I store downloaded database so I can use SQLiteDatabase to open it.
Comment: To ask a question, use the "Ask Question" button.
Answer:
I am wondering if it is possible to achieve using SQLite asset helper

No, sorry.


Intermittent (each startup) Wi-Fi with an Edimax EW-7318USg

Question: Firstly, Wi-Fi works 100% of the time on my Ubuntu netbook, my Android phone and my Windows install (on the same computer/USB-wifi device), so I don't think this can be a router issue... It would be strange if it were a driver issue as it sometimes connects, but FYI the USB-wifi device is a Edimax EW-7318USg.
Second, if it does connect (during this session) then it connects first time, else it will not connect (no matter how long I try). Wi-Fi does connect about 20% of the time (restarting the computer about 5 times usually allows me to connect). Once it has connected it stays connected (until restarted).
Obviously it is hugely irritating! Any ideas how I can remedy this?
EDIT: As requested, the results of running sudo lshw -class Network:
description: Ethernet interface
       product: MCP77 Ethernet
       vendor: nVidia Corporation
       physical id: a
       bus info: pci@0000:00:0a.0
       logical name: eth0
       version: a2
       serial: 00:19:66:d3:fe:21
       capacity: 1Gbit/s
       width: 32 bits
       clock: 66MHz
       capabilities: pm msi ht bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=forcedeth driverversion=0.64 latency=0 link=no maxlatency=20 mingnt=1 multicast=yes port=MII
       resources: irq:41 memory:fcf7c000-fcf7cfff ioport:c880(size=8) memory:fcf7e400-fcf7e4ff memory:fcf7e000-fcf7e00f
  *-network
       description: Wireless interface
       physical id: 1
       bus info: usb@1:2
       logical name: wlan0
       serial: 00:0e:2e:4d:ff:b4
       capabilities: ethernet physical wireless
       configuration: broadcast=yes driver=rt73usb driverversion=2.6.38-8-generic firmware=1.7 ip=192.168.2.6 link=yes multicast=yes wireless=IEEE 802.11bg

Is this a known bug or should it be filed as one? (if so, which or against what?).
Comment: google didnt bring up any hits for that model - are you sure if it is correct?  Please add to your question the results of sudo lshw -class Network
Comment: My mistake, I misread the S for an 8, it's actually an EW7318USg. Thanks!
Comment: @fossfreedom I have corrected the device name in the question, and inserted the results of sudo lshw -class Network. Many thanks.
Comment: This question should instead be filed as a bug report, and [as such](http://meta.askubuntu.com/questions/1317/what-to-do-with-questions-that-describe-known-bugs/) is off-topic, thanks! [Instructions here](http://askubuntu.com/questions/5121/how-do-i-report-a-bug).
Answer: Find out if any log entries are helpful - I usually do:
touch $HOME/now
Record the time right now.
Then, make the event happen (or, wait until the event happens, doing periodic touch $HOME/nows.
Then, after the event has happened, do find /var/log -cnewer $HOME/now to get a list of the log files that were changed between the most recent touch $HOME/now and the find command. Look at the last N lines of each.


Code skips the input for the name of driver 2 & 3 but prints for driver 1 as well prints the output of km as 0.00 for all drivers

Question: I was writing code to prints the details of three drivers but the problem is the program takes the input of driver 1 correctly but skips the input for name for driver 2 and 3 ,also despite providing the input it prints the distance travelled as 0.0.
#include<stdio.h>
struct data
{
    char name;
    int dlo;
    char route;
    float km;
}s1,s2,s3;
void details(struct data *d)
{
    printf("Enter your name: ");
    scanf(" %s",&d->name);
    printf("Enter your driving license no: ");
    scanf("%d",&d->dlo);
    printf("Enter route taken: ");
    scanf("%s",&d->route);
    printf("Enter distance travelled: \n");
    scanf("%.2f",&d->km);
}
void output(struct data *d)
{
    printf("Driver name: %s\n", &d->name);
    printf("Driving license no: %d \n", d->dlo);
    printf("Route taken: %s\n", &d->route);
    printf("Distance travelled: %.2f \n", d->km);
}
int main()
{
        printf("\n--------------driver 1---------------\n");
        details(&s1);
        printf("\n");
        output(&s1);
        printf("\n--------------driver 2---------------\n");
        details(&s2);
        printf("\n");
        output(&s2);
        printf("\n--------------driver 3---------------\n");
        details(&s3);
        printf("\n");
        output(&s3);
    return 0;
}

the output comes likes this:
--------------driver 1---------------
Enter your name: abhishek
Enter your driving licence no: 123
Enter route taken: abcd
Enter distance travelled:
123

Driver name: abhishek
Driving licence no: 123
Route taken: abcd
Distance travelled: 0.00

--------------driver 2---------------
Enter your name: Enter your driving licence no: 321
Enter route taken: efgh
Enter distance travelled:
45

Driver name: 123
Driving licence no: 321
Route taken: efgh
Distance travelled: 0.00

Comment: @Aconcagua  I will make sure to follow your advice from now on, thank you for your advice
Comment: `char name;` can store 1 character, like `'A'`, but not `"Abhishek"`. Change it to `char name[50];` and remove the `&` in front of `d->name` at the `scanf` and `printf`
Comment: I have shown how the outputs comes in the question please go through that
Comment: Actually `char name` cannot even store a single character if you intend to use that as string, as you need room for the terminating null character – which in this case would occupy the only available character place...
Comment: The problem is that you actually invoke *undefined behaviour*. You write beyond array bounds (you can consider `char name` equivalent to an array of length 1), so *anything* can happen, even (by accicent!) outputting the expected result.
Comment: You need to, as @mch already mentioned, provide an array of sufficient length, though I personally would prefer powers of two (32, 64, ...). What you should then do, too, is providing the array length to the format string such that `scanf` won't write beyond array bounds either due to too long user input, so (assuming 50 as proposed by mch): `scanf("%49s")`. Be aware that you need to provide one character less than array length to leave space for the terminating null character!
Comment: The same, of course, applies to `route` as well.
Comment: Off-topic: While `float` appears convenient at a first glance it can render pretty problematic later on due to rounding issues. Be aware that even such a simple number like `0.1` cannot be represented exactly in binary as it is periodic there. You'll encounter problems like [comparing floats](https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison) (note its extension on [relative epsilon](https://stackoverflow.com/a/67843030/1312382), too).
Comment: You get around all that trouble if you store the values in integral types (`int`, `long`, `long long` – or in this case preferably their unsigned counter parts as negative distances appear meaningless anyway), if appropriate using sub-units of the actually desired unit (in this case meters instead of kilometers). Parsing input gets more difficult, sure (if you still want to input kilometers – and outputting, too, but only minimally), but that pays back later on.
Comment: i did as you advised but the problem remains the same ,`Enter your name: Enter your driving licence no:` is being printed
Comment: the problem is solved I just had to change `%.2f` to `%f`, but I don't understand how `%.2f` affected my code
Comment: @AbhishekOjha if you solved your issue, please provide an answer and accept it using the green tick. Thank you.
Comment: @user438383 I am still new here can you tell me how to do that
Comment: @AbhishekOjha The period is not valid for [`scanf`](https://en.cppreference.com/w/cpp/io/c/fscanf) (differing from `printf` in this respect) – not sure how your implementation of `scanf` did handle that. Any number following the `%` character defines how many characters are legal to be consumed, so assuming the period simply was ignored only two characters would have been read then (i. e. only `10` from `100.5`) – though it rather seems as if your implementation did not read in anything at all.
Comment: Oh, and even if just replacing "%.2f" with "%f" seemed to fix the issue – please *do* consider the single char issue commented before – while seemingly working you still rely on undefined behaviour, so the code seeming to working now might fail at any time later (when you'll least expect it), when using a different compiler or on another machine.
Answer: The problem was that I used %.2f in the scanf which resulted in a Run-Time Error thus by changing the scanf("%.2f",&d->km); to scanf("%f",&d->km); the error was solved also I had to use array for name and route to avoid further Run-Time Error.
I really appreciate everyone for their advice.


Proper Term for "Phone Type"

Question: We have several forms which enable users to enter a phone number.  Corresponding to the number, we have a "Phone Type" field which allows them to select work, mobile, home etc.
Phone Type lacks descriptiveness but I haven't been about to see any particular semantics for the term.
In this case, what is the proper term for "Phone Type"?
Comment: To keep it simple for user, Preferred contact or alternative number
Comment: why do you even need to know that?
Comment: Could you please give a bit more context? What do you need that information for?
Comment: This was written in a mobile confirmation order. My question is: What is the meaning of "Other"?
Answer: Why do you need to know the phone type? Is what you really want to know the preferred phone number and secondary phone number?
It seems to me that when people ask for "home", "work" and "mobile" phone numbers, they are assuming that the home number is preferred, and you should try to reach them at that number first. One might then try work number  during the day and then the mobile phone last since that was once considered an expensive call.
But none of these assumptions holds true today. I might want you to call me at work in the evening if the mobile number is somehow not answered (when does THAT happen?) and really never to call the home landline (if such a thing exists). In my case, for example, I do not have a home landline and nobody ever calls me at my work number (except for wrong numbers). I prefer everyone just call my mobile phone.
This situation is a good example of the UX principle to identify the need rather than just collect data or go with what we've always done before or what our competition does.
Unless you are gathering data on what sorts of telephones your users have, I would assume you are trying to gather information on how to contact them and some priority of method.
So why assume when you can ask them?
Give three phone number options:

Preferred phone number
Alternate #1
Alternate #2

Or
Please let us know how to reach you:

Daytime telephone number
Evening telephone number
Alternate telephone number
Comment: @luchomolina: the answer isn't assuming that.  It's asking OP to question what purpose they are really using the information for, and suggesting time-based preference as one likely answer.
Comment: Why do you assume that the reason why @zwerdlds needs this information is to give the numbers a preference when deciding the best time for calling?
Comment: @zwerdlds "Phone Type" is accurate if you have no idea what any of the numbers will be used for. Any other term, as Eric has answered, requires context. I'm not sure how you can design a form to collect and store personally identifying information without any context.
Comment: You need phone type to know what value the phone has to marketing and spamming services: if it is a mobile, they cannot put it on certain lists, etc.
Comment: "the mobile number is somehow not answered (when does THAT happen?)" - If you're not in my contacts, I send it to voicemail  ;)
Comment: Izkata, I do the same thing! But presuming this was a valuable service to me I would add it to my contacts. My point is that I suspect most people's primary (only?) contact number is mobile.
Comment: Obviously, phone type matters if it is going to be used, for example, to send confirmation texts rather than voice calls. In this case it has nothing to do with preferred contact method.
Answer: Version A
I think Apple has a very good and simple design pattern for the "Phone Type". They are not even displaying a label (see below).
Given the customer base you have, take a look at the most common "type" people are choosing / selecting and make it your default.

Version B
O.R. Mapper brought up a good point in comments below about tooltips, which I think is a good point and maybe a better UX given a different audience. The tooltip could provide all necessary information describing the group and labels for each field.
Comment: Indeed. Not everything needs a label.
Comment: Can you upload a screenshot / wireframe of what those forms look like and i'd be happy to provide an alternate solution given your particular situation.
Comment: @zwerdlds The best terminology depends on the situation. Without more context, the safest label would be the generic "phone type". Which may or may not be helpful for a particular use case.
Comment: If you MUST use a label AND if you are asking what that label should be, then 'Phone Type' is clear and common label, it's used by Google Voice and other VoIP companies when setting up your account. If you are looking for possible alternatives, Stanley is right, 'Label', 'Type' could suffice. Other option is 'Phone Location' (assuming multi-level office and different conference rooms). Third alternative would be asking users to 'nickname' the phone, but it's not a common pattern. IMHO, i dont see what is preventing you from dropping that label and simplify UX
Comment: Is this really a quote (and if yes, from which source)?
Comment: If it doesn't have a label, how do you refer to it when speaking about the UI on the phone, or in the manual? *Everything* should have a label/name, even if that label/name only appears in a tooltip.
Comment: if phone fields are together as shown on the wireframe you can refer to a 'Phone Type' or similar in that context. Even if the field does not have a label - it's easy to put it together if a question or statement is worded properly
Comment: @Igorek: I disagree, in particular when there is a separate field for the extension (which might also be interpreted to refer to some "type"). Even if *you* use a uniform name, I guarantee that at least some users will not understand which one is meant or make up their own indeed misleading terms. All of that causes disruptions in communication (think support calls), and if the "official" name/label is not shown anywhere in the UI, these disruptions are likely to persist. So, to avoid future headache, I argue that each field should have a name from the beginning.
Comment: @O.R.Mapper, do you have some research or usability date you can share? I've never ran into such situation that would support your statement in this particular problem. It would be interesting to read and learn.
Comment: @Igorek: Unfortunately, I can only offer my personal experience that almost every conversation with users about software that involves controls that are not clearly labeled/named in some way invariably leads to confusion due to differing terminology sooner or later. (And the same applies to following written tutorials on such GUIs oneself.) On the other hand, I have never witnessed a drawback of a control having a label/name, in a way that a user would have complained about the presence of a label/name, or was unable to understand or do something because the label/name was there.
Comment: @O.R.Mapper  Good feedback. I'll make a note to self to do an test with a larger audience, now you got me curious. I think you are right, it would be silly to assume everyone will get it, however the edge case we are discussing MAY be so small that it would be easier to educate that small group rather than enforcing old practices. I'll let you know when I do a larger test and thank you for pointing it out.
Comment: @Igorek: As I said, if you're concerned about space, at least provide a name in a tooltip. But by providing some kind of a consistent name, you usually help at least your own developers, probably also some of your users, and possibly even people writing tutorials or books about your software. By putting the name/label in a tooltip, your answer is useful for the GUI as such, but at the same time, the question of how to call it remains relevant.
Answer: I think you should leave it more of a free form, because the labels may not necessarily correspond to the numbers assigned. It is up to the user to label them appropriately, thus LABEL or TYPE

I can have someone's number that is a mobile phone but it could act as an office number...so to lessen the confusion I think just LABEL and leave it in the hand of the user to allocate them as they see fit.
Comment: In this case we have a need to tie it to a pre-existing format, which includes the various "types" of phone numbers, so enabling a user-defined label is not appropriate.
Comment: i think LABEL would still work in your condition.
Answer: One thing that could be clarified is the meaning of phone type. Does it refer to the situations and types of calls the phone is used for? Or the location of the phone? Is a work-phone one that is physically located at the office all the time (like a typical stationary/landline phone), or could a mobile phone which you take with you also be a work-phone if you use it for work related calls/tasks from home?
If phone type refers to physical location, then perhaps "Phone Location" would be the right term. In this case "office" might be a more precise term than "work".
If phone type refers to situation/type of calls, then perhaps "Phone Usage" would be the right term. In this case "personal" might be a better term than "home", and you might remove the "mobile" option.
A more generic term to cover both cases would be "Phone Context", but the ambiguity (are they asking me for location or usage?) might be confusing for some users.
Also, it is worth considering whether the options should be mutually exclusive or not. For example, I only have a mobile phone, which I use for everything, both personal and work. If you were asking me for location, I would select "mobile". If you were asking me for usage then I would select both "work" and "personal".
Answer: If you are collecting contact information, you are presumably also collecting email address, and/or other information. You can add a contact method subsection and allow user to select any at random.
Alternatively, if the options are predefined, you can use toggles below the input to select the type.
Also you can autodetect if it is a mobile phone number or a landline and show appropriate toggles, so you can reduce the options shown at a time.
"Device type" is a good term if you want to stick with your method.
Comment: '"Device type" is a good term if you want to stick with your method.' - aren't my home landline phone and my work landline phone really the same type of device?
Comment: Contact method is a good term then. But it is too broad of a term and should then include email, mail and other options as well.
Answer: As long as it is clear that it pertains to the phone number provided*, what about "Contact Type"? (*so as not to invite answers like "email", ie. confusion with "preferred contact type")
Comment: Because "phone type" makes me want to answer "Samsung Galaxy" or "corded"

Proper Term for "Phone Type"


Simple way to setup MTA on FreeBSD only for PHP mail()

Question: I need to setup mail server for sending from PHP scripts only. I'm not needed to receive email or sending it by another way. Preferable is the Postfix (it is easy than Sendmail, for example). Ssmtp is doesn't suit me.
Is there some manual or ready-to-run config for this?
Answer: ssmtp has the big disadvantage to loose mails if the mailhub server is not reachable.
there should be at least some spooler for this scenario.
Answer: freebsd handbook is the best resource about your requirements:
http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/mail-using.html
https://wiki.freebsd.org/SecureSSMTP
i prefer ssmtp


$\lnot\exists x(S(x) \Rightarrow R(x))$ VS $\forall x(S(x) \Rightarrow R(x))$ Without Using De Morgan's Law

Question: I was doing logic exercises the other day and I encountered the following:

Write this statement symbolically and verify your answer using De Morgan's Law:
No squares are rectangles

My solution:
Let $R(x): x$ is a rectangle and $S(x): x$ is a square. Now, we know none of the squares are rectangles; so in other words, there doesn't exist a square that's also a rectangle. I thought the following would be the its equivalent: $\lnot\exists x(S(x) \Rightarrow R(x))$ but I also thought, can't we say all squares are not rectangles and so I wrote the following:  $\forall x(S(x) \Rightarrow \lnot R(x))$ but using De Morgan's law, these two are obviously not equivalent and only the latter is right. Could you explain,without using De Morgan's Law, why the first statement is wrong?
Thanks in advance for any help!
Comment: Mathematicians usually consider $x$ and $X$ to be different symbols. You seem to be using them rather interchangeably.
Comment: Could you please explain?EDIT: Is it better now?
Comment: Well, you fixed it now, so it's fine.
Comment: >"but I also thought, can't we say all squares are not rectangles and so I wrote the following: $\forall x(S(x)\implies R(x))$"

Where was the "not" in that sentence? I think you meant to say $\forall x (S(x)\implies \neg R(x))$.
Comment: @JackCrawford yes, thank you. I fixed it.
Comment: See also the post [Representing the statement using Quantifiers](https://math.stackexchange.com/questions/369546/representing-the-statement-using-quantifiers).
Answer:
No squares are rectangles

is the same as "There is no object that is both a Square and a Rectangle".
Thus, in symbols :

$¬∃x(S(x) \land R(x))$;

This in turn is equivalent to :

$∀x(S(x) \to ¬R(x))$,

and this is exactly : "All squares are not rectangles".
The quantifiers equivalence : $\lnot \exists \equiv \forall \lnot$ is one of the most intuitive logical equivalence : if there is no Black swan, then all swans are not-Black (and vice versa).
The next step needs the propositional equivalence is : $\lnot (p \land q) \equiv (p \to \lnot q)$.

Let's start with : "All squares are not rectangles".
What about if there is an object $a$ that is a Triangle ? It is neither a Square nor a Rectangle, and thus $S(a) \to ¬R(a)$ is True ($\text F \to \text T = \text T$).
This means that the object $a$ does not contradict the formula $∀x(S(x) \to ¬R(x))$.
What happens with $¬∃x(S(x) \land R(x))$ ? We have that $S(a) \land R(a)$ is False, and thus we have no issue also with $¬∃x(S(x) \land R(x))$.
But what about $¬∃x(S(x) \to R(x))$ ?
We have that $S(a) \to R(a)$ is True, and thus the Triangle $a$ satisfy the formula $∃x(S(x) \to R(x))$.
This means that the existence of the Triangle $a$ contradicts the formula $¬∃x(S(x) \to R(x))$, and this means that this formula is not equivalent to : "All squares are not rectangles", and thus is not equivalent to "No squares are rectangles" either.
Comment: Thank you for your answer but as I said, I already know what the answer is but why isn't $\lnot\exists x(S(x) \Rightarrow R(x))$ a valid answer?I know it can be easily proven using De Morgan's law but could you explain why it's not a valid answer without using other statements?
Comment: @BornaAhmadzade An $x$ which is neither a square nor a rectangle satisfies $S(x)\Rightarrow R(x)$. So your statement also means that such an $x$ doesn't exist.
Answer: $S(x)\Rightarrow R(x)$ is always true when $S(x)$ is false, that is, when $x$ isn't a square. Therefore the statement $\neg \exists x (S(x)\Rightarrow R(x)) $ would imply, among other things, that there is no object which isn't a square. This is clearly not a conseqence of what you want to convey. As long as there exists object that isn't a square, its existance makes the statement $\neg \exists x (S(x)\Rightarrow R(x)) $ false, but it doesn't falsify the statement "no squares are rectangles".


Who controls the StackLinguist's tweeting?

Question: There is a twitter account which regularly tweets questions from this site. Who controls this tweeting? Is it random, automatic, or controlled by some moderator? If automatic, what determines which question gets tweeted?
Answer: Twitter.com/StackLinguist tweets interesting questions every so often automatically. I emphasize interesting because Twitter is not meant to be an arbitrary RSS Feed.
The feed is designed to publish the most interesting questions from this site every three hours — without ever repeating themselves.
Twitter Question Feeds for Stack Exchange
The Twitter account currently tweets:

per-site blog posts (if you create one)
chat events, if started by a moderator
interesting questions on the site
bountied questions
interesting answers of +3 or better
unanswered questions of +3 or better
particularly hot meta questions (not support or bug though)


SQL Query Alias Explanation

Question: I am having an issue running this query. It is supposed to be stored as a procedure which is what I am doing. What I can't figure out is what a couple of the aliases are referring to.
Link To Full Source: http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
Code:
CREATE PROCEDURE geodist (IN userid int, IN dist int)

BEGIN

DECLARE mylon double;
DECLARE mylat double;
DECLARE lon1 float;
DECLARE lon2 float;
DECLARE lat1 float;
DECLARE lat2 float;

SELECT longitude, latitude into mylon, mylat from users WHERE id=userid limit 1;

SET lon1 = mylon-dist/abs(cos(radians(mylat))*69);
SET lon2 = mylon+dist/abs(cos(radians(mylat))*69);
SET lat1 = mylat-(dist/69);
SET lat2 = mylat+(dist/69);

SELECT destination.*, 3956 * 2 * ASIN(SQRT( POWER(SIN((orig.lat -dest.lat) * pi()/180 / 2), 2) +COS(orig.lat * pi()/180) * COS(dest.lat * pi()/180) *POWER(SIN((orig.lon -dest.lon) * pi()/180 / 2), 2) )) AS distance FROM users destination, users origin WHERE origin.id=userid
and destination.longitude between lon1 and lon2 and destination.latitude between lat1 and lat2
having distance < dist ORDER BY distance limit 10;

END

The Issue I Am Having: In the actual select statement it almost
  immediately refers to orig.lat and dest.lat, also orig.lon and
  dest.lon. I can't find these references anywhere. What are these
  referring to?

When I try to run this query I get an error:

"Unknown Column orig.lat"
Comment: since 'origin' is an alias for the table 'users', my guess is that 'orig' should be 'origin'
Comment: I tried changing that, now i get the error #1054 - Unknown column 'origin.lat' in 'field list' which is the same as before. Thankyou for you help, btw!
Comment: Simple fix, I got it, THanks!
Answer: Your tables are aliased as destination and origin at users destination and users origin.
Presumably, you want to replace orig.lat -dest.lat with origin.lat -destination.lat. You would also do the same with the other references.
Comment: I get the error #1054 - Unknown column 'origin.lat' in 'field list' which is the same as before, thanks for your help, btw!
Comment: Simple fix, I got it, Thanks for the help!

SQL Query Alias Explanation


Menu for expanding list of items

Question: We're giving this site swi-prolog.org a makeover. (The new site's what you're looking at, forgive the mess, we're under construction).
The original was a 'twisty maze of tunnels' of pages that listed other pages. We're trying to get the navigation under control.
We're trying to figure out how to organize the Tutorials menu.
Originally these were scattered all over the site - some were missing, some were linked to only off obscure documentation pages, some were organized by who wrote them, etc.
Some were in a 'howto' overview page linked from the home page (see it at the howto page
)
In consolidating all this I eliminated the howto page and either distributed the material to other tutorials or decided it wasn't important and eliminated it.
In further discussion with the head dev, he argued (rightly) that the material was indeed important, and further, that having an overview page like this was particularly useful, since the website's wikified and we'd like to encourage users to add their own tutorials.
So, now we're wondering how to organize all this. Adding 'More tutorials' to the tutorials menu seems wrong, since it encourages users to look under tutorials, not see what they want in a list, and assume it's not there, but I'm not sure what else to do.
There's a couple of items under 'documentation' that seem to be lurking suspiciously about the margins of this as well.
Forgive our cluelessness - we're a bunch of logic programmers, not UX pro's (volunteers would be vastly welcome 8cD  )
Comment: Why not merge the howto and tutorials page into one, unless there is something I'm not understanding? Isn't a howto and tutorial the same thing?
Comment: yes, I'm sure we'll be doing that. The problem is, what do we do (design wise, we have code to handle it) to make it possible for users to add items, and how does this not become a monster menu with 48 things on it?
Answer: One of my favorite documentation/tutorial pages is that of Laravel.  They start with a quick start page, which gives you the basics.  If you know what you are doing, no need to move on past there.  In the majority case that you don't, they outline the tutorials and documentation on the left side, with a clear order to go through them.  Additionally, as you open each tutorial, there are clear links to get to certain sections of the tutorial, if you are just looking for one piece.
If I understand you correctly, their "Preface" = your "How to", "Getting Started" = your "Beginner", "Learning More" = "Intermediate", etc..

link: http://laravel.com/docs/quick

Menu for expanding list of items


I need to change the Read Only in gedit to Read/Write

Question: I am BRAND new to Ubuntu.
I just installed it along with Win7 as dual-boot.  I need to edit the grub file and reset the grub-timeout from 10 to 0.  I have done this from the terminal with
sudo gedit /etc/default/grub

I then entered my password and got the gedit screen with the grub file on it.  I then changed the timeout from 10 to 0.  Now I find that gedit is marked as [Read-Only].
How can I save my file?
Comment: run with `gksudo gedit /etc/default/grub`. you may need to install `sudo apt-get install gksu` first if you get error "not installed gksudo"
Comment: Hi & welcome to **AU**. Try `gksudo` instead of `sudo`. It is the most efficient way of using the editor.
Answer: To edit configuration files, I would always use in your place a text-based editor:
sudo nano /etc/default/grub

Answer: gksudo gedit /etc/default/grub is indeed the correct answer to your question, however, if you're brand new to Ubuntu, I'd advise you to install Grub Customiser.
Grub Customiser allows you to change a ton of parameters in grub without the risk of you making a fatal mistake. ;-) (Fatal to Ubuntu, not to you!)
In a terminal type:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

and then in the dash type: "Grub Cu" to open it…


Implement a custom COM interface in Java

Question: I need to pull some data from Java into C#. I am already exposing my C# classes via COM. So I thought a good way to pull data from Java would be to expose IReadStream from C# and implement IReadStream in Java. I can then send an instance of the implementation as a parameter to C# so that I can call IReadStream.Read in C#.
How do I implement a custom COM interface in Java?
Comment: You may have to use JNI/JNA to expose a C++ COM interface that your C# class can use.
Answer: I don't know if it supports this direction, but Jacob is a Java COM Bridge that's frequently mentioned.
Also, using IKVM to run the Java code might make the task significantly easier.
Comment: thanks, i know about jacob. don't think it support what i want to do
Answer: Using COM sounds overly messy whats wrong with exposing your c# code via a socket and have java suck that down.
Answer: I went for named pipes in the end.
On the java side I write into a named pipe (served from the c# side). In c# i should now be able to read from the named pipe. As long as the Read operation is blocking it should be the same as pulling data from java.
See http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx for a c# wrapper around the Named pipes api calls.


Differential equations with power series method

Question: Using power series method solve $$tx''(t) - tx'(t) - x(t) = 0 , \\ x(0)=0, \\ x'(0)=1$$
We can take $$x(t) = \sum_{n=0}^{\infty}a_nt^n$$
Furthermore we have $$x'(t) = \sum_{n=0}^{\infty}na_nt^{n-1} \\ x''(t) = \sum_{n=0}^{\infty}n(n-1)a_nt^{n-2}$$
Then I substituted it to $tx''(t) - tx'(t) - x(t) = 0$ and I received $$\sum_{n=2}^{\infty} n(n-1)a_nt^{n-2} - \sum_{n=1}^{\infty}n a_nt^{n} - \sum_{n=0}^{\infty}a_nt^{n} = 0$$
What can I do next? Thanks in advance.
Comment: I would recommend writing $x(t) = a_0 + a_1t + a_2t^2+a_3t^3+a_4t^4+\cdots$ to start with. Do the differentiations, make the substitutions, apply the initial conditions and then simplify. Most questions only ask for the first few terms (the $k$-jet) of $x$ anyway. If you're asked for the whole thing, then starting with finite terms will help you see any patterns.
Comment: Hints: Get all the powers in the summations the same, Get all of the ranges of the summations the same, Write the general terms for the constants, Solve for those terms
Comment: You will discover the recurrence relation between the coefficients.
Comment: It looks like you have a typo in the first series in your last equation; it should be $t^{n-1}$ and not $t^{n-2}$?
Comment: You should get a series that is the expansion of $x(t) = t~e^t$.
Answer: If
$$
x(t)=\sum_{n=0}^\infty a_nt^n
$$
is a solution of the DE
$$
tx''-tx'-x=0,
$$
then we have
$$
0=t\sum_{n=2}^\infty n(n-1)a_nt^{n-2}-t\sum_{n=1}^\infty na_nt^{n-1}-\sum_{n=0}^\infty a_nt^n=\sum_{n=0}^\infty(n+1)\left[na_{n+1}-a_n\right]t^n.
$$
It follows that
$$
na_{n+1}-a_n=0 \quad \forall n \ge 0
$$
with
$$
a_0=x(0)=0,\ a_1=x'(0)=1.
$$
Thus for every $n \ge 2$ we have
$$
a_n=\frac{1}{n-1}\ldots\frac{1}{2-1}a_{2-1}=\frac{1}{(n-1)!}.
$$
We then deduce that
$$
x(t)=t+\sum_{n=2}^\infty\frac{1}{(n-1)!}t^n=t+t\sum_{n=1}^\infty\frac{1}{n!}t^n=t+t(e^t-1)=te^t.
$$


Generate JSON schema

Question: Im trying a setup a Microsoft flow. In short, I need to take JSON data retrieved from a device, and parse it so that i could reference it in the Flows below. In order to parse, i need to provide the JSON Schema to Flow. Microsoft Flow has an option to generate it from a sample payload (the results returned from the API call), but it's not generating it correctly. I'm hoping someone can help me. I need the correct JSON Schema.
The data returned from the API:

[
  null,
  [
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]
]

Scheme generated in Flow from the above sample payload:

{
    "type": "array",
    "items": {}
}

I then tried to generate the Schema from just the data. That seemed to work, but when the Flow runs, I get a Json validation error.
Tried generating from just the data like this:

{
      "user_id": 2003,
      "user_label": "Test1"
    }

This generated the scheme like this:

{
    "type": "object",
    "properties": {
        "user_id": {
            "type": "number"
        },
        "user_label": {
            "type": "string"
        }
    }
}
Comment: the problem seems to be with your null at the root of the return. Does ur schema accepts null?
Answer: So you have 2 things going on, the nested object array, and the null.
You'll need another Parse JSON after the first Parse JSON.  And you'll want to filter out the null before the second Parse JSON.
It took me a while to figure out, but I hope this helps.
Start by adding the Parse JSON step to whatever step is outputting the JSON.

Now, filter the array, make sure you use the 'Expression' when comparing with null.

Add the second Parse JSON, you'll notice that you won't have the option to select the output "Item" of the Filter array step, so select 'Parse JSON' - Item  for now (we will change this to use the output of the Filter JSON step in a moment)

The step should automatically change to an 'Apply to each'.  In the Parse JSON 2, generate the schema with
[
    {
      "user_id": 2003,
      "user_label": "Test1"
    },
    {
      "user_id": 2004,
      "user_label": "Test2"
    }
  ]

Then, modify the 'Select an output from previous steps field' and change it (from the Body of the Parse JSON step) to the Body of the Filter Array step

Finally, add an action after Parse JSON 2 and select one of the fields in Parse JSON 2, this will automatically change that step to a nested Apply to each

You should end up with something like this:

Generate JSON schema


How to run SQL in shell script

Question: How do you run a SQL command in a shell script while setting a variable?  I had tried this method and it isn't executing the command, it is thinking the command is just a string.
#!/bin/ksh
variable1=`sqlplus -s username/pw@oracle_instance <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
select count(*) from table;
EXIT;
EOF`
if [ -z "$variable1" ]; then
  echo "No rows returned from database"
  exit 0
else
  echo $variable1
fi

Answer: #!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

Comment: @Aneri, not sure if you've used SO before, but writing a question and adding an answer that doesn't exist in SO is adding value to SO. It is actually a feature.
Comment: Self-answering and then self-commenting?
Answer: You can use a heredoc. e.g. from a prompt:
$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

so sqlplus will consume everything up to the EOF marker as stdin.
Comment: I was able to get something like this to execute, but it was having difficulty with setting the result to a variable.
Answer: Maybe it's too late for answering but, there's a working code:
sqlplus -s "/ as sysdba" << EOF
    SET HEADING OFF
    SET FEEDBACK OFF
    SET LINESIZE 3800
    SET TRIMSPOOL ON
    SET TERMOUT OFF
    SET SPACE 0
    SET PAGESIZE 0
    select (select instance_name from v\$instance) as DB_NAME,
           file_name
      from dba_data_files
     order by 2;

Comment: Shouldn't this has EOF at the end (to avoid a warning)?
Answer: sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;

connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;

truncate table tmp;

exit;
EOF

Answer: Code
PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"

OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
           select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";

Explanation:
PL_CONNECT_STRING carry database username, password and it service name
sqlplus is used to connect the Database with PL_CONNECT_STRING details
END-OF-SQL tag contain the query which you want to execute
echo is used to print the output of the query
NOTE: You can give multiple Query inside the END-OF-SQL tag, so its useful for batch execution as well

How to run SQL in shell script


Poweriso returns unrecognized parameter

Question: Using either:
poweriso extract filename.iso -od dirname
poweriso extract "filename.iso" -od "dirname"

returns invariably:
PowerISO   Copyright(C) 2004-2008 PowerISO Computing, Inc
            Type poweriso -? for help

Unrecognized parameter: dirname

I've found another question about this but the only answer only states to put quotation marks around filename and dirname, which has as previously stated not worked. Does anyone have any idea what could be wrong?
Comment: Silly question, but is `dirname` what you're actually typing?  Or are you specifying a folder as in the instructions: http://www.poweriso.com/tutorials/command-line-argus.htm
Comment: I am following instructions, dirname and filename are just to be generical.
Answer: Oh god, sorry to you all. It was me overlooking a really small detail. Thanks to ThatGuy who got me looking again at the instructions page and noticing this.
Problem was I was using
poweriso extract filename.iso -od dirname

HOWEVER, I should be using
poweriso extract filename.iso / -od dirname

Comment: I was just about to post that.  LOL!  The `/ -od` is a requirement, yes.

Poweriso returns unrecognized parameter


Unable to fetch records in a sharedCloudDatabase custom Zone using CloudKit

Question: I am trying to fetch CloudKit records from a custom Zone in a sharedDatabase.
The zone has been created correctly during the share process. So I assume that the zone is correctly a shared custom zone (it is indeed in my CloudKit user dashboard, appearing under the sharedDatabase of the default container).
Even with this simple piece of code to retrieve records:
func loadRecords() {
    let database = CKContainer.default().sharedCloudDatabase
    let query = CKQuery(recordType: "Items", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
    let operation = CKQueryOperation(query: query)
    let zone = CKRecordZone(zoneName: "MyCustomZone")
    var fetchedRecords: [CKRecord] = []

    database.perform(query, inZoneWith: zone.zoneID) { (records, error) in
        if let error = error {
            print(error)
        }
        else if let records = records, let firstRecord = records.first {
            print(firstRecord)
        }
    }
}

I keep receiving this error: (sorry was missing in previous post!)
<CKError 0x280950840: "Invalid Arguments" (12/1009); "Only shared zones can be accessed in the shared DB">

Any idea about what I am missing? Thank you!
Comment: Which error? (missing)
Comment: sorry about that, skipped...now updated.
Comment: Maybe [this post](https://stackoverflow.com/a/48192600/1987726) solves your problem?
Comment: Unfortunately no. I am indeed saving the record in the private user DB before the sharing. So the record is saved in private DB, I then share it and the sharing cause the "window" to be generated in the shareDB of the user accepting the share. This is indeed what confuses me...the zone in the shareDB should be indeed shared!
Answer: Right, I finally figured it out. Thanks to this additional post here on StackOverflow: CloudKit Sharing
You indeed have to fetch your custom zone. But it is not enough to give it a name such as "MyCustomZone" because in your shared DB, it becomes MyCustomZone: _acBxxxyyyzzz. A suffix added by CloudKit.
If you don't fetch all your shared zones, you never have the right custom zone from which you need to pickup the record.
Comment: Can you please post the code here that you are referring to? (The fetching shared custom zones etc). Would really appreciate it. Thank you!


Getting Error when i start TorToolKit Bot telegram on vps

Question: (venv) root@ip-172-31-40-27:/home/ubuntu/TorToolkit-Telegram# ./start.sh
[2021-07-06 14:12:16 +0000] [332160] [INFO] Starting gunicorn 20.0.4
[2021-07-06 14:12:16 +0000] [332160] [INFO] Listening at: http://0.0.0.0:80 (332160)
[2021-07-06 14:12:16 +0000] [332160] [INFO] Using worker: aiohttp.GunicornWebWorker
[2021-07-06 14:12:16 +0000] [332165] [INFO] Booting worker with pid: 332165
2021-07-06 14:12:16,405 INFO MainThread root Database created
2021-07-06 14:12:16,406 INFO MainThread root Database created
2021-07-06 14:12:16,506 INFO MainThread telethon.crypto.aes cryptg detected, it will be used for encryption
2021-07-06 14:12:18,860 INFO MainThread pyrogram.crypto.aes Using TgCrypto
2021-07-06 14:12:23,218 INFO MainThread root Telethon Client created.
Pyrogram v1.1.13, Copyright (C) 2017-2021 Dan https://github.com/delivrance
Licensed under the terms of the GNU Lesser General Public License v3 or later (LGPLv3+)
2021-07-06 14:12:28,510 INFO MainThread root Pryogram Client created.
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/ubuntu/TorToolkit-Telegram/tortoolkit/__main__.py", line 55, in <module>
    ttkbot.loop.run_until_complete(start_server_async(get_val("SERVPORT")))
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/ubuntu/TorToolkit-Telegram/tortoolkit/core/wserver.py", line 334, in start_server_async
    await web.TCPSite(runner,"0.0.0.0",port).start()
  File "/home/ubuntu/venv/lib/python3.8/site-packages/aiohttp/web_runner.py", line 121, in start
    self._server = await loop.create_server(
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1463, in create_server
    raise OSError(err.errno, 'error while attempting '
OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 80): address already in use
2021-07-06 14:12:29,359 ERROR MainThread asyncio Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f62991bcbe0>
2021-07-06 14:12:29,359 ERROR MainThread asyncio Exception in default exception handler
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1733, in call_exception_handler
    self.default_exception_handler(context)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1707, in default_exception_handler
    logger.error('\n'.join(log_lines), exc_info=exc_info)
  File "/usr/lib/python3.8/logging/__init__.py", line 1475, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/usr/lib/python3.8/logging/__init__.py", line 1589, in _log
    self.handle(record)
  File "/usr/lib/python3.8/logging/__init__.py", line 1599, in handle
    self.callHandlers(record)
  File "/usr/lib/python3.8/logging/__init__.py", line 1661, in callHandlers
    hdlr.handle(record)
  File "/usr/lib/python3.8/logging/__init__.py", line 954, in handle
    self.emit(record)
  File "/usr/lib/python3.8/logging/__init__.py", line 1186, in emit
    self.stream = self._open()
  File "/usr/lib/python3.8/logging/__init__.py", line 1176, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
NameError: name 'open' is not defined
Exception ignored in: <function ClientSession.__del__ at 0x7f629fcb8430>
Traceback (most recent call last):
  File "/home/ubuntu/venv/lib/python3.8/site-packages/aiohttp/client.py", line 337, in __del__
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1740, in call_exception_handler
  File "/usr/lib/python3.8/logging/__init__.py", line 1475, in error
  File "/usr/lib/python3.8/logging/__init__.py", line 1589, in _log
  File "/usr/lib/python3.8/logging/__init__.py", line 1599, in handle
  File "/usr/lib/python3.8/logging/__init__.py", line 1661, in callHandlers
  File "/usr/lib/python3.8/logging/__init__.py", line 954, in handle
  File "/usr/lib/python3.8/logging/__init__.py", line 1186, in emit
  File "/usr/lib/python3.8/logging/__init__.py", line 1176, in _open
NameError: name 'open' is not defined`enter code here`enter code here`
(venv) root@ip-172-31-40-27:/home/ubuntu/TorToolkit-Telegram#

Answer: Not knowing any of the products but tortoolkit is trying to listen to port 80:
File "/home/ubuntu/TorToolkit-Telegram/tortoolkit/core/wserver.py", line 334, in start_server_async     await web.TCPSite(runner,"0.0.0.0",port).start()
but the port on the machine is already used:
OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 80): address already in use
I would recommend to find how that "port" variable is controlled and use a less used port. For local development it's best practice to use 8080 to 9000


Is there going to be a friendly Unity settings window?

Question: Currently, as far as I am aware, you need to use the CompizConfig Settings Manager application to play with the Unity configuration settings.
While this makes sense, from a technical point of view, it requires the user to know about the settings manager, install it, and then find the Unity options within it. Not very user friendly.
Is there a user friendly configuration application planned that will offer all the configuration options in an easy-to-use for new people fashion?
Answer: Obviously, application like this will be developed some day (unless Canonical dumps Unity).
For now, it's not coming. 11.04 is not helping with this at all. I couldn't find anything related to this from ubuntu Brainstorm. There doesn't seem to be any bugs filed, so most probably it will not be be fixed anytime soon.
Comment: Mind if I try to correct some English mistake?
Comment: @Oxwivi: I don't mind at all, feel free to (always a good idea).
Comment: I submitted an edit, if it's accepted, have a look at the changes.


How can I rank my games by number of achievements remaining?

Question: I would like to try and get some "perfect" games on Steam - games for which I have collected all the achievements.
Obviously, some games have much bigger lists of achievements than others and some achievements are much harder than others. Can't do much about finding out the latter without playing, but I thought it would be useful/interesting if I could sort and rank my game collection by the total number of achievements or, better yet, total achievements remaining.
I can't see any way to do this in the Steam UI. Is there one, or are there any third party tools that can do this?
Comment: The answers there might answer this question, but it's not a duplicate *question*.
Answer: You can try using AStats, it generates a list of games with achievements for your Steam account that you can sort by multiple criteria such as "number of achievements remaining" as you mention, and also by "hours to 100%" (based on how long it took other members to complete the game), and others.
It's a pretty handy website for Steam game completionists.
Answer: I made a thing that does this. Enter your vanity URL and sort by percent.
Answer: You can use a third party sites such as MetaGamerScore.com.  These type of sites periodically scan your achievements, giving you a good overview of what achievements you have unlocked (or yet to unlock).
There is also a site named TrueSteamAchievements that offers achievement tracking (truesteamachievements.com).
I'm not sure about MetaGamerScore, but with TrueSteamAchievements the site shows you the percentage of registered users that have completed the achievement.  This will give you a guide to how rare an achievement actually is.  Although not always true due to other factors, it allows you to figure out the "harder" achievements to unlock.  There are also tools for filtering down achievements to, say, achievements that are acquired in single player, online etc.
When registered to TrueSteamAchievements, you can add achievements to your todo list, and view solutions to each achievement (good to check criteria, but also to see if someone has found a glitch or shortcut to cut down the hours you spend on one achievement).  There are a whole bunch of other functionality in the site too (and you can link it to your Xbox and PlayStation, if you own such a console).
Comment: _... glitch or shortcut to cut down the hours you spend on one achievement..._

If you're into that sort of thing.


Simplest way to carbonate a kitchen faucet

Question: I'm hoping my plan to carbonate my kitchen drinking faucet is as easy as it seems, but would like some confirmation I'm not missing something:
In short, I want to hook my main water line up to a consumption-grade CO2 tank, the same way I would hook up a Keg. I have a separate drinking faucet connected to my main water line, and I'd like to add a CO2 tank, connected to a regulator, connected to an air line, connected to a keg coupler. The Keg coupler would also connect to my main water line, and separately connect through to my faucet. For a diagram of what I mean, check out: www.kegworks.com/blog/how-draft-systems-work/ [No affiliation].
I'm not concerned with chilling or filtering at this point, but in theory would I be able to add in a water filter that feeds into my main water line into the keg coupler down the road? Or would that create problems with making the filter system 'under reverse pressure' from the CO2 tank?
I'm also trying to avoid needing to get a separate water tank to keep under my kitchen sink as that space is limited and I'd like to keep refill trips to a minimum. If my current plan doesn't work, having a tank of filtered water that I periodically have to refill and put under my sink might be the next best thing.
I guess what I need to worry about is whether my main water line is pressurized enough to prevent the CO2 tank from simply emptying out into my water supply?Alternatively, would the pressure from the main water line 'overpower' the CO2 tank such that I would get minimal carbonation in the end product?
Per the comments, if I would need to keep the CO2 tank < the pressure of the water line (let's assume 50-75 PSI), would that sufficiently carbonate the water? If not, would it be possible to add some sort of one-way valve from the main water line that feeds into some sort of water collection tank, that then connects to the carbonation system, so that it could 'withstand' higher pressure?
Comment: CO2 is used to with beer to create pressure for the beer to flow, however nitrogen is more frequently used in commercial grade systems.  Soda fountains use [a motor driven carbonator](https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQsCzyBIy-F6NkNrp4Xb2vyLHqeDK_6ZQXIHUKrm5nTn0mQE9jQ) to desolve to mix the CO2 into the water. Study up on commercial soda fountains to learn more.
Comment: Residential water supplies are commonly 50-75 PSI. I'm guessing that your CO2 tank would be considerably higher. You'd have to keep the regulator below the water pressure level. Would that carbonate it adequately?
Comment: @isherwood Okay that makes sense, and whether it would carbonate adequately is the question of the day, I suppose. Further details edited into the question based on this.
Comment: @tyson Ahh, I guess that explains why my 'solution' seemed so much simpler, because the motorized solution would force the the CO2 to pass through more surface area of the water, I think.
Comment: Found one on [Amazon](https://www.amazon.com/dp/B00S71IXSU/ref=cm_sw_r_cp_api_i_J.pqCbV645FH7)
Comment: @Tyson Thanks; yes I had seen those but was hoping for residential use the motor driver would have been unnecessary; sink location wouldn't be ideal for me to hook up anything to a power outlet. Seems I was overly optimistic on this one.
Answer: I don't believe this is going to work very well with the set up you have described.  Carbonation of water requires that the CO2 dissolve into the water.  Assuming you get the pressure all worked out, the surface area between the gas and the water is going to be tiny.  If it worked at all, it would dissolve into the water line itself.  My guess is only a few ounces would be carbonated at most when you open the tap.
Another thing to consider is that the colder the water, the more CO2 it can dissolve.  This is why a hot beer is more likely to foam out and create too much head than a cold beer.  Here's a graph of that relationship:
source
I think you might be able to manage this with a tank, though.  Basically it would be a keg but you would need to have a water supply as well as CO2 for the water to refill through.  I'm not sure there's something off the shelf for this but reverse-osmosis systems have a tank so there might be a way to cobble together parts for to make it happen.  I'm not exactly sure how you would make it automatically refill.
You'd want to have some sort of check valve on the water line to prevent it from flowing back into the water supply.  The CO2 tank should have some sort of pressure control valve just like it would on a keg system.
This wikipedia page has some good info on this.  If 70 PSI is the right number for the water line, you would probably need to release the pressure from the CO2 in order to refill the tank.  The amount of carbonation could be tweaked by the pressure from the CO2 tank.  The higher the pressure, the more CO2 will dissolve.
One other consideration is that it the pressure is much higher than typical water pressure, the faucet might not be designed for that and/or it could shoot out too fast.
Comment: I suppose I don't really need the tank to auto-fill. If the tank is reasonably large, even say 5 liters, it wouldn't be too troublesome to reach under the sink once or twice a week, and flip some valves to allow the tank to refill until it becomes usable again. For your chart there, do you know a way to convert solubility of gas  in g/KG into a PSI metric? I'd like around 15 PSI in the final product I guess, and not sure if that means chilling the tank would be needed for the extra 'oomph'.
Comment: @Grade'Eh'Bacon I'm not sure I understand the question.  The g of gas per kg of water is telling you the saturation point of the CO2 in water.  It's not the best graph because I doesn't say at what pressure.  Higher the pressure, the more CO2 will dissolve.  The pressure I think you are referring to is what the effervescing CO2 would produce under normal atmospheric pressure?  I'm afraid that's beyond my skills.
Comment: Fair point, I was asking for what the local pressure / effervescence of the water would be immediately after pouring into atmospheric pressure. Your edit is helpful as well, thanks.
Comment: One last thought is that if I do need a separate tank to hold the water in some intermediate stage, I would suffer more for not having it chilled - because if the water could come straight from the main water line, it would come in at least slightly cooler than room temperature.
Comment: @Grade'Eh'Bacon I'm sure there's a way to calculate that but chemistry was never my thing really.  The wikipedia page (added the link) has references that might help in figuring that out.  If you can get it working, I think you could adjust to your liking, though.
Comment: Right.  You sure you don't just want to get a home carbonation machine?  Sounds like fun but could be a lot of work.  You also don't want to have this tear open at main water pressure or higher.  Might be tough to explain to the insurance company.
Comment: "I'm not exactly sure how you would make it automatically refill". I think one could use two tanks and some clever plumbing to alternate CO2 pressure between the tanks. Then CO2 pressure wouldn't have to be released. I realize this is an old question and OP has moved on (https://diy.stackexchange.com/questions/155142/simplest-way-to-carbonate-a-kitchen-faucet?rq=1#comment333703_189356), but it's fun to over-engineer things in my mind :)
Answer: Creating this second answer since the first one was deleted, and not restored even after editing.  Need to raise serious safety or health concerns
***** Serious Safety or Health Concerns ********
The original setup to provide carbonated water to  "kitchen drinking faucet" and to "my main water line" has potential serious safety or health concerns.  If the kitchen drinking faucet is not all stainless steel with the plastic hose to the faucet connected with stainless steel coupling, then there is a possibility of leaching copper and lead or reacting with copper and producing a poisonous compound.  Many of the kitchen and bar faucets are provided with copper pipes and brass coupling to connect to their water source.  Also many of the "beer faucets"  are chrome over brass or brass.  The chrome will be eaten away by the carbonated water, exposing the brass.  Connecting carbonated water to the main water line, which in the majority of houses is copper pipe, has the same issue. Copper pipes does have an allowance for lead as part of its composition.  All lines and fitting within and on the outlet side of the kegerator to the faucet should be stainless or plastic.
Comment: Hopefully it gives you comfort to know I bought a sodastream instead. I was a bit out of my element on this one!


What type of wood filler should I use?

Question: I'm starting a project to build my own solid body guitar.
I received the body and its made from ash. It needs to be filled (the grain is very porous).
I hear that I need wood filler for this.
The plan is to stain the guitar with a walnut stain and then finish with an oil finish (no lacquering and I want the grain to show through).
So my questions are, does it matter what wood filler I get? and all wood filler can be stained, right?
I've heard that a darker wood filler will accentuate the grain and give a greater contrast between the areas of the grain. However, I also had some advice that I should fill the wood in a similar colour and stain over the top.
I'm quite confused and don't want to get it wrong. I would like the grain to show up as much as possible, but don't want to ruin the staining by putting the wrong filler on it.
Comment: By "filler", do you mean a sealer?  Wood filler (as I understand it) is a putty-like substance that's used for filling e.g. nail holes or other damage, whereas a sealer helps stains to stain more evenly by preventing it from soaking in as much.  Also, if the acoustic properties of the finish are important, http://music.stackexchange.com/ might be a better place to ask this (at least, they have appropriate tags: guitar and construction).
Comment: There are wood fillers that are specifically made for opened grain wood, as opposed to hardening fillers made for structural purposes. Check out http://www.constantines.com/
Comment: Ah, you see this is what I need to know. How can you tell the difference? I'll be off to B&Q later... Is this what I need? http://www.diy.com/nav/decor/decorating-sundries/fillers-putty/wood_fillers/Ronseal-High-Performance-Wood-Filler-Natural-275g-9254231 or something like this? http://www.diy.com/nav/decor/decorating-sundries/fillers-putty/wood_fillers/Colron-Wood-Filler-125ml-9253258
Comment: I'm not too worried about the "acoustic properties" as its going to be an electric guitar and the pickups and amp will be doing most of the work there. :) By filler, I'm not really sure. Basically where there is grain there are loads of pores, so I want to get it smooth before staining and finishing. But I don't want to fill it with something that a) can't be stained and b) will damage the wood.
Answer: Wood fillers for filling grain are very different from those used for structural repairs.  Grain fillers are diluted and rubbed into the wood grain.  See the attached listing from Constantines, one of the leading woodworking suppliers in the U.S.:
http://www.constantines.com/pastewoodfiller.aspx
They are also a source of components and books on building guitars.
I do not know of a non-U.S. source, but they may ship internationally and their info may help evaluate local resources you find.
Comment: Is Rustin's a reasonable alternative to constantines? Apparently you mix with white spirit to thin it. Can I stain over it? Or should I mix the stain with the grain filler?
Comment: Not familiar with that product. Many fillers have a plasticizer in them which prevents staining. When something will accept stain, it almost always says so.

What type of wood filler should I use?


Ubuntu 20.04 goes blank after unlocking

Question: So every time i unlock my laptop this happens :
https://www.reddit.com/r/linux4noobs/comments/gf8r4n/ubuntu_2004_goes_blank_after_unlocking/
Comment: To me it seems like a hardware issue. Is this only happening with your Ubuntu installation (in case it's a dual boot)?
Comment: On windows is normal (dual boot)
Answer: It was extension problem.
This extension caused problem: https://extensions.gnome.org/extension/1414/unblank/

Ubuntu 20.04 goes blank after unlocking


Is there a benefit to stacks of allies in Kairobotica?

Question: In Kairobotica, you gain Power Allies by researching items, which are consumed in the process. Out of curiosity, I researched one I already had and now I have a stack of two, but I haven't noticed any mechanical effects. As the items have other uses, I would very much like to know if this is beneficial or not.
Does having more than one of a given Ally have effects in battle, or is it just a backup in case you lose them?
Answer: If you lose a battle and you're with a power ally, you will lose it, and that's pretty much why we can stack them.


AWS EC2 & EBS for personal development server

Question: I'm AWS free-tier user and planning to Use AWS EC2 & EBS as a personal web development server. I will be using this machine 100 hours max in a month. Will be stopping and starting the EC2 instance. What will be the best configuration for EC2/EBS for running development ENV for good performance? Would I be able changes EC2 instance after setup?
Development Environment

Ubuntu
Ruby
Python
Nodejs
Docker
Kubernetes
Vscode
database server
Remote Desktop Client -> VNC

EC2 Instance

EBS Volume

General Purpose SSD (gp2)
Provisioned IOPS SSD (io1)
Throughput Optimized HDD (st1)
Cold HDD (sc1)
Answer: Start with a t3.micro and GP2. Then once you're using it you can stop the instance and change instance type as demand requires.


$\{f_n\}$ be a sequence of functions which are continuous over $[0, 1]$ and continuously differentiable in $(0, 1)$

Question: Let $\{f_n\}$ be a sequence of functions which are continuous over $[0, 1]$ and continuously differentiable in $(0, 1)$. Assume that $|f_n(x)| \leq 1$ and that $|f_n'(x)| \leq 1$ for all $x \in(0, 1)$ and for each positive integer $n$. Pick out the true statements.
(a) $f_n$ is uniformly continuous for each $n$.
(b) $\{f_n\}$ is a convergent sequence in $C[0, 1]$.
(c) $\{f_n\}$ contains a subsequence which converges in $C[0, 1]$.

I am totally stuck.  How should I solve this? Thanks for your help.
Comment: $[0,1]$ is compact. You might know a theorem on continuous functions on a compact space? Also, try a simple alternating sequence of constant functions to kill (b), and look up Arzela-Ascoli to see if it applies to c).
Comment: I think the title of the post is entirely too long for being so nondescript, but I could not come up with a better title.
Comment: Do you know any theorems about uniform continuity?  Or about convergent subsequences?  If you know any, you might want to try them and say why they help or don't help.
Comment: A [related problem](http://math.stackexchange.com/questions/219377/show-that-f-n-is-equicontinuous-given-uniform-convergence/219402#219402).
Answer: Hints
(a) $[0,1]$ is compact. Probably you know a theorem like this:

Let $(X,d)$ a compact metric space and $f: X \to \mathbb{R}$ continuous. Then...

(b) What about $f_n(x) := (-1)^n$?
(c) Apply Arzelà-Ascoli. (Use $|f_n(x)| \leq 1$, $|f_n'(x)| \leq 1$. Think about mean-value theorem to prove one of the conditions.)
Comment: But I can not understand how to prove that ${f_n}$ is closed?
Comment: @sani What do you mean by closedness of a function?


Having Issue with file name appended with date -shell scripting

Question: I tried to append the current day and time to the existing file name in shell scripting and I found my command is not working as expected.
For example, if my file name is f1.log and I nees to append it along with current time. This appended version must be used for further processing of the file.
I tried with the following script but getting an error
    now=$(date +"%m-%d-%Y/%T")
    echo hi >>time.log
    mv "time.log" "time.$now.log" (error here : file or directory not found)
    echo hello >> time.log$now   (have to continue processing with new file)

Answer: You cannot have a / character in a filename.  The mv command is looking for a directory named with the minute, day, and year of the output of date and trying to create a file named by the time.  Just change your format to not include / in the filename.
Comment: oops! yeah I failed to realize that. Thanks !
Answer: The problem is with shell's interpertation of / in your date +"%m-%d-%Y/%T".
Change it to a - instead (or something else, as long as it's not / or another meta character that will make the files difficult to work with in the future)
Comment: `/` is not a meta-character to the shell.  The problem is that it is the delimiter between directory names in the path.


When we call Abort() method in Threading,and For conditions? Is there any validations to check before Abort the thread?

Question: I'm getting ThreadAbortException when call Abort() method, and I referred to solve this in Stack Overflow that they said to use Thread.ResetAbort() method before ending the thread, but It's not clear to me.
Please suggest me where can I use ResetAbort method. I'm getting that exception in marked line when call the Abort() method.
while (true)
{
    Group g = null;
    if (countGroupsList != null)
    {
        lock (countGroupsList.SyncRoot) // Exception here
        {
            if (groupsCounter < countGroupsList.Count)
            {
                g = (Group)countGroupsList[groupsCounter];
                groupsCounter++;
            }
         }
    }

Comment: `Thread.Abort()` is a bad idea and generally means you have other issues with your solution. Why do you need to exit the thread this way?
Comment: what is the way of stop the thread?
Answer: Thread.Abort is a rude way to kill a thread. But if you really want to do so you can just ignore the exception. It's the way the thread says: Ouch, I'm dying.
You also can catch this exception and use the Thread.Abort method in your catch block. But that will prevent the thread to be killed.


iOS navigation controller without navigation bar

Question: This is how I launched by main controller in my iOS app.
UIViewController *rootController = [[RootViewController alloc] init];
navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window setRootViewController:navigationController];
[self.window makeKeyAndVisible];
return YES;

With this I am getting a blank bar at the top.

I want to use a navigation controller to control the flow of screens that users are able to reach by pressing back but I don't want a navigation bar. How can I change my code to get what I want?
Answer: You can use this code right after you declare navigationController = ... in the code sample you provided:
[navigationController setNavigationBarHidden:true];

And then whenever you need to go "back," your app would run this code from within the current view controller:
[self.navigationController popViewControllerAnimated:true];