text:
Q: c# format data saving to an excel file I am working with the Kinect and trying to save tracking coordinates into an excel file. I have managed to create the excel file and save the data, but i need to format the way in which the data is saved in order to create graphs. How do I do it?
The data is currently displayed in one cell as:
23-04-13 10:24
Head: X:411 Y:255
ShoulderCenter: X:417 Y:317
ShoulderLeft: X:360 Y:353
ShoulderRight: X:474 Y:357
ElbowLeft: X:341 Y:412
ElbowRight: X:513 Y:426
WristLeft: X:321 Y:451
WristRight: X:513 Y:471
HandLeft: X:312 Y:454
HandRight: X:502 Y:471
Spine: X:422 Y:389
HipCenter: X:422 Y:403
HipLeft: X:397 Y:429
HipRight: X:450 Y:434
KneeLeft: X:305 Y:484
KneeRight: X:316 Y:425
AnkleLeft: X:205 Y:547
AnkleRight: X:426 Y:437
FootLeft: X:178 Y:559
FootRight: X:394 Y:441
I need to have the coordinate values in separate cells.
My code for saving to excel.
}
        TextBox1.Text = Head;
        TextBox2.Text = ShoulderCenter;
        TextBox3.Text = ShoulderLeft;
        TextBox4.Text = ShoulderRight;
        TextBox5.Text = ElbowLeft;
        TextBox6.Text = ElbowRight;
        TextBox7.Text = WristLeft;
        TextBox8.Text = WristRight;
        TextBox9.Text = HandLeft;
        TextBox10.Text = HandRight;
        TextBox11.Text = Spine;
        TextBox12.Text = HipCenter;
        TextBox13.Text = HipLeft;
        TextBox14.Text = HipRight;
        TextBox15.Text = KneeLeft;
        TextBox16.Text = KneeRight;
        TextBox17.Text = AnkleLeft;
        TextBox18.Text = AnkleRight;
        TextBox19.Text = FootLeft;
        TextBox20.Text = FootRight;

        {
            StreamWriter sw = File.AppendText("Data.xls");
            sw.WriteLine(DateTime.Now);
            sw.WriteLine(TextBox1.Text);
            sw.WriteLine(TextBox2.Text);
            sw.WriteLine(TextBox3.Text);
            sw.WriteLine(TextBox4.Text);
            sw.WriteLine(TextBox5.Text);
            sw.WriteLine(TextBox6.Text);
            sw.WriteLine(TextBox7.Text);
            sw.WriteLine(TextBox8.Text);
            sw.WriteLine(TextBox9.Text);
            sw.WriteLine(TextBox10.Text);
            sw.WriteLine(TextBox11.Text);
            sw.WriteLine(TextBox12.Text);
            sw.WriteLine(TextBox13.Text);
            sw.WriteLine(TextBox14.Text);
            sw.WriteLine(TextBox15.Text);
            sw.WriteLine(TextBox16.Text);
            sw.WriteLine(TextBox17.Text);
            sw.WriteLine(TextBox18.Text);
            sw.WriteLine(TextBox19.Text);
            sw.WriteLine(TextBox20.Text);

            sw.Close();

    }

A: First of all, put your Values in a Array (IEnumerable, List, or what else), so you can go through it with a Loop.
using Excel = Microsoft.Office.Interop.Excel;

And using:
public void doExcel()
{

    Excel.Application myExcelApplication = new Excel.Application();
    myExcelApplication.Visible = true;
    myExcelApplication.ScreenUpdating = true;
    Excel.Workbook myExcelWorkbook = (Excel.Workbook) myExcelApplication.Workbooks.Add(System.Reflection.Missing.Value));
    Excel.Worksheet myExcelWorkSheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;

    for (int i = 0; i < myList.Count; i++)
    {
        myExcelWorkSheet.Cells[3, i] = String.Format("{0}", myList[i]);
    }
    myExcelWorkbook.Close(true, "C:\\data.xls", System.Reflection.Missing.Value);
}


text:
Q: Way of streaming data from a NodeJS server to .NET CORE? Excuse me, for I am new to .NET and Visual studio:
I want to stream data from my NodeJS server (Visual Studio Code), to my .NET Core app (Visual Studio).
I have posted on here before and have gotten it taken down due to there being answers already posted, but I was researching around a lot, and couldn't find any.
So the way I currently have it working is setting my NodeJS to write to a file, and then my .NET reads from the file at the same time. As you might be able to tell, this is far from ideal, as they conflict with each other and give errors a lot of the time, meaning the stream is nowhere close to perfect.
Then I found these things called pipes, is there a way to create a "pipe" server on .NET or NodeJS and connect to it in the other framework to allow data to be easily passed between the two?
If you need any more clarification just let me know, thanks.

A: You can create localhost RestAPI
import express from 'express';
const app = express();
app.post('/', (req, res) => {
  return res.send('Received a POST HTTP method');
});
app.listen(8080) //port

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;

namespace RestAPI
{
    public class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;

        public WebServer(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
            {
                throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
            }

            // URI prefixes are required eg: "http://localhost:8080/test/"
            if (prefixes == null || prefixes.Count == 0)
            {
                throw new ArgumentException("URI prefixes are required");
            }

            if (method == null)
            {
                throw new ArgumentException("responder method required");
            }

            foreach (var s in prefixes)
            {
                _listener.Prefixes.Add(s);
            }

            _responderMethod = method;

            _listener.Start();

        }

        public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
           : this(prefixes, method)
        {
        }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem(c =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                if (ctx == null)
                                {
                                    return;
                                }

                                var rstr = _responderMethod(ctx.Request);
                                var buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);

                                string cmd = ctx.Request.RawUrl;
                                if (cmd.Contains("cmd="))
                                {
                                    cmd = cmd.Split('=')[1];
                                    cmd = HttpUtility.UrlDecode(cmd);
                                    Debug.WriteLine($"Request : {cmd}");
                                    Program.MakeCMD(cmd);
                                }
                            }
                            catch
                            {
                                // ignored
                            }
                            finally
                            {
                                // always close the stream
                                if (ctx != null)
                                {
                                    ctx.Response.OutputStream.Close();
                                }
                            }
                        }, _listener.GetContext());
                    }
                }
                catch (Exception ex)
                {
                    // ignored
                }
            });
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }

    public static class Program
    {
        public static string prefix = "http://localhost:8081";
        public static string SendResponse(HttpListenerRequest request)
        {
            string txt = ""; //You can return some text/json
            return txt;
        }

        public static void Main(string[] args)
        {
            try
            {
                var ws = new WebServer(SendResponse, prefix);
                ws.Run();
            }
            catch
            {
                ConsoleLog.WriteLine("It looks like you are not running in administrator mode. Administrator Mode is required to start the web server!");
            }

        }
    }
}

I didn't found easier c# example :)
Then use XMLHttpRequest in node js and HttpClient in c#

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the cost of leveling the triangular plot.Find the area using Herons formula A Triangular Plot has sides $600$m .$640$m and $700$m.How much would the leveling cost if $1m^2=50$Rs. Solve the Problem using Heron's Formula.

A: Not exactly a cauchy integral problem, but I'll bite.
$s=\frac{a+b+c}{2}=\frac{600+640+700}{2}=970$
$A=\sqrt{s(s-a)(s-b)(s-c)}=\sqrt{970(970-600)(970-640)(970-700)}\approx 77781$
$Cost = 77781 × 50 = 3889051$
It will cost Rs. 38,89,051.


text:
Q: How to a circular Image on ImageView and relative layout using xml How to add a circular image on Image view as the below image:

and this is the code I have:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="3dp"
        card_view:cardBackgroundColor="@color/colorwhite"
        card_view:cardCornerRadius="8dp"
        card_view:cardUseCompatPadding="false"
        card_view:elevation="15dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:layout_gravity="center_horizontal"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/flag"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentRight="true"
                android:scaleType="fitXY"
                android:src="@drawable/mac_img" />

            <TextView
                android:id="@+id/titleTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginTop="85dp"
                android:textStyle="bold"
                android:textColor="@color/colorwhite"
                android:layout_centerHorizontal="true" />

        </RelativeLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

as I am trying also add the a text view like is shown in the image like the Closed, So all I need I want the way to do this as to put widgets like this way as in the figure..

A: Ok good I solved it by adding some margins I hope someone give me a recommendation about this, and this is the full code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="3dp"
        card_view:cardBackgroundColor="@color/colorwhite"
        card_view:cardCornerRadius="8dp"
        card_view:cardUseCompatPadding="false"
        card_view:elevation="15dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:layout_gravity="center_horizontal"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/flag"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentRight="true"
                android:scaleType="fitXY"
                android:src="@drawable/mac_img" />

            <TextView
                android:id="@+id/titleTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginTop="85dp"
                android:textStyle="bold"
                android:textColor="@color/colorwhite"
                android:layout_centerHorizontal="true" />

        </RelativeLayout>

        <com.cuboid.cuboidcirclebutton.CuboidButton
            android:layout_width="70dp"
            android:layout_height="70dp"
            app:cub_border_color="@color/color_64b5f6"
            app:cub_border_radius="4dp"
            android:layout_marginTop="85dp"
            android:layout_marginLeft="30dp"
            app:cub_color="@color/colorwhite"
            app:cub_hover_color="@color/color_0288D1"
            app:cub_icon="@drawable/eat"
            app:cub_riple_effect="true" />

    </androidx.cardview.widget.CardView>

</LinearLayout>


text:
Q: What is the best bucket size for a task queue filled with many deferred tasks in Google App Engine? My Google App Engine application is adding a large number of deferred tasks to a task queue. The tasks are scheduled to run every x seconds. If I understand the bucket-size property b correctly, a high value would prevent the deferred tasks to run until b tasks have been added. However, there is a close-to-realtime requirement that the tasks run as scheduled. I do not want that the tasks are blocked until the bucket-size is reached. Instead they should run as close to their scheduled time as possible.
To support this use case, should I use a bucket-size of 1 and a rate of 500 (which is the current maximum rate)? Which other approaches exist to support this? Thanks!

A: The bucket size does not prevent tasks from running individually. It plays a different role.
Suppose you have an empty queue with rate of 500 tasks per second, and several hours where no tasks are added or started. Then suddenly a large number of tasks are added at once. How many of these tasks would you like started immediately?  Set this number as your bucket size. For example, with a bucket size of 1000, 1000 tasks will be started immediately (then 500 per second going forward).
How does this work? The bucket is topped up by 500 tokens every second (the queue's rate), up to the maximum being the bucket size. When there are tasks are available to start, they will only be started while the bucket is not empty, and one token will be removed from the bucket as each task is started.

A: You should NOT use taskqueues (TQ) for deferred tasks that are important to run close-to-realtime using the assumption that bucket/rate setting will assure high throughput. There have been several discussion threads in Google groups about infrequent delays with task start times that are minutes or more in length. Bucket size and rates will not have an affect on this -- your TQ tasks will simply sit there while your high-throughput TQ is idle. To date I have not ever seen any explanation from Google as to why this occurs. Again, if you utilize TQs for close-to-real-time tasks you MUST handle as an exception the infrequent times when your tasks will delay for minutes prior to starting. (I in fact do this, and have not yet been negatively affected, but you have to have code in place to handle a result = delayed task). My great hope is that with the new server/application testing underway, Google will find an easy way to kill this incredibly big issue with TQs (fingers crossed).


text:
Q: Golang, Firebase... converting a MAP to a struct slice how to convert a Document map Snapshot from firestore into a struct slice?  The struct is not displayed in this example, but the problem code is towards the end of the page.
This code works except for the Marked Code at bottom. Code communicates with a FireStore DB and returns a complicated structure called COMPLEX_NONACS.  Bascially, I want to convert . firestore snapshot into a json golang object.
package main

import (
    "context"
    "fmt"
    "log"

    "firebase.google.com/go"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}
func main() {
    ctx := context.Background()
    sa := option.WithCredentialsFile("./scai-qit-fb-adminsdk.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
        log.Fatalf("error initializing app: %v\n", err)
    }
    client, err := app.Firestore(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    CompNACS := []string{}
    var SCNACS COMPLEX_NONACS // single Complex NONACS
    var MCNACS []COMPLEX_NONACS

    iter := client.Collection("COMPLEX_NONACS").Documents(ctx)
    for {
        doc, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            log.Fatalf("Failed to iterate: %v", err)
        }
        //This part works.  WIll return a Map of each Document
        fmt.Println("--------------------------/n")
        fmt.Println(doc.Ref.ID)
        fmt.Println("--/n")
        fmt.Println(doc.Data())

        //  PUT ANSWER HERE...
        // doc.Data() should return map[String] interface{} that is
        // actually of a struct TYPE COMPLEX_NONACS.
        // Question is there a simpler way to CAST doc.Data() as
        // a type?  Docs say this...
        // Data returns the DocumentSnapshot's fields as a map.
        // It is equivalent to
        //     var m map[string]interface{}
        //     d.DataTo(&m)
        // except that it returns nil if the document does not exist.

        //---   this is the error ---
        //  The problem cannot convert to COMPLEX_NONACS
        SCNACS = COMPLEX_NONACS(doc.Data())
        fmt.Println(SCNACS)

        CompNACS = append(CompNACS, doc.Ref.ID)
    }
}

/==========================
the first two Documents...
The structure is the same for all documents in the collection, but some Documents just have different combinations of fields.  I would list the struct, but it is huge.
--------------------------/n
A01B01C01D01
--/n
map[E01PCI: DE03CABG:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E06CPCI: DE06CCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE01PCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE06CPCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DF03CABGPCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE05CCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE04PCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE07BPRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] Q04PRIORCABG:No Previous CABG DF03PRIMARY:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] E06BPCI: E05BCABG: E06CCABG: DF04PRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE05APCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] E03PCI: F03CABGPCI: DE06CABG:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE05CPCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] E04PRIMARY: DE05BPCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE04CABG:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] Q03:C01 E06APRIMARY:48-Asymptomatic DE06PCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] F03CABG: E05ACABG: DEADEND: DE04PRIMARY:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E05CPCI: Q01IschemicSymptoms:Asymptomatic (No ischemic symptoms) DE02PCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] INDEX:A01B01C01D01 E05PRIMARY: F01PRIMARY: E01PRIMARY: Q03NonInvasiveTestResults:No non-invasive testing performed E03PRIMARY: DE03PRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] Q02AntiIschemicMedicalTherapy:No Therapy DF04PCI:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DF01PRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] F04PCI: E05CCABG: DE07CCABG:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] E07CCABG: E07PRIMARY:49-Asymptomatic F03PRIMARY: E05CPRIMARY:23-Asymptomatic E07BPRIMARY: E07BCABG: DE06PRIMARY:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DE07CABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DF02PRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE05PRIMARY:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DE06APCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DF03CABG:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E06ACABG: E06BPRIMARY: E07APCI: DE06APRIMARY:map[SCOREGRAPHIC:08 SCORE:08 INDICATION:48 SCOREDEFINITIONS:48 Q01CAT:Asymptomatic TermDescription:[48. Three-vessel CAD (no left main) Abnormal LV systolic function -] Name:48-Asymptomatic] DF04CABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E06APCI: E02PCI: E05PCI: DE07ACABG:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E04CABG: DE05ACABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DE07APRIMARY:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE06BCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] F04CABG: Q02:B01 DE07PRIMARY:map[TermDescription:[49. Left main stenosis  -] Name:49-Asymptomatic SCOREGRAPHIC:09 SCORE:09 INDICATION:49 SCOREDEFINITIONS:49 Q01CAT:Asymptomatic] DE07PCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E06PCI: DE06BPRIMARY:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] E02PRIMARY:20-Asymptomatic DE06ACABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DE05BCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E07CABG: DE07CPRIMARY:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE05BPRIMARY:map[SCOREGRAPHIC:03 SCORE:03 INDICATION:22 SCOREDEFINITIONS:22 Q01CAT:Asymptomatic TermDescription:[22. One- or 2-vessel CAD with borderline stenosis 50% to 60% No noninvasive testing performed or equivocal test results present FFR less than or equal to 0.80* and/or IVUS with significant reduction in] Name:22-Asymptomatic] E02CABG: E04PCI: DE05APRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE05CPRIMARY:map[SCORE:01 INDICATION:23 SCOREDEFINITIONS:23 Q01CAT:Asymptomatic TermDescription:[23. One- or 2-vessel CAD with borderline stenosis 50% to 60% No noninvasive testing performed or equivocal test results present FFR or IVUS findings do not meet criteria for significant stenosis] Name:23-Asymptomatic SCOREGRAPHIC:01] DE07BCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E01CABG: E05BPCI: E05BPRIMARY:22-Asymptomatic DE07CPCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE02PRIMARY:map[Q01CAT:Asymptomatic TermDescription:[20. One- or 2-vessel CAD without involvement of proximal LAD No noninvasive testing performed -] Name:20-Asymptomatic SCOREGRAPHIC:03 SCORE:03 INDICATION:20 SCOREDEFINITIONS:201] DE01CABG:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] Q01:A01 E03CABG: E06PRIMARY: DE06CPRIMARY:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE06BPCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE02CABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DF04CABGPCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] F02PRIMARY: E05APCI: E07APRIMARY: F04PRIMARY: E05CABG: E06CPRIMARY: E06CABG: DE07APCI:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] Q04:D01 DE01PRIMARY:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E07CPRIMARY: F04CABGPCI: E07CPCI: E05APRIMARY: DE05PCI:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DF03PCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] F03PCI: E07ACABG: DE05CABG:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] Title:NACS-100 DE03PCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] E07BPCI: E07PCI: DE07BPCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] E06BCABG:]
--------------------------/n
A01B01C01D02
--/n
map[DF03PCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] F04PRIMARY: DEADEND:NR DE05CPRIMARY:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DE05CPCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE07BPCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] F02PRIMARY: DE07CPRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE07CABG:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E02PRIMARY: DE05BCABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] E01PCI: Q03NonInvasiveTestResults:No non-invasive testing performed E07BPRIMARY: E06CPCI: E03PRIMARY: E06CCABG: E06APRIMARY: E07PCI: DE05BPCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E01CABG: DE05CCABG:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DF04CABGPCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE07ACABG:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] E04CABG: DE05PCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE07APCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E05CABG: INDEX:A01B01C01D02 E04PCI: DE07CPCI:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E06PCI: E05CCABG: F03PRIMARY: F04CABGPCI: E05APCI: E05BPRIMARY: DE06CPCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DF03CABGPCI:map[Q01CAT: TermDescription:[] Name:69 SCOREGRAPHIC: SCORE: INDICATION:69 SCOREDEFINITIONS:] E07CPCI: DE06APCI:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE05ACABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE05APRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE06BPCI:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DF04CABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE03PCI:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE07CCABG:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE06ACABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] F03PCI: DE06PRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E07CABG: E05BCABG: DE06BCABG:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] F03CABGPCI:69 DE06BPRIMARY:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] F04CABG: E05PRIMARY: Title:NACS-500 DE07APRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E06ACABG: E03PCI: DE02CABG:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE06CPRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] DE07BPRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] F01PRIMARY: DE01PCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE06APRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E07APCI: DE06CABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DE07BCABG:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DF02PRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E04PRIMARY: DF04PRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE05PRIMARY:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] E06CPRIMARY: Q02AntiIschemicMedicalTherapy:No Therapy E06PRIMARY: E01PRIMARY: Q04PRIORCABG:Previous CABG E05CPCI: DF01PRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E07APRIMARY: E06BPRIMARY: E05CPRIMARY: DE03PRIMARY:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] E06CABG: E03CABG: DE02PCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] F03CABG: E05APRIMARY: DF04PCI:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE05CABG:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] DE05APCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] E02PCI: Q01IschemicSymptoms:Asymptomatic (No ischemic symptoms) E07PRIMARY: DE04CABG:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] E06APCI: E06BCABG: DE02PRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] DE06PCI:map[INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE:] DF03CABG:map[SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC:] DE07PCI:map[SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION:] Q03:C01 E05PCI: DE06CCABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DE04PCI:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E07BCABG: E07CPRIMARY: E02CABG: DE03CABG:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] F04PCI: E07ACABG: DE04PRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] Q04:D02 E05BPCI: E07CCABG: DE05BPRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] DF03PRIMARY:map[Q01CAT: TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS:] DE01PRIMARY:map[SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil> Name:] E05ACABG: Q01:A01 E07BPCI: DE01CABG:map[TermDescription:<nil> Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT:] Q02:B01 DE07PRIMARY:map[Name: SCOREGRAPHIC: SCORE: INDICATION: SCOREDEFINITIONS: Q01CAT: TermDescription:<nil>] E06BPCI:]

A: It looks like you're getting result data from Firebase with type map[string]interface{} and you need to convert it to type map[string]*Foo (where Foo is some struct defined elsewhere).
If the Foo struct can easily be de/serialized into some intermediate format then you might be able to serialize the untyped values and then deserialize them into a variable of your desired type.
For example, using JSON (Go Playground):
docdata := getDocData()
for label, data := range docdata {
    // Marshal the untyped data into a suitable format.
    bs, err := json.Marshal(data)
    check(err)
    // Unmarshal the formatted data into a variable with desired type.
    var foo *Foo
    err = json.Unmarshal(bs, &foo)
    check(err)
    fmt.Printf("OK: label=%q, foo=%#v\n", label, foo)
}
// OK: label="E01PCI", foo=(*main.Foo)(nil)
// OK: label="E06CPCI", foo=(*main.Foo)(nil)
// OK: label="DE03CABG", foo=&main.Foo{Name:"Alpha", SCOREGRAPHIC:"Bravo", SCORE:3.14159, INDICATION:true, SCOREDEFINITIONS:"Echo", Q01CAT:6, TermDescription:(*string)(nil)}
// OK: label="DE06CCABG", foo=&main.Foo{Name:"Hotel", SCOREGRAPHIC:"India", SCORE:10.1, INDICATION:true, SCOREDEFINITIONS:"Lima", Q01CAT:13, TermDescription:(*string)(0x1050c3d0)}

It's unclear from your question whether the data in doc.Data() is the entire struct that you mention or some other sort of structured data which includes instances of your struct (my example assumes the latter); however, the general idea of serializing into an intermediate format and deserializing into a typed variable should work either way.


text:
Q: How to design a RESTful URL for search with optional parameters? If I have to create a URL in my RESTful web service, which would be used by my clients to search all businesses by their fields where the fields are optional, what would the URL look like?
A business can be search by their name alone, name and phone number or name, phone number and contact e-mail.

A: Chandru,
think of the list of all the businesses like of a set of entities with attributes. You can create URIs that identify (select) a subset by the use of parameters in the URI.
Commonly this is done by query string parameters (the stuff after the '?') but you can also specify parameters as path segments or matrix URIs.
The most typical means to do this would be something like

*

*http://foo.org/service/businesses/?name=acme or

*http://foo.org/service/businesses/?name=acme&phone=12345 or

*http://foo.org/service/businesses/?name=acme&contact=smith@bar.org
  ('@' would need URL encoding of
  course)

It is conceptually similar to an SQL select clause.
Parameters in path segments or matrix parameters have an impact regarding the indexing possibilities (e.g. matrix parameters allow you to filter at multiple levels because the hierarchy can continue after wards, which it cannot with query parameters). I suggest you make that a different question if you are concerned with it.
Example:

http://foo.org/service/businesses/france/name=acme;city=paris/latest/?contact=xxx

Jan


text:
Q: How to list manually installed packages? I'd like to get a list of packages installed manually by apt or aptitude and be able to find out whether a foobar package was installed manually or automatically.
How can we do that from the command line?

A: As several people have commented, apt-mark showmanual seems to be a bit buggy (and I reported it as bug 727799). When I'm using it, it actually reports a lot of stuff that isn't even logged in /var/lib/apt/extended_states (where this is supposed to be stored) and apt-get isn't logging things as installed in /var/lib/apt/extended_states (just in /var/lib/dpkg/status). The python script by txwikinger above draws from /var/lib/apt/extended_states directly but if you're using it today the syntax might not work (mine just started generating errors with Kubuntu 13.10). Updated syntax is:
#!/usr/bin/python
import sys

try:
    import apt_pkg
except ImportError:
    print "Error importing apt_pkg, is python-apt installed?"
    sys.exit(1)

apt_pkg.init()
STATE_FILE = apt_pkg.config.find_dir("Dir::State") + "extended_states"
auto = set()
tagfile = apt_pkg.TagFile(open(STATE_FILE))
while tagfile.step():
    pkgname = tagfile.section.get("Package")
    autoInst = tagfile.section.get("Auto-Installed")
    if not int(autoInst):
        auto.add(pkgname)
print "\n".join(sorted(auto))

For me this was a very short list of 5 items which doesn't seem to be accurate either.

A: To get a list of all packages (not installed, installed by user or installed by default, across all PPAs), apt employs the following method:
apt list [option]
The possible options useful for this are:
--installed to display only the packages that are installed on the system (out of some 50,000+)
--manual-installed to list the packages that were explicitly installed by a command, either directly, or as dependencies.
Alternatively, you could do:
apt list --installed | grep -F \[installed\] to get a list of packages that resulted from user commands and their dependencies only, and to get additional information on them such as version and architecture supported (x86, x86_64, amd64, all, etc.)

A: For Ubuntu 16.04, check out the log file /var/log/apt/history.log.
For example:
zgrep 'Commandline: apt' /var/log/apt/history.log /var/log/apt/history.log.*.gz

It's not perfect, but it's pretty good at making it clear exactly what I installed by hand.  Put a -B 1 on the grep to see when it was installed.
Example output
Commandline: apt install postgresql-9.5-plv8
Commandline: aptdaemon role='role-install-file' sender=':1.85'
Commandline: apt install task
Commandline: apt autoremove
Commandline: apt install atom
Commandline: apt upgrade
Commandline: apt-get install asciinema
Commandline: apt install iperf3
Commandline: apt upgrade
Commandline: apt-get install chromium-browser
Commandline: apt install joe cpanminus build-essential postgresql libdbd-pg-perl libcrypt-openssl-bignum-perl libcrypt-openssl-rsa-perl libio-socket-ssl-perl libnet-ssleay-perl libssl-dev
Commandline: aptdaemon role='role-commit-packages' sender=':1.2314'
Commandline: apt install git
Commandline: apt install sqlite
Commandline: apt install whois
Commandline: apt install libdbd-pg-perl
Commandline: apt install perl-doc
Commandline: apt upgrade

Not sure if this picks up aptitude or not.  It doesn't seem to pick up installs from the Ubuntu Software desktop app.

A: You can use either of these two one-liners. Both yield the exact same output on my machine and are more precise than all solutions proposed up until now (July 6, 2014) in this question.
Using apt-mark:
comm -23 <(apt-mark showmanual | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)

Using aptitude:
comm -23 <(aptitude search '~i !~M' -F '%p' | sed "s/ *$//" | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)

Very few packages still fall through the cracks, although I suspect these are actually installed by the user, either right after the installation through the language localization setup or e.g. through the Totem codec installer. Also, the linux-header versions also seem to accumulate, even though I've only installed the non version-specific metapackage. Examples:
libreoffice-help-en-gb
openoffice.org-hyphenation
gstreamer0.10-fluendo-mp3
linux-headers-3.13.0-29

How does it work:

*

*Get the list of manually installed packages. For aptitude, the additional sed strips out remaining whitespace at the end of the line.

*Get the list of packages installed right after a fresh install.

*Compare the files, only output the lines in file 1 that are not present in file 2.

Other possibilities don't work as well:

*

*Using the ubuntu-14.04-desktop-amd64.manifest file (here for Ubuntu 14.04) instead of /var/log/installer/initial-status.gz. More packages are shown as manually installed even though they are not.

*Using apt-mark showauto instead of /var/log/installer/initial-status.gz. apt-mark for example doesn't include the xserver-xorg package, while the other file does.

I used various other StackExchange posts as references, however none work as well as the above solution:

*

*aptitude + manifest

*initial-status.gz + apt-mark showauto
Both list more packages than the above solution.
EDIT: What to do if you've upgraded from a previous release:
If you've upgraded Ubuntu from one release to the next, you will probably need to adjust this process. In that case, I would check the manifest file of the newer release (see above) in addition to the initial-status.gz file from the current release. You can easily do that by just adding another comparison. Using just the manifest file will not work, as the manifest file unfortunately does not contain everything that the initial_status.gz file does (I checked).

A: If you're in a VM (Virtual Machine), then the following might work better for you:
egrep 'apt(-get)? +install' /var/log/apt/history.log

That finds software you installed both via apt and apt-get. If you'd like to include aptitude too, this should work:
egrep 'apt(-get|itude)? +install' /var/log/apt/history.log

(But don't think this'd find packages installed directly via dpkg — which I don't really do anyway.)
Rationale: If the Virtual Machine already included some default software installed by the VM maintainers (in the base image), but not by you, then, this answer won't show the software they installed (well at least not in the VMs I'm using), only the software you installed.
The other answers here, which uses e.g. apt-mark showmanual or aptitude search '!~M ~i' or apt list --manual-installed, in my case, in a VM, showed 90% to me uninteresting packages that I didn't install — instead, some of the VM base image maintainers did (I presume).

A: apt-mark showauto | grep -iE '^foobar$' will output "foobar" if the package was installed automatically, nothing otherwise.
aptitude search '!~M ~i' will list the packages that were not installed automatically. It's a pity aptitude won't be part of the default install on Ubuntu Desktop starting from 10.10.

A: If no one gives you a nice answer using a apr-something command you can do it the hard way. Apt-get stores its info in /var/lib/apt/extended_states. Any file that is installed automatically will be added to this file. If you install a package already in this file manually, the package will remain in this file but with Auto-installed: 0 in the second line. It's not deleted.
Note: As expected better answers that are likely to work if file placement changes have appeared. I keep mine just in case the info on the file location is useful.

A: After googling a lot, I've managed to assemble this script. It works alright for me:
#!/bin/bash

# List of all packages currently installed
current=$(dpkg -l | awk '{print $2}' | sort | uniq)

# List of all packages that were installed with the system
pre=$(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort | uniq)

# List of packages that don't depend on any other package
manual=$(apt-mark showmanual | sort | uniq)

# (Current - Pre) ∩ (Manual)
packages=$(comm -12 <(comm -23 <(echo "$current") <(echo "$pre")) <(echo "$manual") )

for pack in $packages; do
    packname=$(echo $pack | cut -f 1 -d ":")
    desc=$(apt-cache search "^$packname$" | sed -E 's/.* - (.*)/\1/')
    date=$(date -r /var/lib/dpkg/info/$pack.list)

    echo "# $desc"
    echo "# $date"
    echo "sudo apt-get install $pack"
    echo -e ""
done

A: An updated version of @jmiserez' answer:
comm -23 \
    <(apt-mark showmanual | sort -u) \
    <(grep -oP '^(?:Package|Depends):\s+\K.*' /var/log/installer/status \
        | grep -oP '[^\s,()]+?(?=(?:\s+\([^)]+\))?+(?:,|$))' \
        | sort -u)

The log is no longer stored at /var/log/installer/initial-status.gz and the original did not omit dependent packages. The list it produces will include packages you didn't manually install, but it's a more manageable length and still very useful.

A: In newer versions of the package apt, there is also the apt-mark command
apt-mark showmanual

A: The following script will print out all the packages that are not set to automatic install and hence were installed manually:
#!/usr/bin/python

try:
    import apt_pkg
except ImportError:
    print "Error importing apt_pkg, is python-apt installed?"
    sys.exit(1)

apt_pkg.init()
STATE_FILE = apt_pkg.config.find_dir("Dir::State") + "extended_states"
auto = set()
tagfile = apt_pkg.TagFile(open(STATE_FILE))
while tagfile.step():
    pkgname = tagfile.section.get("Package")
    autoInst = tagfile.section.get("Auto-Installed")
    if not int(autoInst):
        auto.add(pkgname)
print "\n".join(sorted(auto))

it is based on how apt-mark prints out the automatically installed packages.

A: I would like to give a GUI solution.

*

*Open Synaptic Package Manager.

*Go to Status.

*Click Installed (manual).
It will give the list of packages installed manually by apt or aptitude.
Unfortunately I could not find any option in Custom Filters to find out whether a foobar package was installed manually or automatically.
If the package is under Installed but not under Installed (manual), then it was installed automatically. If the package is under Installed (manual), then it was installed manually.

A: As Li Lo said, apt-mark showauto should get you a fat list of things automatically installed.
Now to show the things that are installed manually, it turns out there's a lovely simple search modifier for aptitude. But you don't want to to do that. You want to write a huge bash command that does some rocket science.
Note: This is more an illustration of how cool you'll look busting out massive bash commands to all your friends.
comm -3  <(dpkg-query --show -f '${Package} ${Status}\n' | \n
grep "install ok installed" | cut --delimiter=' ' -f 1) <(apt-mark showauto)

I broke it onto two lines for readability. What does this do?

*

*First we query dpkg for a list of packages that are installed.

*We filter those for the ones that are actually installed (not just residual config)

*We chop off the status

*We compare that list with the automated list from apt-mark

*We rock out because we can.

A: Not sure if this is helpful, but to find packages that were recently installed manually by the current user, search the history. E.g., for bash:
$ history | egrep '\bapt\b'

Modify the grep to check for specific packages.

A: This gets you a list of manual installed packages and its corresponding version
apt list --manual-installed | sed 's/\// /' | awk '{print $1 "=" $3}'

A: From Ubuntu 22.04 and onwards, you could take care of this using a more modern apt front-end called nala (for 22.04 you have to enable the "universe" repository).
sudo apt install nala

From this point, use nala to install new packages on your system, using:
sudo nala install <package-name>

Leave security updates etc. to the unattended-upgrades package.
Now, when you run the command nala history, you get a list of the commands run with nala, including installed packages. To filter only new installations, use:
nala history | grep install

An added bonus of the history feature is that you can undo any step in the history, so that you can reverse package installation procedures - something that is unnecessarily hard using apt itself.

A: If you installed all your packages from the terminal using apt, you could throw a simple regex searching for apt install * at the contents of /var/log/apt/history.log and see what it gobbles up.
The regex might be as simple as: Commandline: apt install [\w -]+ (following the log syntax of apt on Ubuntu 16.04)

A: This will list all manually installed packages without: dependencies, uninstalled packages, packages installed during system installation.
unopts() {
  in=`cat`
  echo "$in" | sed -r 's/ --[^ ]+//g;s/ -[^ ]+//g'
}

list() {
  cat '/var/log/apt/history.log' |
  grep --color=never -v '\-o APT::Status-Fd=4 \-o APT::Keep-Fds::=5 \-o APT::Keep-Fds::=6' |
  egrep --color=never "Commandline: apt-get.* $1" |
  sed -r "s/Commandline: apt-get//;s/ $1//" |
  unopts |
  tr ' ' '\n' |
  sed '/^$/d'
}

hapt() {
  tmp=`mktemp -d`
  installed=$tmp/installed
  deleted=$tmp/deleted
  dpkg=$tmp/dpkg
  list 'install' > $installed
  list '(remove|purge|autoremove)' > $deleted
  dpkg --get-selections |
  grep -v 'deinstall' |
  cut -f 1 > $dpkg
  while read package
  do
    sed -i "0,/$package/{//d;}" $installed
  done < $deleted
  while read package
  do
    if [ -z "`grep --color=never "^$package$" $dpkg`" ]
    then
      sed -i "0,/$package/{//d;}" $installed
    fi
  done < $installed
  cat $installed
  rm -r $tmp
}


text:
Q: How to use AutoHotKey to act upon new files created in a folder? I'd like to have AutoHotKey listen/watch a folder on disk (let's say c:\folder) for any new files that are created there. If a new file show's up, the script should execute a set of commands:
Send {Esc}
   Sleep, 100
   Send {F5}
   Sleep, 100
   Send {Home}
   Sleep, 100
   Send s
   Sleep, 100
   Send {Enter}
Return
, after which it should go back to watching the folder for new changes and so on. I realize it should use the WatchDirectory() funtion, but don't know how to implement it. Any help? Thx!

A: You can use the WatchFolder() function, download it put it in the same place as your script and then you can do:
#Include %A_ScriptDir%\WatchFolder.ahk

WatchFolder("c:\folder", "myFunc", , Watch := 1)
return

myFunc(path, changes) {
    for k, change in changes
        ; 1 means new file was added
        if (change.action = 1) {
            gosub doStuff
            return
        }
}

doStuff:
; commands you want to execute
return

A: Thanks for your answer. I added your code and it doesn't want to work, the script seems not to load (no icon in task bar). My final code looks like this:
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

#Include %A_ScriptDir%\WatchFolder.ahk

WatchFolder("C:\Users\kris\Desktop\temp", "myFunc", , Watch := 1)
return

myFunc(path, changes) {
for k, change in changes
    ; 1 means new file was added
    if (change.action = 1) {
        gosub doStuff
        return
    }
}

doStuff:
  Send {Esc}
  Sleep, 500
  Send {F5}
  Sleep, 100
  Send {Home}
  Sleep, 100
  Send s
  Sleep, 100
  Send {Enter}
return

I've inserted the WatchFolder.ahk in the same folder as the script.


text:
Q: Diffeomorphisms of $\mathbb{R}^n$ I recently realized that I don't know any non-linear diffeomorphisms of the plane (or $\mathbb{R}^n$ in general) except for linear ones, so I want to ask rather broad questions hoping to be pointed to the appropriate literature.
1) Are there simple ways of constructing autodiffeomorphisms of $\mathbb{R}^n$ that can be expressed in closed form? UPD: Ok, there's e.g. $(x, y) \mapsto (x, y + f(x))$, where $f: \mathbb{R} \to \mathbb{R}$ is smooth, so I call this one back - kind of, if you know some exciting and unusual family, feel free to share :)
2) Is every autodiffeomorphism of $\mathbb{R}^n$ isotopic to a linear one? Obviously, every one is homotopic to any other due to $\mathbb{R}^n$ being contractible, but since $\mathrm{GL}(\mathbb{R}^n)$ is not connected, $\mathbb{R}^n$ is a k-space), and homotopies behave nicely under differentials at a point, even some linear autodiffeomorphisms are not isotopic, if I'm not mistaken.

A: The answer to your question (2) is yes.
The proof goes like this.  Let $f$ be a diffeomorphism.  We find an isotopy from $f$ to a diffeomorphism $g$ with $g(0)=0$.  The isotopy is
$$(x,t) \longmapsto f(x)-tf(0) $$
when $t=0$ this is $f$, when $t=1$ you get $f(x)-f(0)$.
Next, given a diffeo $g$ with $g(0)=0$ we isotope $g$ to a linear diffeomorphism.  The map is this:
$$(x,t) \longmapsto \frac{g((1-t)x)}{1-t}$$
for $t \in [0,1)$ and at $t=1$ we have
$$(x,1) \longmapsto Dg_0(x)$$
You can check this map is continuous provided $g$ is $C^1$.
Regarding your 1st question, one of the most common techniques is to integrate vector fields.

A: Consider $\mathbb{R}^2$ first. Let $f$ be a smooth function on $\mathbb{R}^2$. If we consider a matrix
$$ \begin{bmatrix}
\cos(f(x,y)) &  -\sin(f(x,y))\\
 \sin(f(x,y)) &  \cos(f(x,y))
\end{bmatrix}$$ This is non linear map and it gives a diffeomorphism on $\mathbb{R}^2$. Using these $2\times2$ blocks we can build diffeomorphisms on $\mathbb{R}^n$
just like we build rotations from the $2\times2$ blocks. We can use hyperbolic cos and sine also.
$$ \begin{bmatrix}
\cosh(f(x,y)) &  \sinh(f(x,y))\\
 \sinh(f(x,y)) &  \cosh(f(x,y))
\end{bmatrix}$$
Another set of non linear diffeomorphisms are given by,
$$\begin{bmatrix} 1 & f(x,y)\\0 & 1\end{bmatrix}$$ we can choose any non zero constants on the diagonals instead of $1$ and can have lower triangular matrices also. Product of all these types also gives non linear diffeomorphisms.


text:
Q: Estou com problemas no meu sistema de login <?php
include('conexao.php');

if(empty($_POST['usuario']) || empty($_POST['senha'])) {
    header('Location: index.html');
    exit();
}

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, $_POST['senha']);

$query = 'select usuario_id, usuario from usuario where usuario = '{$usuario}' and senha = md5('{$senha}')';

$result =  mysqli_query($conexao, $query);

$row = mysql_num_rows($result);

if($row == 1) {
    $_SESSION['usuario'] = $usuario;
    header('Location: home.html');
    exit();
} else {
    header('Location: index.html');
    exit();
}

Ele retorna o seguinte erro:

Parse error: syntax error, unexpected '' and senha = md5('' (T_CONSTANT_ENCAPSED_STRING) in C:\xampp\htdocs\login.php on line 13

Por favor me ajudem eu não faço ideia do quê possa ser ...

A: Eu recomendo usar PrepareStatement por questões de segurança e para evitar riscos maiores de SQLInjection, eu simulei uma sessão pegando o perfil de acesso do usuário, e a id dele, porque é só isso basicamente que vc precisaria, em tese, numa sessão:

if (!$_POST || empty($_POST['usuario']) || empty($_POST['senha'])) {
    header('Location: index.html');
    exit();
}

$usuario = mysqli_real_escape_string($_POST['usuario']);
$senha = MD5($_POST['senha']);

$query = "SELECT id, role FROM usuario WHERE usuario = ? AND senha = ?";

 if (!($stmt = mysqli_prepare($conexao, $query) && $usuario && $senha)) {
    header('Location: index.html');
    exit();
 } else {
    $setParams = mysqli_stmt_bind_param($stmt, "ss", $usuario, $senha);
    $execute = mysqli_stmt_execute($stmt);
    $results = mysqli_stmt_get_result($stmt);
    $array_result = mysqli_fetch_assoc($results);

    //print_r($array_result);

   if (!$results) {
        header('Location: index.html');
        exit();
    }

    if (!isset($array_result['id'])) {
        header('Location: index.html');
        exit();
    }

    session_start();
    $_SESSION['usuario'] = $usuario;
    $_SESSION['id'] = $array_result['id'];
    $_SESSION['nivel_acesso'] = $array_result['role'];
    header('Location: home.html');
    exit();
}

A: Olá @JeanExtreme002, tudo bem?
Atualizei o $_POST atribuído na variável "senha" e atualizei a sua query.
Altere o seu código para tal:
<?php
include('conexao.php');

if(empty($_POST['usuario']) || empty($_POST['senha'])) {
    header('Location: index.html');
    exit();
}

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, md5($_POST['senha']));

$query = "SELECT * FROM usuario WHERE usuario = '$usuario' AND senha = '$senha'";

$result =  mysqli_query($conexao, $query);

$row = mysql_num_rows($result);

if($row == 1) {
    $_SESSION['usuario'] = $usuario;
    header('Location: home.html');
    exit();
} else {
    header('Location: index.html');
    exit();
}

Espero ter ajudado.
Cumprimentos,
minds'.


text:
Q: Sanitize password string in cpp I have a string ,
userStmt:
SELECT * FROM RUN_ON_HIVE(SERVER('10.23.40.23'),USERNAME('user'),PASSWORD('pass'),DBNAME('default'),QUERY('ANALYZE TABLE default.test01 COMPUTE STATISTICS'));

I am trying to convert the password clause to "****".
String sanitizeduserstmt=userStmt;
  boost::regex pw_re("PASSWORD\\('[^']*'\\)");
  boost::regex_replace(sanitizeduserstmt, pw_re, "PASSWORD('****')");

But this is not working . Can someone tell me where am I going wrong?
TIA

A: The boost::regex_replace method does not modify the input string inplace, you need to assign the value back to the variable.
In your case, the fix will look like
#include <boost/regex.hpp>
#include <iostream>
using namespace std;

int main() {
    string sanitizeduserstmt="SELECT * FROM RUN_ON_HIVE(SERVER('10.23.40.23'),USERNAME('user'),PASSWORD('pass'),DBNAME('default'),QUERY('ANALYZE TABLE default.test01 COMPUTE STATISTICS'));";
    boost::regex pw_re("PASSWORD\\('[^']*'\\)");
    sanitizeduserstmt=boost::regex_replace(sanitizeduserstmt, pw_re, "PASSWORD('****')");
    std::cout << "Result: " << sanitizeduserstmt << "\n";
    // => Result: SELECT * FROM RUN_ON_HIVE(SERVER('10.23.40.23'),USERNAME('user'),PASSWORD('****'),DBNAME('default'),QUERY('ANALYZE TABLE default.test01 COMPUTE STATISTICS'));
}

See the Coliru demo.


text:
Q: fix position in a div css I'm a new to css and i really can't fix all as i want...
How can i align vertical the h1 to the start of user form?
but most important problem for me is that i can't center good the check and the link, i want it one below the other and centered in the div.
I'm not sure if i have positioned good the div but i want it centred but not too low on the page.
thanks to everyone!

body {
    text-align: left;
    background-image: url("img/lemon.jpg");
    color: #1b1b1b;
}

input[type=text],
input[type=password]{
    width: 65%;
    display: table;
    margin: 0 auto;
    padding: 12px 20px;
    border: none;
    border-bottom: 1px solid darkgray;
    background-color: #e9e9e9;
    box-sizing: border-box;
    margin-bottom: 7px;
    resize: vertical;
}

h1 {
    font-size: x-large;
}
h2 {
    font-size: x-large;
}

button {
    background-color: #4CAF50;
    color: white;
    padding: 7px 20px;
    width: 65%;
    height: 20%;
    display: table;
    margin: 0 auto;
    border: none;
    cursor: pointer;
    background: linear-gradient(to bottom, #3d94f6 5%, #1e62d0 100%);
    background-color: #3d94f6;
    border: 1px solid #337fed;
    cursor: pointer;
    color: #ffffff;
    font-size: 17px;

    text-decoration: none;
    text-shadow: -1px 1px 1px #1570cd;
}

button:hover {
    background: linear-gradient(to bottom, #1e62d0 5%, #3d94f6 100%);
    background-color: #1e62d0;
}

button:active {
    position: relative;
    top: 1px;
}

.container {
    width: 35%;
    height: auto;
    margin-right: auto;
    margin-left: auto;
    margin-top: 7%;
    background-color: white;
    box-shadow: 2px 2px 11px rgb(11, 11, 11);
    -webkit-box-shadow: 2px 2px 11px rgb(11, 11, 11);
    -moz-box-shadow: 2px 2px 11px rgb(11, 11, 11);
    overflow: hidden;
}

#check {
    display:block;
    margin-top: 7px;
}

span.frgt {
    margin-top: 7px;
    display: block;
}
a {
    text-decoration: none;
    color: #1e62d0;
}
img {
    width: 100%;
    height: auto;
    opacity: 0.4;
}
<!DOCTYPE html>

Login

        <input type="text" placeholder="Username" name="uname" required>
        <input type="password" placeholder="password" name="psw" required>
        <button type="submit">Login</button>

            <input type="checkbox" checked="checked" name="remember"> Remember me

        forgot password?

A: If you set the h1 to the same width of the button and use "margin: 0 auto" to center it, this will make the h1 span the width of the button, and by default the text will be left aligned to the start of the button.
h1 {
  font-size: x-large;
  width: 65%;
  margin: 0 auto;
}

I'm not too sure exactly what you want to do with the check section. If you use "text-align: center", this will center it, or use the same code as above to align it with the buttons.

A: you can use text-align: center; and vertical-align:top;
If your problem still exists, please explain more clearly what you want.

A: To make it easier to align your elements, just wrap them into one div and adjust the div with CSS instead of dealing with each single element.
Here is an example of what you can do.

body {
  text-align: left;
  background-image: url("img/lemon.jpg");
  color: #1b1b1b;
}

.form {
  width: 75%;
  margin: auto;
}

.form-bottom {
  text-align: center;
}

input[type=text],
input[type=password] {
  display: table;
  margin: 0 auto;
  width: 100%;
  padding: 12px 20px;
  border: none;
  border-bottom: 1px solid darkgray;
  background-color: #e9e9e9;
  box-sizing: border-box;
  margin-bottom: 7px;
  resize: vertical;
}

h1 {
  font-size: x-large;
}

h2 {
  font-size: x-large;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 7px 20px;
  height: 20%;
  width: 100%;
  display: table;
  margin: 0 auto;
  border: none;
  cursor: pointer;
  background: linear-gradient(to bottom, #3d94f6 5%, #1e62d0 100%);
  background-color: #3d94f6;
  border: 1px solid #337fed;
  cursor: pointer;
  color: #ffffff;
  font-size: 17px;
  text-decoration: none;
  text-shadow: -1px 1px 1px #1570cd;
}

button:hover {
  background: linear-gradient(to bottom, #1e62d0 5%, #3d94f6 100%);
  background-color: #1e62d0;
}

button:active {
  position: relative;
  top: 1px;
}

.container {
  width: 35%;
  height: auto;
  margin-right: auto;
  margin-left: auto;
  margin-top: 7%;
  background-color: white;
  box-shadow: 2px 2px 11px rgb(11, 11, 11);
  -webkit-box-shadow: 2px 2px 11px rgb(11, 11, 11);
  -moz-box-shadow: 2px 2px 11px rgb(11, 11, 11);
  overflow: hidden;
}

#check {
  display: block;
  margin-top: 7px;
}

span.frgt {
  margin-top: 7px;
  display: block;
}

a {
  text-decoration: none;
  color: #1e62d0;
}

img {
  width: 100%;
  height: auto;
  opacity: 0.4;
}

Login

      <input type="text" placeholder="Username" name="uname" required>
      <input type="password" placeholder="password" name="psw" required>
      <button type="submit">Login</button>

            <input type="checkbox" checked="checked" name="remember"> Remember me

      forgot password?

A: Use text-align: center; to center text within container.


text:
Q: Is there a Git command that allows you to copy files between local branches without accessing remote? I do not want to push my changes up just yet so I am not going to checkout a file from master or any branch that is remote.

A: Yes, there is such a command, called merge. You can merge a branch into another one, see more here: https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
Merging does not imply a push/pull from remote.


text:
Q: Using QEventLoop to block connected to multiple signals Using a QEventLoop to block execution in a Qt program, how can you connect 10 individual signals to the one loop in such a way that it won't unblock until all 10 signals are received?

A: Please avoid using nested loops when possible. But if you are absolutely sure that you have no way around, you need to have a way to store which of the signals have fired and which of them haven't, and quit the event loop (i.e. maybe by emitting a signal connected to your event loop's QEventLoop::quit) only when all signals have fired.
Here is a minimum example that uses 10 QTimers with different intervals, and waits for all of them to fire before quitting a nested event loop:
#include <QtCore>
#include <algorithm>

int main(int argc, char* argv[]) {
    QCoreApplication a(argc, argv);
    const int n = 10;
    //10 timers to emit timeout signals on different intervals
    QTimer timers[n];
    //an array that stores whether each timer has fired or not
    bool timerFired[n]= {};
    QEventLoop loop;
    //setup and connect timer signals
    for(int i=0; i<n; i++) {
        timers[i].setSingleShot(true);
        QObject::connect(&timers[i], &QTimer::timeout, [i, &timerFired, &loop]{
            qDebug() << "timer " << i << " fired";
            timerFired[i]=true;
            //if all timers have fired
            if(std::all_of(std::begin(timerFired), std::end(timerFired),
                           [](bool b){ return b; }))
                loop.quit(); //quit event loop
        });
        timers[i].start(i*i*100);
    }
    qDebug() << "executing loop";
    loop.exec();
    qDebug() << "loop finished";

    QTimer::singleShot(0, &a, &QCoreApplication::quit);
    return a.exec();
}


text:
Q: E: Package 'oracle-java8-installer' has no installation candidate on Debian I have been trying to install Java 8 on my Debian V-server, but I can't get past the download bc of the error in the Title.
I use the command sudo apt-get install oracle-java8-installer

A: Well, this solved my Issue:
https://pkgs.org/download/oracle-java8-installer
Just followed the instructions and that's it. Sadly, my Server still won't start, dunno if that's an issue that I can post here


text:
Q: killing asynctask when doInBackground hangs on a TCP Socket IPStringI have a fairly simple Activity which works as follows:
in the onCreate, I call an AsyncTask TCP Socket connection to a remote server over a proprietary port, send a quick ASCII command to the server and process the response via the onPostExecute().  Works great, it's fast and functional.
However, if the remote server is down -- or I mistakenly entered in the wrong IP address for the communication -- my AsyncTask will hang with the "logging in" dialog spinning on the screen for as long as it takes for the Socket to timeout.
I've been digging away at this for the last 2 days trying to figure out how to call the cancel(), but am failing.  Any suggestions?
Here's the current code:
 public class Scratchpad extends AsyncTask<Object, String, String>{
private String returningResponse;
private volatile Socket socket;

@Override
protected void onPreExecute(){
    //throw the "Logging In" dialog up
    initializeDialog();
    super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
    //send the ASCII result off to the function that parses through it
    loginTriggerResult(result);
    super.onPostExecute(result);
}
@Override
protected String doInBackground(Object... params) {
        /*
         * bunch of stuff goes here to strip out the proper
         * values from the Object for IP address, Port number etc.
         * params[0], params[1] etc.
         *
        */
    InetAddress serverIP = null;
    String IPString = (String) params[1];
    int portnumber = (Integer) params[2];

    //convert the String "IPString" into an InetAddress
    try {
        serverIP = InetAddress.getByName(IPString);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //and then, bingo bango bongo, make the connection with the 'try':
    try{
        socket = new Socket(serverIP.getHostAddress(), portnumber);
        //I tried this too, forcing the timeout...  It crashes immediately.
        //SocketAddress socketAddress = new InetSocketAddress(serverIP.getHostAddress(), portnumber);
        //socket.connect(socketAddress, 3000);
        Log.d("networking","Connection Completed");

        //bunch of stuff goes here that happens AFTER the solid connection,
        //which we never get to if the Socket fails on a "waiting to connect" thing.

        //reader.close();
        //outputStream.close();

    }catch (SocketException e){
        e.printStackTrace();
        Log.w("socket","socket closed with SocketException");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.w("socket","socket closed with IOException");
    }
    return returningResponse;   //postExecute will handle this.
}

}
I'm not getting any of the Log messages until the 3 or 4 minutes pass that the socket times out.
I'm thinking there must be a way to run a TimerTask or something OUTSIDE of the AsyncTask to track how long it's taking to make the connection (or not) and then somehow "cancel()" the running 'try' inside the AsyncTask, but I've been failing on numerous styles.
This HAS to be something that's commonly used, and there's gotta be an easy solution?
UPDATE:
The path I was heading down was trying to use the socket connection from within AsyncTask to "monitor itself", and if/when it timed out without getting a solid connection -- trigger the cancel() of the AsyncTask.
I was trying to do this from within the AsyncTask itself, with this.cancel() inside the IOException catch of the Socket timeout.
The solution so far is to implement a timer outside of the AsyncTask that launches at the same time as the AsyncTask, and call the cancel from there after however many seconds have transpired.
This solution does gracefully exit from the connection attempt, and I can put any sort of Dialog triggers or Toasts inside the onCancelled() stanza of the AsyncTask.
It doesn't crash anymore, BUT: the socket is still trying to connect in the background, even though the task is cancelled.

A: It definitely seems like the simplest solution (which you have tried) would be to set the timeout when calling connect.  Can you post the stack trace generated when the connect with timeout fails?

A: What exactly is it are you trying to do? Detect when you've entered the wrong IP address or the server is down? Only show logging in for a certain amount of time? I get that you're asking how to cancel your async task, but that doesn't seem to be the root of the problem you're trying to solve.
I think MisterSquonnk is exactly right, you should just be able to set the timeout duration when call connect. You may have something else broken in your code if that timeout doesn't work. Alternatively if you just want something that lets you do your own timeout without having anything to do with socket, see below:
If you want to assume you're connection has failed in a shorter amount of time than the socket takes to time out, start a new CountDownTimer http://developer.android.com/reference/android/os/CountDownTimer.html at the same time and in the same place in your activity as you start your async task with whatever you want the timeout duration to be.
After the timer runs out (and onFinish in the timer is called), call cancel on the async task, or otherwise prevent onPostExecute from executing, and do whatever you want to do when a login attempt fails in your UI. Similarly if the login attempt succeeds before the timer runs out, cancel the timer or otherwise prevent onFinish from being called.


text:
Q: How to call javascript function on the OnLoad event of GridView? I want to call a javascript function when the gridview loads. Im calling it like this,
<asp:GridView ID="GridView4" runat="server" OnLoad="javascript:AddTHEAD('<%= GridView4.ClientID %>')">
</asp:GridView>

and here is the javascript function
<script type="text/javascript">
        function AddTHEAD(tableName) {
        window.open(document.location.href+'&mode=print','_blank');
            var table = document.getElementById(tableName);
            if (table != null) {
                var head = document.createElement("THEAD");
                head.style.display = "table-header-group";
                head.appendChild(table.rows[0]);
                table.insertBefore(head, table.childNodes[0]);
            }
        }
</script>

But im getting compilation errors on calling javasccript function like this. How to call javascript function on the OnLoad event of GridView? What i want to do is basically print gridview header on each page, but i couldn't figure out how. Please help!

A: I don't see an OnLoad event in gridview, but I do see a Load event. Inside this event I would use scriptmanager to call a javascript function from the code behind. Here is an example:
Protected Sub gridCreditLines_ExistingGlobal_Load(sender As Object, e As EventArgs) Handles gridCreditLines_ExistingGlobal.Load

    ScriptManager.RegisterStartupScript(Page,
                                        Page.GetType(),
                                        "AddTHEAD",
                                        "AddTHEAD(" & tableName & ");",
                                        True)

End Sub

Using scriptmanager may require you to add a scriptmanager control to your form:
    <ajaxToolKit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </ajaxToolKit:ToolkitScriptManager>

I'm sure there is a little more to it to hook this into your existing code, but this should at least point you to the right direction. This technique always works for me when trying to call my js functions from the VB code behind.


text:
Q: UL breaks out of 100% height container UL list items don't seem to obey the parent container 100% width in chrome and firefox.  I tried using list-style-position:inside; but that doesn't seem to help:

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

Can anyone explain how I can get the ul text in the example inside the orange div container?

A: Remove style attribute of html tag.

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello


text:
Q: How to add a 3 second delay to this function My goal with this code is to create an effect of leaves blowing away 3 seconds after page load, but currently I am unable to create a delay. Perhaps its because the code format. I made i quick jsfiddle to demonstrate what I have so far.
http://jsfiddle.net/vXpDk/
So my question is how to create a delay of the function so that it doesn't start to rotate and slide for 3 seconds...and if it is possible to to create diagonal paths instead of horizontal and vertical.
Here's the code from the jsFiddle:
var $elie = $("#leaf1"), degree = 0, timer;

rotate();

function rotate() {
    $elie.delay(2000)
        .css({ WebkitTransform: 'rotate(' + degree + 'deg)'})
        .animate({ "left": "+=800px" }, 2000)
        .fadeOut(100);
    $elie.delay(2000)
        .css({ '-moz-transform': 'rotate(' + degree + 'deg)'})
        .animate({ "left": "+=800px" }, 2000)
        .fadeOut(100);

    timer = setTimeout(function() {
        ++degree;
        rotate();
    },0);
}

A: Like this? http://jsfiddle.net/L69Ud/
    var $elie = $("#leaf1"), degree = 0;

    $elie.animate({ "left": "+=800px" }, 5000).fadeOut(100);
    setTimeout(rotate, 3000);

    function rotate() {
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

    setTimeout(function() {
            ++degree; rotate();
            }, 0);
    }

and if it is possible to to create diagonal paths instead of
  horizontal and vertical.

Animate left and top at the same time  http://jsfiddle.net/L69Ud/1/
The only modification here is
$elie.animate({ left: "+=500px", top: "+=500px" }, 5000).fadeOut(100);

How would you code this so that the div does not move at all for 3 seconds then begins to rotate and slide at the same time?
http://jsfiddle.net/L69Ud/3/
    var $elie = $("#leaf1"), degree = 0;

    setTimeout(function() {
       $elie.animate({ left: "+=500px", top: "+=500px" }, 5000).fadeOut(100);
       rotate();
    }, 3000);

    function rotate() {
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

        setTimeout(function() {
                ++degree; rotate();
                }, 0);
    }


text:
Q: Tkinter command doesnt reacts in second OptionMenu I have 2 OptionMenus.
The first one is to select Manufacturer and method assign to command clear options in second OptionMenu and add options assign to the selected manufacturer.
The problem is that second OptionMenu dont trigger the method assign to it's command argument. When I delete/comment first OptionMenu then the second one work correctly.
Why?
Here is piece of code:
        self.cells_menu = tk.OptionMenu(self.local_master,
                                        self.selected_cell,
                                        *[c.full_name()
                                          for c in available_cells.values()
                                          if len(c.performed_tests)>0],
                                        command=lambda x: self.on_cell_select(x))
        self.cells_menu.config(width=40, anchor="w")
        self.cells_menu.grid(row=1, column=0, sticky="W", columnspan=2)
    # (...)
    self.selected_test = tk.StringVar(self.local_master)
        self.test_menu = tk.OptionMenu(self.local_master,
                                       self.selected_test,
                                       *(None, None),
                                       command=lambda x: print(self.selected_test, x))
        self.test_menu.config(width=40, anchor="w")
        self.test_menu.grid(row=3, column=0, sticky="W", columnspan=2)
    # (...)
     def on_cell_select(self, cell_name: str):
        self.selected_cell.set(cell_name)
        new_cell = self.available_cells[cell_name]
        self.update_test_list(new_cell,
                              self.test_menu,
                              self.selected_test)

    def on_test_select(self, cell_name: str):
        print(cell_name)
        curr_cell = self.available_cells[cell_name]
        print(curr_cell)

    def update_test_list(self,
                         new_cell: Cell,
                         menu_to_update: tk.OptionMenu,
                         assign_varstring: tk.StringVar):
        self.selected_test.set('')
        menu_to_update["menu"].delete(0, "end")

        for test in new_cell.performed_tests:
            menu_to_update["menu"].add_command(label=test,
                                               command=tk._setit(assign_varstring,
                                                                 test))```

A: I found the answer.
I just need to add third argument to add_command method. Just like this
def on_cell_select(self, cell_name: str):
    self.selected_cell.set(cell_name)
    new_cell = self.available_cells[cell_name]
    self.update_test_list(new_cell,
                          self.test_menu,
                          self.selected_test,
                          (...))
# (...)

def update_test_list(self,
                     new_cell: Cell,
                     menu_to_update: tk.OptionMenu,
                     assign_varstring: tk.StringVar,
                     command: Callable):
    self.selected_test.set('')
    menu_to_update["menu"].delete(0, "end")
    menu_to_update.config()
    for test in new_cell.performed_tests:
        menu_to_update["menu"].add_command(label=test,
                                           command=tk._setit(assign_varstring,
                                                             test,
                                                             command))


text:
Q: Compile C# → LLVM → ASM.JS? From my understanding I can compile C++ to LLVM, then use Emscripten which outputs to JavaScript.
From http://kripken.github.io/mloc_emscripten_talk/#/11:
C/C++ → LLVM → Emscripten → JavaScript
How might I generate asm.js via Emscripten (I believe that's what generates asm.js at the moment), and (ASM_JS=1 as a compile flag) is there anything that takes C# or .NET to translate it to LLVM?

A: Mono supports LLVM as backend. However, it will probably require lots of changes to make it compatible with Emscripten

A: It seems that for the moment there is not the interest necessary. Perhaps one option would be to use JSIL.
Source: https://twitter.com/migueldeicaza/status/411930995366309888


text:
Q: Nested logarithm series While working on problems from Spivak's Calculus, I came on one asking for the convergence/divergence of the series $$\sum_{n=1}^{\infty} \frac{1}{n^{1+\frac{1}{n}}}.$$
This is a straightforward comparison with the harmonic series to show divergence, but I ended up playing around with the idea a bit more and stumbling on the interesting fact that $$\sum_{n=2}^{\infty} \frac{1}{n^{1+\frac{1}{\log n}}}\,\,\text{diverges}\quad\text{and}\quad \sum_{n=2}^{\infty} \frac{1}{n^{1+\frac{1}{\log\log n}}}\,\,\text{converges}.$$
The first is another limit comparison with the harmonic series; the second I tried to do by looking at $$\int_2^{\infty} \frac{1}{n}\cdot \frac{1}{n^{\frac{1}{\log \log n}}}\, dn$$ and substituting $u=\log n$ to give $$\int_2^{\infty}e^{-\frac{u}{\log u}}\, du,$$ which seems more tractable.
I have two questions:

*

*Can anyone show convergence of divergence of the second series by finishing up my attempt or through some other technique?

*More generally, for the series $$\sum_{n=1}^{\infty} \frac{1}{n^{1+\frac{1}{f(n)}}}$$ what can be said about the growth rates/other characterizations of the $f$ for which this converges?

Any help would be much appreciated!

A: Since $\frac{u^{1/2}}{\log u}\to\infty$, there exists $c>0$ such that $\frac{u^{1/2}}{\log u}>1$ for all $u>c$. Thus $\frac{u}{\log u}>u^{1/2}$ for all $u>c$, and then
$$
e^{-\frac u{\log u}}\leq e^{-u^{1/2}},\ \ u>c.
$$
Also, as $\frac{e^{u^{1/2}}}{u^2}\to\infty$, we can find $d>c$ with $$e^{-u^{1/2}}\leq\frac1{u^2},\ \ u>d. $$
About your second question, you get the integral
$$
\int_1^\infty\frac1x\,e^{-\frac{\log x}{f(x)}}\,dx,
$$
so basically you need $f$ to lose against the logarithm so that the exponential retains some kick.

A: There was a request for a different approach from that discussed in the OP.  Here, we use Cauchy's Condensation test on the series $S$ expressed as
$$S=\sum_{n=3}^\infty f(n) \tag 1$$
where the summand $f(n)$ is given by
$$f(n)=\frac{1}{n^{1+\frac{1}{\log(\log(n)}}}$$
Now, we analyze the sum $T$ expressed as
$$\begin{align}
T&=\sum_{n=3}^\infty 2^n f(2^n)\\\\
&=\sum_{n=3}^\infty 2^n \frac{1}{2^{n\left(1+\frac{1}{\log(\log(2^n)}\right)}}\\\\
&=\sum_{n=3}^\infty 2^{-\left(\frac{n}{\log(n\log(2))}\right)} \tag 2
\end{align}$$
Now, for any $\alpha >0$, the logarithm function satisfies the inequality SEE THIS ANSWER
$$\log(x)\le \frac{x^\alpha -1}{\alpha}\le \frac{x^\alpha}{\alpha} \tag 3$$
Applying $(3)$ to $(2)$ reveals that for $0<\alpha <1$
$$2^{-\left(\frac{n}{\log(n\log(2))}\right)}\le 2^{-\left(\frac{\alpha n^{1-\alpha}}{\log^\alpha(2)}\right)}$$
Thus, the series in $(2)$ clearly converges by the comparison test.  Take for example $\alpha =1/2$.  Then, it is easy to show that
$$2^{-\left(\frac{ n^{1/2}}{2\sqrt{\log(2)}}\right)}\le \frac{48/\log^{3/2}}{n^{3/2}}$$
and the series converges by comparing it to the series $\sum_{n=3}^\infty \frac{1}{n^{3/2}}$.
Finally, the condensation test guarantees that the series in $(1)$ also converges.  And we are done!


text:
Q: Different way of specifying a view in MVC? I am just looking at a code sample and I notice something I have not seen before:
    public virtual ActionResult Index()
    {
        var model = new MenuRatingModel();
        List entries = new List();
        model.ListEntries = new []
                                {
                                    new MenuRatingListEntryModel(),
                                    new MenuRatingListEntryModel(),
                                    new MenuRatingListEntryModel(),
                                    new MenuRatingListEntryModel()
                                };
        return View(Views.Index, model);
    }

Here the developer specifies "Views.Index" in the return. Can someone explain why this is. Would it not be easier just to omit that?

A: I think the developer created some kind of Enum/Const class, where all the names of all the views are stored. The View-method accepts a string for the name of the view you would like to render. A problem with providing a string, is that it is more difficult to refactor and it is more error-prown (i.e. typos). If you may decide to rename a view, you will have to change the name everywhere you use the name of the view.
By creating a static class, you can store all names of the Views in one place. In the case one of the names of a view changes, you will only have to change this in one place.
e.g.
public static class Views
{
    public const string Index = "Index";
    public const string SomeOtherView = "SomeOtherView";
}

A: They could omit that. It looks as they are doing that as a standard wherever so there are no 'magic strings' that could be misspelled. Also you can right click a view and easily find out ALL locations it is referenced which is probably a major reason they did this.