making sure one task completes before another starts in java

Question: Can anyone show me a way to force one task in java to complete before the next task is allows to start?  Specifically, I want to edit the code below so that the first marked two lines of code are completely finished before the next marked two lines are called.
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
      String idString = req.getParameter("id");
      Long id = new Long(idString);
//complete the actions specified on next two lines
      School school = new SchoolDAO().findSchool(id);
      req.setAttribute("school", school);
//before even starting the actions specified on the next two lines
      List<CourseSummary> coursesummaries = new CourseSummaryDAO().findAllcsum(id);
      req.setAttribute("coursesummaries", coursesummaries);

      jsp.forward(req, resp);
}

EDIT:
To better understand Fernando's suggestion, I am including some relevant parts of SchoolDAO as follows:
public class SchoolDAO extends DataAccessObject{
    public School findSchool(Long id) {
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            connection = getConnection();
            String sql = "select * from schoolprog where id=?";
            statement = connection.prepareStatement(sql);
            statement.setLong(1, id.longValue());
            rs = statement.executeQuery();
            if (!rs.next()) {return null;}
            return readSchool(rs);
         }
         catch (SQLException e) {throw new RuntimeException(e);}
         finally {close(rs, statement, connection);}
      }
      private School readSchool(ResultSet rs) throws SQLException {
          Long id = new Long(rs.getLong("id"));
          String spname = rs.getString("spname");
          String spurl = rs.getString("spurl");
          School school = new School();
          school.setId(id);
          school.setName(spname);
          school.setUrl(spurl);
          return school;
      }
}

Similarly, CourseSummaryDAO contains:
public class CourseSummaryDAO extends DataAccessObject{
    public List<CourseSummary> findAllcsum(Long sid) {
        LinkedList<CourseSummary> coursesummaries = new LinkedList<CourseSummary>();
        ResultSet rs = null;
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            connection = getConnection(); //this is the line throwing null pointer error
      String sql = "select * from coursetotals where spid=?";
            statement = connection.prepareStatement(sql);
            statement.setLong(1, sid);
            rs = statement.executeQuery();
      //for every row, call read method to extract column
            //values and place them in a coursesummary instance
            while (rs.next()) {
                CourseSummary coursesummary = readcsum("findAll", rs);
                coursesummaries.add(coursesummary);
            }
            return coursesummaries;
         }
         catch (SQLException e) {throw new RuntimeException(e);}
         finally {close(rs, statement, connection);}
     }

The line where the program is breaking is:
connection = getConnection(); //

Comment: What behaviour are you seeing that makes you think those lines _aren't_ completing first? They must be run before execution reaches the following lines...
Comment: @WilliamMorrison, can you please explain how those 2 lines can be *asynchronous* ? Isn't *java code* inside a function *synchronous* ?
Comment: Who knew a findSchool(id) method could be so complex? ;-)
Comment: @MattR think maybe he means the result of calling those lines is complete, not that the lines are executed.
Comment: You can use a CountdownLatch object. See this question
http://stackoverflow.com/questions/7811681/java-threads-waiting-value
Comment: @MattR Deep in the code, there is a problem with a second database connection not being able to open up because a first connection has not closed.  However, the connections are both explicitly closed in the code.  I think it is just a question of being a few milliseconds too early, and I was hoping there was something at the level listed in this posting that would enable the program to wait until the first tasks completely returned before starting the second tasks.  I am investigating the deeper problem in other ways separately.
Comment: @CodeMed we'd need more information about your classes to help you I think. The code at this level doesn't offer a way to block, or be notified of async operation completion.
Comment: @RaviTrivedi they could kick off a task on another thread for some processing is what I mean. Yes, code inside a function is synchronous, but that code could be doing anything. Including creating threads or submitting tasks for a thread to process.
Comment: @WilliamMorrison, well, isn't that a totally diff Question ? :)
Comment: No. I think this is what he's asking for. A way to ensure some async task (closing the database) is completed before the next lines are executed, right?
Comment: @MattR yeah, it actually performs a parallel search using 8 cores and 10GB RAM on 10 billion entries... except each search is linear... :)
Comment: This task is just a search on the db? what do you mean by 'each search'?
Comment: @Fernando I just added the rest of what I think is the relevant code.
Comment: I guess your getConnection() is the problem now.
Answer: If you have two tasks that should be performed serially (i.e. one finishes before the next one starts) then the best answer is to perform them synchronously.  For instance, suppose that task1() and task2() are the tasks:
// Wrong way:
Runnable r1 = new Runnable(){
    public void run() {
        task1();
    }};
Runnable r2 = new Runnable(){
    public void run() {
        // Wait for r1 to finish task1 ... somehow
        task2();
    }};

// Right way:
Runnable r = new Runnable(){
    public void run() {
        task1();
        task2();
    }};

And in your case, it looks like the doGet call can only return when it gets the result of both tasks.  So that suggests that you shouldn't be using threads at all in this case.  Just call task1() and task2() in sequence ... on the request thread.

EDIT
Looking at the doGet method and the two classes that you added subsequently, it looks like the processing is already sequential / serial.  That is, the first "task" ends before the second "task" starts.
The problem with getConnection() throwing NullPointerException is (most likely) nothing to do with asynchrony.  However I can't be sure of that without seeing the code of getConnection() and the complete stacktrace.
Comment: What if `task1()` is a asynchronous task and you still want `task2()` to start only after `task1()` is completely done with its execution?
Comment: Ask a new question ... providing code that illustrates what you mean by an asynchronous task.
Comment: Thanks for prompt reply. Here's the question --> https://stackoverflow.com/questions/38125689/how-to-make-sure-a-task-starts-its-execution-only-after-a-previous-asynchronous
Answer: In Java, everything is normally executed in order, meaning that a given line of code will completely finish executing before the next line will start to do anything. The exception to this rule is when threads come into play. Threads allow multiple blocks of code to execute simultaneously. Because you aren't using any threads in your program (you'd know if you were, don't worry), it's guaranteed that the first two lines of code will complete before the next two begin to be executed.
So, your problem doesn't seem to be that your code is running "out of order". It's likely that your error is somewhere within the getConnection() method if that's what's throwing the NPE.
Answer: Here's an example (see Java Threads waiting value for details)
import java.util.concurrent.CountDownLatch;

class MyTask implements Runnable
{

    CountDownLatch signal;

    public MyTask(CountDownLatch signal)
    {
        this.signal = signal;
    }

    public void run()
    {
        System.out.println("starting task");
        for (int i = 0; i < 10000000; i++)
            Math.random();

        //call when the task is done
        signal.countDown();
    }
}

public class Program
{
    public static void main(String[] args) {
        int workers = 1;
        CountDownLatch signal = new CountDownLatch(workers);

        new Thread(new MyTask(signal)).start();

         try {
                // Waits for all the works to finish ( only 1 in this case)
                signal.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("task is done");
        }

}

This is just a suggestion, maybe there's a better design:
import java.util.concurrent.CountDownLatch;

public class SchoolDAO extends DataAccessObject implements Runnable {

    Long id;
    CountDownLatch signal;
    School searchResult;

    public SchoolDAO(Long id, CountDownLatch signal)
    {
        this.id = id;
        this.signal = signal;
    }

    public void run()
    {
       searchResult = findSchool(id);
       signal.countDown();
    }

    // the other methods didn't change
}

Now you can call it inside doGet():
CountDownLatch signal = new CountDownLatch(1);
SchoolDAO dao = new SchoolDAO(id, signal);

new Thread(dao).start();
try {
      signal.await();
    } catch (InterruptedException e)
    {
      e.printStackTrace();
    }
 School result = dao.searchResult;

Comment: I seem to have reached a dead end on another java problem.  Do you have a little time to look at it and help me solve it?  I posted it in another question at this link:  http://stackoverflow.com/questions/20307310/beancreationexception-after-adding-two-variables


Can I connect from VS 2015 to VSTS and GitHub the same time?

Question: I have solution in VS, which connected to VSTS to keep repository there. I know I can connect to GitHub from VS, but I want to keep connection to VSTS at the same time.
So I want to publish to both: VSTS and GitHub from VS.
Is it possible?
Or I need to synchronize repositories as described in this answer?
I prefer to do it from VS.
Update: I use git repo in VSTS.
Answer: Refer to these steps to add a new remote in VS 2015.

Connect to your VSTS git repository
Click Settings

Click Repository Settings

Click Add link in Remotes section

After that you can choose a remote repository when you push/sync to remote repository.
Comment: exactly what I wanted
Answer:
Or I need to synchronize repositories as described in this answer?

This is preferable: you can initialize a git repo in your VSTS-managed repo, which means you can use the build phase to check and pull from the Git repo as described in the answer you mention.
That is because, if you chose to connect to connect to a Team Foundation Version Control (TFVC) repo, it cannot be a GitHub repo.
You can use Git and TFVC repos in the same team project, but you would still need build commands to synchronize that repo from GitHub, or configure said Git repo to push to two different upstream (TFVC and GitHub) repos.
Comment: I have got repo in VSTS. How I can configure connection to Github from VS interface, without dropping connection to VSTS?
Comment: @Alex Not sure (beside https://www.visualstudio.com/en-us/docs/git/team-projects which is the opposite). I would simply (in command line) `git init .` and `git remote add origin https://github.com//`
Comment: okay, did it from command line. I just thought it could be easy to do from VS.
Comment: @Alex " I just thought it could be easy to do from VS": not to my knowledge.


Extend XHTML with namespaces

Question: I've seen this somewhere, but I don't remeber the page.
I'd like to extend the HTML tags, so then I can add my own attributes to the HTML elements, I saw a example where the developer added a new xmlns to the page definition, so he could add new things and still be a valid XHTML.
What is the name of this technique and where could I find information about it?
Cheers.
PS: Or maybe I've dreamed this? :D
Answer: Here is an article on this topic. However it would not be "valid" as XHTML is part of a international standard.
Comment: It's valid if it validates against the XHTML schema. That is what validity means in XML.
Comment: I am referring to the W3C validation.
Comment: D'oh!! The website has to be W3C compilant, so I cannot use this then :(  Thanks very much!
Comment: W3C, World Wide Web Consortium (W3C) develop and maintain the standards that we all use for HTML and CSS. These standard defines how things should work, and with HTML and CSS how browsers (should) render the tags. While adding a namespace and your own tags may be structurally valid, it is not recognized as valid by the W3C and therefore browsers may have issues.

Extend XHTML with namespaces


Update the SQL column based on filter of another column?

Question: I am stuck in a SQL query. I want to update the column STATUS using sql query.
The exact requirement is I have a SQL table as follows.
_____________________________________________
start_date          end_date        status
---------------------------------------------
2014/01/03      |   2018/01/03  |   FAILED
2016/12/15      |   2017/01/03  |   SUCCESS
2014/01/03      |   2010/01/13  |   FAILED
2017/10/23      |   2017/01/03  |   FAILED
2014/01/03      |   2011/01/03  |   FAILED
2017/11/13      |   2017/01/03  |   SUCCESS
---------------------------------------------

In the above table, I have start_date, end_date and status.
Now I want to update the status from "FAILED" to "SUSPEND" where the end_date is the oldest one among all the dates and start_date is same but end_date is different. (Here only one row will be updated as showing in the below table)
I am trying to build a query but unable to fetch the required result.
after applying a correct query, the table should look like as follows.

start_date          end_date        status
---------------------------------------------
2014/01/03      |   2018/01/03  |   FAILED
2016/12/15      |   2017/01/03  |   SUCCESS
2014/01/03      |   2010/01/13  |   SUSPEND
2017/10/23      |   2017/01/03  |   FAILED
2014/01/03      |   2011/01/03  |   FAILED
2017/11/13      |   2017/01/03  |   SUCCESS
---------------------------------------------

Can anyone please help me in this.
Thanks in Advance.
Comment: Is there any PK in this table ? This looks like a bad design. What is the purpose of this table ?
Comment: "the end_date is the oldest one and start_date is same but end_date is different." what's the meaning of this sentence? start_date > end_date?
Comment: No there is no PK in the table. this is a sample table actual table has the huge amount of data and many columns.
Comment: @ZhongWang it means there are multiple end date but I want to update only that STATUS where end date is oldest among all dates.
Comment: Hi, I edited my question for better understanding.
Comment: @JayeshVyas what is the datatype for your start_date and end_date columns. It seems they are not `date` type, instead `varchar`
Comment: @MadhurBhaiya  I am using date as datatype for both dates.
Answer: You could use an update using a where clause. I didn't understand what you mean with and start_date is same but end_date is different, so i didn use it.
UPDATE table1
SET status='SUSPEND'
WHERE status='FAILED' and end_date<start_date

Comment: thanks for ur quick response but I want to update only that particular row where status is FAILED and end date is the oldest one (plus I have to identified that how many rows has the same start dates.)
Answer:
In a Derived Table, get minimum value of end_date for a group of start_date.
Join it your main table based on start_date and min_end_date.
Update status accordingly.

Try the following in MySQL (DB Fiddle):
UPDATE your_table AS t1
JOIN (SELECT start_date,
             MIN(end_date) AS min_end_date
      FROM your_table
      GROUP BY start_date) AS t2 ON t2.start_date = t1.start_date AND
                                    t2.min_end_date = t1.end_date
SET t1.status = 'SUSPEND'
WHERE t1.status = 'FAILED'

Comment: hey madhur it is giving error.                                                                                Error at Command Line:52 Column:15
Error report:
SQL Error: ORA-00971: missing SET keyword
00971. 00000 -  "missing SET keyword"
Comment: @JayeshVyas are you using MySQL or Oracle Database (PL/SQL) ? It looks like you are definitely not using MySQL
Comment: I am using Sqldeveloper not PL/SQL
Comment: @JayeshVyas why did you tag this question as MySQL  ? My Solution works for MySQL. Oracle , MySQL, SQL Server etc are all different RDBMS and have different syntax at times. Anyways, I am editing answer to add solution for Oracle also.
Comment: @JayeshVyas please join me in chat here: https://chat.stackoverflow.com/rooms/181674/room-for-madhur-bhaiya-and-jayesh-vyas
Answer: Whatever the logic Madhur told is correct except a functional bug. Since you were asking for oldest.. We should query using MIN instead of MAX as below
UPDATE your_table AS t1
JOIN (SELECT start_date,
             MIN(end_date) AS max_end_date
     FROM your_table
     GROUP BY start_date) AS t2 ON t2.start_date = t1.start_date AND
                                    t2.max_end_date = t1.end_date
SET t1.status = 'SUSPEND'
WHERE t1.status = 'FAILED'


Can I see which Games With Gold games for Xbox One I've acquired, without an Xbox One?

Question: I don't have an Xbox One, but I do have an Xbox 360 and an Xbox Live Gold account. Every month since it began, I've been collecting the Games with Gold for both platforms on the off-chance that I eventually upgrade to an Xbox One.  But so far, of course, I've never downloaded any of the XB1-only titles.
I can easily check which Xbox 360 games I've acquired this way, including any that haven't actually downloaded yet, via the Download History page on the Xbox Live website. But this only shows Xbox 360 and PC titles. Is there any similar way to see what Xbox One games I've acquired, without having any access to an Xbox One?
Answer: From that download link you have in your question, on the top right of the page you will see "My Xbox."  Click it, and select "My Games."  This will show you all the games you own for both Xbox One, and Xbox 360.  For you, all your Xbox One games should only be the Games with Gold games since that's all you've ever purchased.
Comment: D'oh, can't believe I've never noticed that before. Thanks.


how to get tar.tgz inside sub directory size without extract?

Question: Iam able to get inside content from tar.tgz file without extract file. but file size is very high so can't extract it on server.i need to get all sub directory size human readable formate from tar.tgz file without extract it.
Answer: I think the more convenient for you will be to us mc.
mc - Midnight Commander is a clone from norton utilities.
Is a text console based utility that will allow you to browse your .tar.gz , then select the files or folders you want to restore (Key Insert over the file you want) then copy.
With Key Tab you switch from one side and the other. Normally I use the left for source and the right side for target destination.
So on the left browse to your .tar.gz file with the arrow Keys, and where you are over it press Enter. It will start opening the file. If it is very big you will need time. For 1GB it took 10 seconds on my system.
Once it is opened, browse to the selected destination with the arrow Keys, press Insert Key to mark what you want to copy, and press F5 to copy to the other side.
The line in the bottom shows what action is done by each F key. F6 RenMov, F7 Mkdir....
To exit, if F10 is intercepted by the Terminal, type exit and Enter.
I created a tar.gz in my Workstation to show you:

However you do need the free space on the computer browsing.


Fabric JS how to address a SVG

Question: I have loaded a SVG on the canvas. Everything works, but I have difficulties to address the object.
Here is the code:
fabric.loadSVGFromURL("images/Achse3.svg",function(objects)
  {

          var achse1 = new fabric.PathGroup(objects, {
            left: 127,
            top: 70,
            opacity: 0.5,
            scaleX: 1.25,
            scaleY: 1.25
          });

          canvas.add(achse1);
      //canvas.renderAll();
  });

I tried to address the SVG via canvas.item, but the results are very strange. Depending on the value in the sample:
canvas.item(11).set('top',this.value);

The items change. How can I address the item I loaded. I tried it with
canvas.achse1.set('top',this.value);

But this is not working.
Answer: Since you have a reference to your PathGroup, you have just to set the related properties of it.
Try yourself the runnable snippet below if it meets your needs.

var canvas = new fabric.Canvas('c'), svg_group;

fabric.loadSVGFromURL("https://upload.wikimedia.org/wikipedia/commons/a/a9/Olympic_rings_with_white_rims.svg", function(objects) {

  svg_group = new fabric.PathGroup(objects, {
    left: 0,
    top: 0,
    opacity: 1,
    scaleX: .1,
    scaleY: .1
  });

  canvas.add(svg_group);
  $('#b').on('click', () => {
    svg_group.set('top', 100);
    canvas.renderAll();
  })
});
canvas {
  border: 1px dashed #333;
}

<canvas id='c' width=300 height=150></canvas>
<button id='b'>move it</button>
Comment: Hi, I´m sorry, but this is not working form me. Maybe it is related to the variable declaration within the loadSVGfromUrl function.
Answer: Found the problem. I used VAR to declare the variable within the loadSVG function. So the variable was just local within the function. The declaration without VAR did the job. Now the variable is global and can be addressed from outside the function.

Fabric JS how to address a SVG


dismissViewControllerAnimated: completion: has no effect

Question: Has anyone seen this before?  In the iPad simulator, I have an About view controller.  I want to present it modally, and have the user click a close button.
To complicate it a bit, I have a main View Controller, that presents an iAd banner and a "Main Menu" view controller.  The button is on the main menu, and so the IBAction is sent to the Main menu view controller.
In the Main Menu VC, I have a property pointing to the app View Controller, so I call:
AboutViewController *about = [[AboutViewController alloc] initWithNibName:....];
about.callingViewController = viewController;
[viewController presentViewController:about animated:YES completion:nil];

So then in the About View Controller, I have an IBAction that dismisses it:
- (void) dismissAbout:(id)sender
{
    [callingViewController dismissViewControllerAnimated:YES completion:nil];
}

When the dismissAbout is called, nothing happens - the view doesn't go away, and no output in the debugger console.  Any ideas?
Answer: I think you need to call
[self dismissViewControllerAnimated:YES completion:nil];

instead.
Answer: IBAction should be
- (IBAction) dismissAbout:(id)

secondly you are dimissing the aboutController so should use self instead of callingViewController
Comment: Also @ssantos, that was it, I had to message self.  (The .h declares dismissAbout as IBAction, while the .m declares it as void.  IBAction is an alias for void.)
Answer: As the other answers say, you can use [self dismiss...] because that message is automatically forwarded to the presenting view controller. You also could use [self.presentingViewController dismiss..] because a modal controller has a presentingViewController property that points to the view controller that presented you. There's no need to create and pass the callingViewController.


how can I call my method child to inside my function?

Question: I am trying to send my src_path file to my functionlazy_ass, and then back to on_created but I got  TypeError: lazy_ass() missing 1 required positional argument: 'event' , how can I improve it to call like this?
class updater(FileSystemEventHandler):
    def __init__(self, src_path):
        super().__init__()
        self.last_modified = datetime.now()
        self.__src_path = src_path
        self.__event_observer = Observer()

    def on_created(self, event):
        if datetime.now() - self.last_modified < timedelta(seconds=1):
            return
        else:
            self.last_modified = datetime.now()
            print(f"hey, {event.src_path} has been created!")
            self.lazy_ass()

    def lazy_ass(self, event):
            print(f"github {event.src_path}!")

Comment: You seem to have several methods, but I don't see any class.
Comment: yes, they are inside a class called `updater`
Answer: You should delete your event parameter if you are not using it, however, if you want it to be a placeholder (eg. for future use), you can try def lazy_ass(self, event=None): (See document about default argument here)
Answer: You've called self.lazy_ass() inside instance method on_created. So that lazy_ass can access all instance properties, so your function will look like this:
def lazy_ass(self):
    print(f"github {self.__src_path}!")

This code removed event because you're not passed any event when you call self.lazy_ass() that lead you to this error: TypeError: lazy_ass() missing 1 required positional argument: 'event'. Secondly, you can access to __src_path (which you set from __init__ method) inside lazy_ass method.


Is there a way to determine how much money you have above $10,000,000?

Question: After your bank exceeds $10,000,000 the cash display in your inventory just stays maxed out at $9,999,999.  Many high-level items even have their prices displayed as $9,999,999.  Is there any practical way to determine the actual amount these displays represent?
Note:  I'm asking as a player on a PS3 - cheats or other methods specific to the PC are of no use to me.
Answer:
Players wishing to know exactly how much money their characters have (and who don't mind losing 7% of it) can calculate this from the death of their characters. The 7% that the character lost will be displayed on the left of the screen along with the New-U message. The character's money before the reconstruction can be calculated as follows: money = fee / 7 * 100.

Borderlands Wikia entry on Money
Comment: This is a way (It's arguable whether or not it's a *good* way) to figure out how much you have on-hand - but how do you figure out the actual price of items listed at $9,999,999?
Comment: Note the 7% loss isn't as bad as it sounds, if you play long enough you'll eventually get to an Overflow in your money counter which will reset your money to $0
Answer: Only Suitable for PC
If you have a mod program installed, such as Willow Tree this program reads your saved games and displays the correct full amount of money along with a pile of other information and tweaks you can perform on your character and inventory.
Please remember this is somewhat a mod, and all mods are not guaranteed to work and may corrupt your game save, so back up!
EDIT: question re-tagged, this answer is only viable for PC versions of Borderlands.


SES PHP newsletter cronjob mail sending loop

Question: I just started Amazon SES and successfully configured. Actually I purchased for sending news letter as well as member status for my site.
My Site contains about 18000 Users. I want to run a cron job every saturday evening and send them the newest updations and their current status.
Can I fulfil the requirement with Amazon SES ?
Any problem if I looped these users in a mail query ? As I am a new bee to this , any one can please help ?
Answer: well it depends. As a new user to ses, i noticed that you are allow to send 10k emails per 24 hours. you have 18k. Could problem yes.
I tried once by sending 5k emails and i got time out issue with php. So i think you need to split 18k into small portion i guess...


HP printer ( LaserJet Pro MFP M125nw)

Question: I have this information of my system:
OS:  Netrunner 14
System:  Linux 3.13.0-44-generic i686
KDE:  4.13.3

I bought yesterday printer from HP ( LaserJet Pro MFP M125nw)
I know from the beginning this HP type is already configured  with my system , No need to install the package of HP .
So, when I plug the USP cable to my PC It gives me a massage that the printer has been configured . but When I try to print any pages or test paper ...It's not printing at all ..
So could any one help me to solve this problem
thanks a lot
oudai ,,
Answer: I have the same printer and Ubuntu 14.04, and I was also wondering why the test page won't get printed, even though the set-up seemed to be successful.
After a while I recognized that the system couldn't auto-install a proprietary plug-in for the driver, but it is fairly easy to install with the pre-installed tool hplip. Just type the command hp-setup and follow the instructions.
It should be quite straight forward, but you can find more information here:
http://hplipopensource.com/hplip-web/support.html
Comment: Same as m125a, run `hp-setup` to install and it works well.

HP printer ( LaserJet Pro MFP M125nw)


How can i get the full, sequenced call stack of an ASP.NET request?

Question: I'm trying to hunt down some performance issues in my ASP.NET (Nancy, OWIN/System.Web hosted) app.
Through profiling, (namely Stackify tools), i've noticed some 'gaps' at the end of certain requests, that aren't non-obvious calls (e.g not Database, HTTP, Redis, etc).
Here's an example: (taken from Stackify's Prefix tool)

Summary:

Request took 1289ms
'Most' (hot path) was taken by a SQL query. (i'm fine with this for now, could be optimized but is not the focus of this question)
Couple of 'Untracked Application Code' gaps, taking over 500ms.

Particulary, the last gap (340ms) i've seen a lot and is the focus of my investigations.
Prefix allows custom code configuration that allows to get more info on these 'gaps' by whitelisting an assembly, but the problem is i don't know which assembly this time is being spent. My gut feeling is Nancy/OWIN/some dependency injection lib, etc. (i've tried whitelisting all of these, to no avail). I just know it's not my immediate code in this URL.
So my questions are:

Any ideas on how i can find out the full and ordered call stack of this request, to then use as whitelisting for Prefix? Tools i can use?
Any 'left of centre' ideas on how to track down this gap? Another tool instead of Prefix that tells me where time is spent?

Thanks!
Comment: Have you got any idea how to resolve "Untracked Application Code" delay problem?
Answer: You can set up custom .Net code profiling, both for Prefix and for Retrace, by creating a JSON file containing the classes and methods that should be profiled in JSON format (wildcard characters are allowed).
See this article
https://dzone.com/articles/troubleshooting-percona-monitoring-and-management
As well as
 https://support.stackify.com/custom-profiling-configure-for-net/


Scala: Function0 vs by-name parameters

Question: Can anyone give a definitive answer on how by-name parameters => T and Function0 parameters () => T are transformed into one another by the Scala compiler? I know they are not the same, but the difference is very subtle as they can be interchangeably used in many scenarios.
Example: if I define
def someFunction: Int = 2
def f(x: => Int): Unit = println(x)

then I can successfully call
f(2)
f(someFunction)

How is () => Int an acceptable replacement for => Int?
More generally, is () => T a universally acceptable replacement for a by-name => T parameter?
Also, please correct me if I'm wrong on the following reasoning: => T is never an acceptable replacement for () => T because the first is a value type (T), the other is a function type. That is, if I have def f(x: () => Int), I'll never be able to pass an Int, or a lazy Int (doesn't even make sense anyway as there are no lazy types).
Comment: Your examples are definitely *not* equivalent. The first one produces a `Try[() ⇒ Int]`, the second one a `Try[Int]`. Your function argument of type `() ⇒ Int` gets converted to `⇒ T` with `T` being `() ⇒ Int`.
Comment: Some good info here: https://tpolecat.github.io/2014/06/26/call-by-name.html
Comment: They do not replace each other and they are not transformed into one another by the Scala compiler. They are simply different things and usually serve different purposes.
Comment: @Jean-PhilippePellet point definitely taken, you're right. Changed my example to accommodate.
Comment: In you updated example, `someFunction` is _not_ a function. If it _were_ a function then `f(someFunction)` would not compile.
Comment: If I `def someFunction(): Int = 2` the code still compiles with the note that the compiler actually interprets `f(someFunction)` as `f(someFunction())`.
Comment: But `def someFunction(): Int = 2` is not a function.  It is a method. Methods can be turned into functions but they are not the same thing. Try this `val realFunc = someFunction _` then you'll have a real function and you'll see that `f(realFunc)` won't compile.
Comment: @webuster Hi, is this resolved?
Answer: Alright, here's the full breakdown.
def value: Int = ???
def method(): Int = ???

def f1(f: () => Int) = ???
def f2(f: => Int) = ???

f1(value)  // fails
f1(method) // works
f2(value)  // works
f2(method) // works with a warning "empty-paren method accessed as parameterless"

f1(value)

This one fails because f1 is expecting a Unit => Int function, but is given an Int value.

f1(method)

This one works because f1 is expecting a function, and is given a method. Here's the difference: method is not a value in Scala; it cannot exist on its own and is an attribute of the context it's defined in (class, trait, object etc.). Function is a value; it can be kept in a collection, taken as argument in another function, returned from a function etc. When the compiler is expecting a function and is given a method, it performs eta expansion. Given a function e.g. f: (a: Int, b: Int) => Int, eta expansion is a process of creation of another layer around that while preserving the signature, so it becomes (a: Int, b: Int) => f(a, b). This technique is useful because we can turn methods into function. Given some method def f(a: Int): Int = ???, we can perform eta-expansion to create a function of type Int => Int out of it: (a: Int) => f(a). I wrote a blog post about this some time ago if you're interested.

f2(value)

Works without surprises, but pay attention to the fact that the passed value is accessed every time it's used in the function body.

f2(method)

Works, but with a warning that we are invoking a method that is defined with empty parenthesis by using no parenthesis. Good practice is to use methods without parenthesis (e.g. f) when they simply represent a value, but one that is recalculated every time it's accessed, e.g. numberOfUpvotes, and to use methods with empty parenthesis (e.g. f()) when some kind of side-effect is performed and hence the method isn't idempotent, e.g. createSnapshot() (again, this should not be present in purely functional code).
Word of advice: don't encumber your mind with what's a replacement for what. Don't use replacements. If something needs a function, provide it a function. If it needs a value, provide a value. If a method is defined without parens, invoke it without parens. If it has parens, invoke it with parens.
If you need to go from method to function and compiler is expecting a function, eta-expansion will happen automatically. If it's not expecting a function, you need to do it manually.
def f(): Int = ???
val a = f               // no function context; a is a string
val b: () => Int = f    // b is a function Unit => Int
val c = f2 _            // c is a function Unit => Int

Last case is a partially applied function. I feel like I'm going too broad now so I will stop here. I hope this helped.

Scala: Function0 vs by-name parameters


How do I know when to switch to a finer grit when polishing marble?

Question: I am polishing a marble shelf with pads impregnated with a resin containing diamond powder (it has some advantages over sandpaper, but otherwise works in a similar way). I used grit 50 to remove scratches and stopped when I couldn't see any more scratches.
Then I use grit 100, 200, 400, 800 (maybe more) to get a nice polish. But it's hard to tell the difference before and after grit 400 (for instance) by touching or looking. How do I tell I've spent enough time with this grit and I should switch to the next, finer one (in this example, grit 800)?
The final step will be a sealer.
Answer: I would suggest that to get a really smooth polish you will be using sand paper or polishing pads with grit numbers as fine as 3000 or more. The general advice is to switch to the next finer grit when you no longer see any remaining grooves or roughness left by the previous grit.
You may need to experiment with looking at the area that you are polishing carefully to see how it is coming along. It will certainly be necessary to really clean up the area and remove all the dust and particulate that you have created. A bright light shining on the surface that you then look at from an oblique angle can help you to see the fine details. If you are using the dry polishing technique it may be useful to wet the surface to see how your work area compares to other parts of the marble that were previously polished.
Comment: Thanks. Indeed, this is the advice I got from the vendor: polish just enough to remove the scratches from the previous grit. But on a large area, it's difficult to remember the scratch pattern. Plus, it becomes invisible as soon as the marble is wet (which is better for the disks), so it would be tedious to dry it often. I'm experimenting with various polishing times, and maybe my criterion will be time-based rather than "scratch-based"...
Answer: I found some use in having a predictable pattern, for instance move from left to right (and back) with a grit, then with the next one move from top to bottom until on doesn't see any left/right grooves.


How do I create a command to make me stay at one stack of an item?

Question: I would like to make a command that keeps me at one stack of arrows.
How can I do this?
Comment: Is this for a map? Creative mode? Have you tried anything?
Answer: 1. CommandStats
Using CommandStats allows you to detect the number of specific items in a player's inventory no matter how they are arranged. This both allows you to accurately provide arrows until they reach exactly 64 as well as remove arrows if they have more than 64.
Prerequisites
Objective to hold the number of relevant items.
/scoreboard objectives add ArrowCount dummy

"AffectedItems" CommandStat trigger to apply to players, who will target their own "ArrowCount" score. This may need to run on a clock if new players may join at any time.
/stats entity @a set AffectedItems @a[c=1] ArrowCount

In order for CommandStats to modify a target's score, that target must be tracked prior. This may also need to run on a clock for the same reason.
/scoreboard players add @a ArrowCount 0

Clock commands
The following must be run in numerical order on a clock.

Cause players to run a /clear command that looks for a specific item. The maximum amount is set to 0, which means no items will be removed but the "AffectedItems" trigger will be sent the total number of that item the player has in their inventory. You can add to this command to look for an exact arrow rather than generic arrows.
/execute @a ~ ~ ~ /clear @a[c=1] minecraft:arrow 0 0

Players that have 63 or fewer arrows will be given a new arrow.
/give @a[score_ArrowCount=63] minecraft:arrow

Players with 65 or more arrows will have the extra arrows removed.
/clear @a[score_ArrowCount_min=65] minecraft:arrow 0 1

The final result is the player never having more or less than 64 of that specific arrow in their inventory.
2. Statistics
The stat.useItem.bow objective-type will increase when the bow is used, and you can use that to provide the player with the appropriate number of arrows.
/scoreboard objectives add UseBow stat.useItem.minecraft.bow

And the following would run in numerical order on a clock.

Provide relevant players with an arrow after they have used their bow.
/give @a[score_UseBow_min=1] minecraft:arrow

Reduce their "UseBow" score by 1.
/scoreboard players remove @a[score_UseBow_min=1] UseBow 1

The downside is you will not be able to differentiate between special arrows that have been removed, such as tipped arrows, and normal arrows. As well, the player can pick up more than the allotted 64 arrows since this only provides new arrows rather than removing extra.
Answer: Simply put the following commands in a repeat/chain command block line:
/scoreboard players tag @a[tag=arrows] remove arrows
/scoreboard players tag @a[tag=!arrows] add arrows {Inventory:[{id:minecraft:arrow,Count:63}]}
/give @a[tag=arrows] minecraft:arrow

Note that you must start off with either 63 or 64 arrows for this command to work.
Comment: Be aware that this requires all arrows to be within the same stack. If the player spreads the arrows out in such a manner that they will never have exactly 63 in a stack, the mechanism will fail.
Comment: @Skylinerw The question said `keep me at **one** stack of arrows` so I assumed that they would all be in the same stack.
Answer: Set a command block to (clock)
testfor @e[type=arrow,r=radiusInBlocks]

then have a comparator going out of it connecting to two command blocks (needs redstone) with
give player minecraft:arrow

and after some delay...

kill @e[type=arrow]

Then if you start with 64 arrows, you shoot one, you gain one! :D
Comment: This solution does not work at all with multiplayer, or when you expect another user is going to use your map.
Comment: Also, this won't work for more arrows shot!
Comment: Sorry let me edit this...


Concurrency issue when loading satellite assembly?

Question: In our CI, we sometimes get the following error:
System.IO.FileNotFoundException : Could not load file or assembly '<our-assembly-name>.resources, Version=22.214.171.124, Culture=en-US, PublicKeyToken=null'. The system cannot find the file specified.
    at System.Reflection.RuntimeAssembly.InternalLoad(ObjectHandleOnStack assemblyName, ObjectHandleOnStack requestingAssembly, StackCrawlMarkHandle stackMark, Boolean throwOnFileNotFound, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly)
    at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, RuntimeAssembly requestingAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
    at System.Reflection.RuntimeAssembly.InternalGetSatelliteAssembly(CultureInfo culture, Version version, Boolean throwOnFileNotFound)
    at System.Reflection.RuntimeAssembly.GetSatelliteAssembly(CultureInfo culture, Version version)
    at System.Reflection.RuntimeAssembly.GetSatelliteAssembly(CultureInfo culture)

So far we've never seen this exception in production or on a local development machine. It only occurs on the CI during test execution (using dotnet test with xunit as testing framework and mcr.microsoft.com/dotnet/sdk:5.0.401 as base image). Since we see this error only now and then and most of the tests run in parallel, so I'm led to believe that this might be a concurrency issue.
Does anybody have an idea what would be the cause of (and thus also the remedy for) this?
Some context: what we are trying to achieve in our code is to get the stream for a localized resource. So we are doing something like:
var assembly = Assembly.GetExecutingAssembly()
    .GetSatelliteAssembly(CultureInfo.CreateSpecificCulture(language)); // this sometimes crashes
using (Stream stream = assembly.GetManifestResourceStream(resourceName))  { ... }

where language in this case is "en-US".
Comment: If you're running multiple `dotnet test` instances in parallel, you might need to add the `--no-build` option, to prevent that you have parallel builds at the same time as parallel test runs.
Comment: @PMF unfortunately, I'm not. I'm first doing a `dotnet build` followed by a `dotnet test ` and there-in, the error is thrown.
Comment: Hmm, still I would try whether `--no-build` fixes the issue. You don't need to (attempt to) build a second time.
Answer: It seems that the culprit was a test that was using the Buildalyzer.Workspaces package (v3.2.3) which in turn uses Roslyn (Microsoft.CodeAnalysis.CSharp.Workspaces) to compute certain code statistics.
I've noticed a crash of the test host in that test and so I've decided to disable it for the time being. Since then, we also haven't seen the satellite assembly look-up raise a FileNotFoundException anymore. I'm assuming that somehow the "parallel build" that Roslyn does interfered with the running tests.
I don't have a proof for this but this is what the experience shows. Also, if a activate the test again, other sporadic problems start showing up again (including the FileNotFoundException). It seems to me that the Roslyn packages shouldn't necessarily be executed in parallel as part of a testing suite.


Wifi slow, temporarily fixed by resetting the connection

Question: I've got a fresh install of ubuntu on a desktop with this Gigabyte wifi card plugged into it. The default ubuntu driver seems to be working for it, which is good because I couldn't find proprietary Gigabyte linux drivers. However, the speed is tremendously random, and will often shoot down to the ~.2mbps range until I disable and then enable wifi.
I've found a great many answers similar to this but as the range of wifi issues is large, I've been avoiding answers that involve for example removing modules and etc. What can I start investigating to find the root of this issue specific to my machine/build and then solve it?
Details
OS: Ubuntu 16.04 LTS
Memory: 15.6GiB
Processor: Intel® Core™ i5-6500 CPU @ 3.20GHz × 4
Graphics: GeForce GTX 1060 6GB/PCIe/SSE2
OS type: 64-bit
Disk: 14.1GB

sudo lshw -class network
*-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: enp3s0
       version: 15
       serial: 38:d5:47:14:2a:9b
       size: 10Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl8168h-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=MII speed=10Mbit/s
       resources: irq:123 ioport:d000(size=256) memory:f7204000-f7204fff memory:f7200000-f7203fff
  *-network
       description: Wireless interface
       product: Wireless 8260
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:05:00.0
       logical name: wlp5s0
       version: 3a
       serial: 44:85:00:7a:b4:94
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=4.4.0-53-generic firmware=16.242414.0 ip=10.0.0.37 latency=0 link=yes multicast=yes wireless=IEEE 802.11abgn
       resources: irq:129 memory:f7100000-f7101fff

lspci
00:00.0 Host bridge: Intel Corporation Sky Lake Host Bridge/DRAM Registers (rev 07)
00:01.0 PCI bridge: Intel Corporation Sky Lake PCIe Controller (x16) (rev 07)
00:14.0 USB controller: Intel Corporation Sunrise Point-H USB 3.0 xHCI Controller (rev 31)
00:16.0 Communication controller: Intel Corporation Sunrise Point-H CSME HECI #1 (rev 31)
00:17.0 SATA controller: Intel Corporation Sunrise Point-H SATA controller [AHCI mode] (rev 31)
00:1c.0 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #5 (rev f1)
00:1c.7 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #8 (rev f1)
00:1d.0 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #9 (rev f1)
00:1d.1 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #10 (rev f1)
00:1f.0 ISA bridge: Intel Corporation Sunrise Point-H LPC Controller (rev 31)
00:1f.2 Memory controller: Intel Corporation Sunrise Point-H PMC (rev 31)
00:1f.3 Audio device: Intel Corporation Sunrise Point-H HD Audio (rev 31)
00:1f.4 SMBus: Intel Corporation Sunrise Point-H SMBus (rev 31)
01:00.0 VGA compatible controller: NVIDIA Corporation Device 1c03 (rev a1)
01:00.1 Audio device: NVIDIA Corporation Device 10f1 (rev a1)
02:00.0 Non-Volatile memory controller: Intel Corporation Device f1a5 (rev 03)
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 15)
05:00.0 Network controller: Intel Corporation Wireless 8260 (rev 3a)

rfkill list all
0: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

EDIT: Using an ubuntu forums script, I have output:
Booted last: 20 Dec 2016 00:00 PST -0800

Script from: 08 Jul 2016 02:16 UTC +0000

##### kernel ############################

Linux 4.4.0-53-generic #74-Ubuntu SMP Fri Dec 2 15:59:10 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Parameters: ro, quiet, splash, vt.handoff=7

##### lsmod #############################

eeepc_wmi              16384  0
asus_wmi               28672  1 eeepc_wmi
sparse_keymap          16384  1 asus_wmi
iwlmvm                311296  0
mac80211              737280  1 iwlmvm
iwlwifi               200704  1 iwlmvm
cfg80211              565248  3 iwlwifi,mac80211,iwlmvm
mxm_wmi                16384  1 nouveau
wmi                    20480  3 mxm_wmi,nouveau,asus_wmi
video                  40960  3 i915_bpo,nouveau,asus_wmi

##### interfaces ########################

auto lo
iface lo inet loopback

##### ifconfig ##########################

enp3s0    Link encap:Ethernet  HWaddr <MAC 'enp3s0' [IF1]>
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

wlp5s0    Link encap:Ethernet  HWaddr <MAC 'wlp5s0' [IF2]>
          inet addr:10.0.0.37  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: fe80::5c72:ba8d:7aad:c70b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:27624 errors:0 dropped:0 overruns:0 frame:0
          TX packets:22794 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:28624912 (28.6 MB)  TX bytes:4181896 (4.1 MB)

##### iwconfig ##########################

lo        no wireless extensions.

enp3s0    no wireless extensions.

wlp5s0    IEEE 802.11abgn  ESSID:"Speedy Remember Harambe"
          Mode:Managed  Frequency:5.765 GHz  Access Point: <MAC 'Speedy Remember Harambe' [AC1]>
          Bit Rate=585.1 Mb/s   Tx-Power=22 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=40/70  Signal level=-70 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:57   Missed beacon:0

##### route #############################

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.0.0.1        0.0.0.0         UG    600    0        0 wlp5s0
10.0.0.0        0.0.0.0         255.255.255.0   U     600    0        0 wlp5s0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlp5s0

##### resolv.conf #######################

nameserver 127.0.1.1

##### network managers ##################

Installed:

    NetworkManager

Running:

root       774     1  0 11:12 ?        00:00:01 /usr/sbin/NetworkManager --no-daemon

##### NetworkManager info ###############

GENERAL.DEVICE:                         wlp5s0
GENERAL.TYPE:                           wifi
GENERAL.NM-TYPE:                        NMDeviceWifi
GENERAL.VENDOR:                         Intel Corporation
GENERAL.PRODUCT:                        Wireless 8260
GENERAL.DRIVER:                         iwlwifi
GENERAL.DRIVER-VERSION:                 4.4.0-53-generic
GENERAL.FIRMWARE-VERSION:               16.242414.0
GENERAL.HWADDR:                         <MAC 'wlp5s0' [IF2]>
GENERAL.MTU:                            0
GENERAL.STATE:                          100 (connected)
GENERAL.REASON:                         0 (No reason given)
GENERAL.UDI:                            /sys/devices/pci0000:00/0000:00:1d.1/0000:05:00.0/net/wlp5s0
GENERAL.IP-IFACE:                       wlp5s0
GENERAL.IS-SOFTWARE:                    no
GENERAL.NM-MANAGED:                     yes
GENERAL.AUTOCONNECT:                    yes
GENERAL.FIRMWARE-MISSING:               no
GENERAL.NM-PLUGIN-MISSING:              no
GENERAL.PHYS-PORT-ID:                   --
GENERAL.CONNECTION:                     Speedy Remember Harambe
GENERAL.CON-UUID:                       3f8fe005-bc76-4f14-a20a-4b9ff06d353f
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/4
GENERAL.METERED:                        no (guessed)
CAPABILITIES.CARRIER-DETECT:            no
CAPABILITIES.SPEED:                     585 Mb/s
CAPABILITIES.IS-SOFTWARE:               no
WIFI-PROPERTIES.WEP:                    yes
WIFI-PROPERTIES.WPA:                    yes
WIFI-PROPERTIES.WPA2:                   yes
WIFI-PROPERTIES.TKIP:                   yes
WIFI-PROPERTIES.CCMP:                   yes
WIFI-PROPERTIES.AP:                     yes
WIFI-PROPERTIES.ADHOC:                  yes
WIFI-PROPERTIES.2GHZ:                   yes
WIFI-PROPERTIES.5GHZ:                   yes
CONNECTIONS.AVAILABLE-CONNECTION-PATHS: /org/freedesktop/NetworkManager/Settings/{0}
CONNECTIONS.AVAILABLE-CONNECTIONS[1]:   3f8fe005-bc76-4f14-a20a-4b9ff06d353f | Speedy Remember Harambe
IP4.ADDRESS[1]:                         10.0.0.37/24
IP4.GATEWAY:                            10.0.0.1
IP4.ROUTE[1]:                           dst = 169.254.0.0/16, nh = 0.0.0.0, mt = 1000
IP4.DNS[1]:                             10.0.0.1
DHCP4.OPTION[1]:                        requested_routers = 1
DHCP4.OPTION[2]:                        requested_domain_search = 1
DHCP4.OPTION[3]:                        requested_time_offset = 1
DHCP4.OPTION[4]:                        requested_domain_name = 1
DHCP4.OPTION[5]:                        requested_rfc3442_classless_static_routes = 1
DHCP4.OPTION[6]:                        requested_broadcast_address = 1
DHCP4.OPTION[7]:                        requested_netbios_scope = 1
DHCP4.OPTION[8]:                        requested_wpad = 1
DHCP4.OPTION[9]:                        next_server = 0.0.0.0
DHCP4.OPTION[10]:                       expiry = 1482349114
DHCP4.OPTION[11]:                       requested_interface_mtu = 1
DHCP4.OPTION[12]:                       requested_subnet_mask = 1
DHCP4.OPTION[13]:                       dhcp_lease_time = 86400
DHCP4.OPTION[14]:                       dhcp_message_type = 5
DHCP4.OPTION[15]:                       ip_address = 10.0.0.37
DHCP4.OPTION[16]:                       requested_static_routes = 1
DHCP4.OPTION[17]:                       requested_domain_name_servers = 1
DHCP4.OPTION[18]:                       routers = 10.0.0.1
DHCP4.OPTION[19]:                       broadcast_address = 10.0.0.255
DHCP4.OPTION[20]:                       requested_ntp_servers = 1
DHCP4.OPTION[21]:                       requested_netbios_name_servers = 1
DHCP4.OPTION[22]:                       domain_name_servers = 10.0.0.1
DHCP4.OPTION[23]:                       requested_ms_classless_static_routes = 1
DHCP4.OPTION[24]:                       subnet_mask = 255.255.255.0
DHCP4.OPTION[25]:                       network_number = 10.0.0.0
DHCP4.OPTION[26]:                       requested_host_name = 1
DHCP4.OPTION[27]:                       dhcp_server_identifier = 10.0.0.1
IP6.ADDRESS[1]:                         fe80::5c72:ba8d:7aad:c70b/64
IP6.GATEWAY:

GENERAL.DEVICE:                         enp3s0
GENERAL.TYPE:                           ethernet
GENERAL.NM-TYPE:                        NMDeviceEthernet
GENERAL.VENDOR:                         Realtek Semiconductor Co., Ltd.
GENERAL.PRODUCT:                        RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
GENERAL.DRIVER:                         r8169
GENERAL.DRIVER-VERSION:                 2.3LK-NAPI
GENERAL.FIRMWARE-VERSION:
GENERAL.HWADDR:                         <MAC 'enp3s0' [IF1]>
GENERAL.MTU:                            1500
GENERAL.STATE:                          20 (unavailable)
GENERAL.REASON:                         2 (Device is now managed)
GENERAL.UDI:                            /sys/devices/pci0000:00/0000:00:1c.7/0000:03:00.0/net/enp3s0
GENERAL.IP-IFACE:
GENERAL.IS-SOFTWARE:                    no
GENERAL.NM-MANAGED:                     yes
GENERAL.AUTOCONNECT:                    yes
GENERAL.FIRMWARE-MISSING:               no
GENERAL.NM-PLUGIN-MISSING:              no
GENERAL.PHYS-PORT-ID:                   --
GENERAL.CONNECTION:                     --
GENERAL.CON-UUID:                       --
GENERAL.CON-PATH:                       --
GENERAL.METERED:                        unknown
CAPABILITIES.CARRIER-DETECT:            yes
CAPABILITIES.SPEED:                     unknown
CAPABILITIES.IS-SOFTWARE:               no
WIRED-PROPERTIES.CARRIER:               off
CONNECTIONS.AVAILABLE-CONNECTION-PATHS:

##### NetworkManager.state ##############

[main]
NetworkingEnabled=true
WirelessEnabled=true
WWANEnabled=true

##### NetworkManager.conf ###############

[main]
plugins=ifupdown,keyfile,ofono
dns=dnsmasq

[ifupdown]
managed=false

##### NetworkManager profiles ###########

[[/etc/NetworkManager/system-connections/Speedy Remember Harambe]] (600 root)
[connection] id=Speedy Remember Harambe | type=wifi | permissions=
[wifi] mac-address=<MAC 'wlp5s0' [IF2]> | mac-address-blacklist= | ssid=Speedy Remember Harambe
[ipv4] method=auto
[ipv6] method=auto

##### iw reg get ########################

Region: America/Los_Angeles (based on set time zone)

country 00: DFS-UNSET
    (2402 - 2472 @ 40), (6, 20), (N/A)
    (2457 - 2482 @ 40), (6, 20), (N/A), PASSIVE-SCAN
    (2474 - 2494 @ 20), (6, 20), (N/A), NO-OFDM, PASSIVE-SCAN
    (5170 - 5250 @ 160), (6, 20), (N/A), PASSIVE-SCAN
    (5250 - 5330 @ 160), (6, 20), (0 ms), DFS, PASSIVE-SCAN
    (5490 - 5730 @ 160), (6, 20), (0 ms), DFS, PASSIVE-SCAN
    (5735 - 5835 @ 80), (6, 20), (N/A), PASSIVE-SCAN
    (57240 - 63720 @ 2160), (N/A, 0), (N/A)

##### iwlist channels ###################

lo        no frequency information.

enp3s0    no frequency information.

wlp5s0    32 channels in total; available frequencies :
          Channel 01 : 2.412 GHz
          Channel 02 : 2.417 GHz
          Channel 03 : 2.422 GHz
          Channel 04 : 2.427 GHz
          Channel 05 : 2.432 GHz
          Channel 06 : 2.437 GHz
          Channel 07 : 2.442 GHz
          Channel 08 : 2.447 GHz
          Channel 09 : 2.452 GHz
          Channel 10 : 2.457 GHz
          Channel 11 : 2.462 GHz
          Channel 12 : 2.467 GHz
          Channel 13 : 2.472 GHz
          Channel 36 : 5.18 GHz
          Channel 40 : 5.2 GHz
          Channel 44 : 5.22 GHz
          Channel 48 : 5.24 GHz
          Channel 52 : 5.26 GHz
          Channel 56 : 5.28 GHz
          Channel 60 : 5.3 GHz
          Channel 64 : 5.32 GHz
          Channel 100 : 5.5 GHz
          Channel 104 : 5.52 GHz
          Channel 108 : 5.54 GHz
          Channel 112 : 5.56 GHz
          Channel 116 : 5.58 GHz
          Channel 120 : 5.6 GHz
          Channel 124 : 5.62 GHz
          Channel 128 : 5.64 GHz
          Channel 132 : 5.66 GHz
          Channel 136 : 5.68 GHz
          Channel 140 : 5.7 GHz
          Current Frequency:5.765 GHz

##### iwlist scan #######################

lo        Interface doesn't support scanning.

enp3s0    Interface doesn't support scanning.

Channel occupancy:

      5   APs on   Frequency:2.412 GHz (Channel 1)
      2   APs on   Frequency:2.427 GHz (Channel 4)
      1   APs on   Frequency:2.437 GHz (Channel 6)
      1   APs on   Frequency:2.447 GHz (Channel 8)
      1   APs on   Frequency:2.452 GHz (Channel 9)
      1   APs on   Frequency:2.457 GHz (Channel 10)
      2   APs on   Frequency:2.462 GHz (Channel 11)
      1   APs on   Frequency:5.32 GHz (Channel 64)
      2   APs on   Frequency:5.765 GHz

wlp5s0    Scan completed :
          Cell 01 - Address: <MAC 'Speedy Remember Harambe' [AC1]>
                    Channel:153
                    Frequency:5.765 GHz
                    Quality=45/70  Signal level=-65 dBm
                    Encryption key:on
                    ESSID:"Speedy Remember Harambe"
                    Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                              36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=000000003ede57a2
                    Extra: Last beacon: 80ms ago
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK

          Cell 08 - Address: <MAC 'Remember Harambe' [AC8]>
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=58/70  Signal level=-52 dBm
                    Encryption key:on
                    ESSID:"Remember Harambe"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=000000003e2e6761
                    Extra: Last beacon: 340ms ago
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : CCMP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) :

##### module infos ######################

[iwlmvm]
filename:       /lib/modules/4.4.0-53-generic/kernel/drivers/net/wireless/iwlwifi/mvm/iwlmvm.ko
license:        GPL
author:         Copyright(c) 2003- 2015 Intel Corporation <firstname.lastname@example.com>
description:    The new Intel(R) wireless AGN driver for Linux
srcversion:     60ED6558F1225672289299A
depends:        iwlwifi,mac80211,cfg80211
intree:         Y
vermagic:       4.4.0-53-generic SMP mod_unload modversions
parm:           init_dbg:set to true to debug an ASSERT in INIT fw (default: false (bool)
parm:           power_scheme:power management scheme: 1-active, 2-balanced, 3-low power, default: 2 (int)
parm:           tfd_q_hang_detect:TFD queues hang detection (default: true (bool)

[mac80211]
filename:       /lib/modules/4.4.0-53-generic/kernel/net/mac80211/mac80211.ko
license:        GPL
description:    IEEE 802.11 subsystem
srcversion:     F1176862D12ECD05A1066CF
depends:        cfg80211
intree:         Y
vermagic:       4.4.0-53-generic SMP mod_unload modversions
parm:           minstrel_vht_only:Use only VHT rates when VHT is supported by sta. (bool)
parm:           max_nullfunc_tries:Maximum nullfunc tx tries before disconnecting (reason 4). (int)
parm:           max_probe_tries:Maximum probe tries before disconnecting (reason 4). (int)
parm:           beacon_loss_count:Number of beacon intervals before we decide beacon was lost. (int)
parm:           probe_wait_ms:Maximum time(ms) to wait for probe response before disconnecting (reason 4). (int)
parm:           ieee80211_default_rc_algo:Default rate control algorithm for mac80211 to use (charp)

[iwlwifi]
filename:       /lib/modules/4.4.0-53-generic/kernel/drivers/net/wireless/iwlwifi/iwlwifi.ko
license:        GPL
author:         Copyright(c) 2003- 2015 Intel Corporation <firstname.lastname@example.com>
description:    Intel(R) Wireless WiFi driver for Linux
firmware:       iwlwifi-100-5.ucode
firmware:       iwlwifi-1000-5.ucode
firmware:       iwlwifi-135-6.ucode
firmware:       iwlwifi-105-6.ucode
firmware:       iwlwifi-2030-6.ucode
firmware:       iwlwifi-2000-6.ucode
firmware:       iwlwifi-5150-2.ucode
firmware:       iwlwifi-5000-5.ucode
firmware:       iwlwifi-6000g2b-6.ucode
firmware:       iwlwifi-6000g2a-5.ucode
firmware:       iwlwifi-6050-5.ucode
firmware:       iwlwifi-6000-4.ucode
firmware:       iwlwifi-7265D-13.ucode
firmware:       iwlwifi-7265-13.ucode
firmware:       iwlwifi-3160-13.ucode
firmware:       iwlwifi-7260-13.ucode
firmware:       iwlwifi-8000-13.ucode
srcversion:     F854699497C0353E851B722
depends:        cfg80211
intree:         Y
vermagic:       4.4.0-53-generic SMP mod_unload modversions
parm:           swcrypto:using crypto in software (default 0 [hardware]) (int)
parm:           11n_disable:disable 11n functionality, bitmap: 1: full, 2: disable agg TX, 4: disable agg RX, 8 enable agg TX (uint)
parm:           amsdu_size_8K:enable 8K amsdu size (default 0) (int)
parm:           fw_restart:restart firmware in case of error (default true) (bool)
parm:           antenna_coupling:specify antenna coupling in dB (default: 0 dB) (int)
parm:           nvm_file:NVM file name (charp)
parm:           d0i3_disable:disable d0i3 functionality (default: Y) (bool)
parm:           lar_disable:disable LAR functionality (default: N) (bool)
parm:           uapsd_disable:disable U-APSD functionality (default: Y) (bool)
parm:           bt_coex_active:enable wifi/bt co-exist (default: enable) (bool)
parm:           led_mode:0=system default, 1=On(RF On)/Off(RF Off), 2=blinking, 3=Off (default: 0) (int)
parm:           power_save:enable WiFi power management (default: disable) (bool)
parm:           power_level:default power save level (range from 1 - 5, default: 1) (int)
parm:           fw_monitor:firmware monitor - to debug FW (default: false - needs lots of memory) (bool)

[cfg80211]
filename:       /lib/modules/4.4.0-53-generic/kernel/net/wireless/cfg80211.ko
description:    wireless configuration support
license:        GPL
author:         Johannes Berg
srcversion:     FD4B9DA2F385F0531B5CB0B
depends:
intree:         Y
vermagic:       4.4.0-53-generic SMP mod_unload modversions
parm:           ieee80211_regdom:IEEE 802.11 regulatory domain code (charp)
parm:           cfg80211_disable_40mhz_24ghz:Disable 40MHz support in the 2.4GHz band (bool)

##### module parameters #################

[iwlmvm]
init_dbg: N
power_scheme: 2
tfd_q_hang_detect: Y

[mac80211]
beacon_loss_count: 7
ieee80211_default_rc_algo: minstrel_ht
max_nullfunc_tries: 2
max_probe_tries: 5
minstrel_vht_only: Y
probe_wait_ms: 500

[iwlwifi]
11n_disable: 0
amsdu_size_8K: 0
antenna_coupling: 0
bt_coex_active: Y
d0i3_disable: Y
fw_monitor: N
fw_restart: Y
lar_disable: N
led_mode: 0
nvm_file: (null)
power_level: 0
power_save: N
swcrypto: 0
uapsd_disable: Y

[cfg80211]
cfg80211_disable_40mhz_24ghz: N
ieee80211_regdom: 00

##### /etc/modules ######################

##### modprobe options ##################

[/etc/modprobe.d/blacklist-ath_pci.conf]
blacklist ath_pci

[/etc/modprobe.d/blacklist.conf]
blacklist evbug
blacklist usbmouse
blacklist usbkbd
blacklist eepro100
blacklist de4x5
blacklist eth1394
blacklist snd_intel8x0m
blacklist snd_aw2
blacklist i2c_i801
blacklist prism54
blacklist bcm43xx
blacklist garmin_gps
blacklist asus_acpi
blacklist snd_pcsp
blacklist pcspkr
blacklist amd76x_edac

[/etc/modprobe.d/blacklist-rare-network.conf]
alias net-pf-3 off
alias net-pf-6 off
alias net-pf-9 off
alias net-pf-11 off
alias net-pf-12 off
alias net-pf-19 off
alias net-pf-21 off
alias net-pf-36 off

[/etc/modprobe.d/iwlwifi.conf]
remove iwlwifi \
(/sbin/lsmod | grep -o -e ^iwlmvm -e ^iwldvm -e ^iwlwifi | xargs /sbin/rmmod) \
&& /sbin/modprobe -r mac80211

[/etc/modprobe.d/mlx4.conf]
softdep mlx4_core post: mlx4_en

##### rc.local ##########################

exit 0

##### pm-utils ##########################

##### udev rules ########################

##### dmesg #############################

[    2.244747] ieee80211 phy0: Selected rate control algorithm 'iwl-mvm-rs'
[    2.245702] iwlwifi 0000:05:00.0 wlp5s0: renamed from wlan0
[    2.617072] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready
[    2.617179] iwlwifi 0000:05:00.0: L1 Disabled - LTR Enabled (repeated 4 times)
[    2.839204] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready
[    2.863868] IPv6: ADDRCONF(NETDEV_UP): enp3s0: link is not ready
[    2.878500] r8169 0000:03:00.0 enp3s0: link down
[    2.878580] IPv6: ADDRCONF(NETDEV_UP): enp3s0: link is not ready
[    3.281099] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready
[    6.199988] wlp5s0: authenticate with <MAC 'Speedy Remember Harambe' [AC1]>
[    6.208739] wlp5s0: send auth to <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[    6.218401] wlp5s0: authenticated
[    6.219758] wlp5s0: associate with <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[    6.249831] wlp5s0: RX AssocResp from <MAC 'Speedy Remember Harambe' [AC1]> (capab=0x411 status=0 aid=2)
[    6.251336] wlp5s0: associated
[    6.251370] IPv6: ADDRCONF(NETDEV_CHANGE): wlp5s0: link becomes ready
[  501.655804] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready (repeated 2 times)
[  629.431483] wlp5s0: authenticate with <MAC 'Speedy Remember Harambe' [AC1]>
[  629.438528] wlp5s0: send auth to <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[  629.444300] wlp5s0: authenticated
[  629.444976] wlp5s0: associate with <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[  629.475428] wlp5s0: RX AssocResp from <MAC 'Speedy Remember Harambe' [AC1]> (capab=0x411 status=0 aid=1)
[  629.476336] wlp5s0: associated
[  629.476394] IPv6: ADDRCONF(NETDEV_CHANGE): wlp5s0: link becomes ready
[ 1467.319888] wlp5s0: deauthenticating from <MAC 'Speedy Remember Harambe' [AC1]> by local choice (Reason: 3=DEAUTH_LEAVING)
[ 1470.906112] iwlwifi 0000:05:00.0: L1 Disabled - LTR Enabled (repeated 4 times)
[ 1471.129828] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready (repeated 2 times)
[ 1474.344826] wlp5s0: authenticate with <MAC 'Speedy Remember Harambe' [AC1]>
[ 1474.351913] wlp5s0: send auth to <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[ 1474.361499] wlp5s0: authenticated
[ 1474.365080] wlp5s0: associate with <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[ 1474.391911] wlp5s0: RX AssocResp from <MAC 'Speedy Remember Harambe' [AC1]> (capab=0x411 status=0 aid=1)
[ 1474.393623] wlp5s0: associated
[ 1474.393687] IPv6: ADDRCONF(NETDEV_CHANGE): wlp5s0: link becomes ready
[ 1575.034920] wlp5s0: deauthenticating from <MAC 'Speedy Remember Harambe' [AC1]> by local choice (Reason: 3=DEAUTH_LEAVING)
[ 1578.590948] iwlwifi 0000:05:00.0: L1 Disabled - LTR Enabled (repeated 4 times)
[ 1578.815693] IPv6: ADDRCONF(NETDEV_UP): wlp5s0: link is not ready (repeated 2 times)
[ 1581.880495] wlp5s0: authenticate with <MAC 'Speedy Remember Harambe' [AC1]>
[ 1581.887558] wlp5s0: send auth to <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[ 1581.897142] wlp5s0: authenticated
[ 1581.897520] wlp5s0: associate with <MAC 'Speedy Remember Harambe' [AC1]> (try 1/3)
[ 1581.928003] wlp5s0: RX AssocResp from <MAC 'Speedy Remember Harambe' [AC1]> (capab=0x411 status=0 aid=1)
[ 1581.929503] wlp5s0: associated
[ 1581.929530] IPv6: ADDRCONF(NETDEV_CHANGE): wlp5s0: link becomes ready

Comment: Can you include `ping 220.127.116.11` trace during one of these slowdowns?
Comment: Weird, speed tests through tools such as speedtest.net are reflecting the horrible net speeds (as well as for example streaming and etc, drops in which are why I notice), but ping doesn't: `--- 220.127.116.11 ping statistics ---
52 packets transmitted, 52 received, 0% packet loss, time 51074ms
rtt min/avg/max/mdev = 24.107/25.465/27.550/0.935 ms
`
Answer: I own and use successfully two Intel wireless devices. I have honed a few techniques in several years and thousands of forum posts.
First, check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I also have better luck with a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred.
I notice that your SSID is named, "Speedy Remember Harambe". I recently worked on a case where connectivity was greatly improved by, remarkably, removing spaces in the name. I suggest that you try renaming the network to something like SpeedyRememberHarambe.
After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS

Of course, substitute your country code if not Iceland. Set it permanently:
gksudo gedit /etc/default/crda

Use nano or kate or leafpad if you don't have the text editor gedit.
Change the last line to read:
REGDOMAIN=IS

Proofread carefully, save and close the text editor.
Next, I'd set IPv6 to Ignore in Network Manager: http://docs.fedoraproject.org/en-US/Fedora/18/html/Installation_Guide/images/netconfig/network-connections-ipv6-ignore.png  This example is for ethernet, but you want wireless.
Reboot the computer and let us hear your report.
Comment: I am not the OP, but this miraculously gave me a huge boost in speeds on a 4.9 kernel with an iwlwifi driver.


How can i read 'Encoded by' information of Mp3 File?

Question: I can read album, artist, title and etc. with Taglib-sharp but i couldnt find out how to read 'encoded by' field like itunes does.
Answer: I just found out.
tagFile = TagLib.File.Create(fileLocation);
TagLib.Id3v2.Tag tag5 = (TagLib.Id3v2.Tag)tagFile.GetTag(TagTypes.Id3v2);

                    IEnumerable<TagLib.Id3v2.Frame> frames = tag5.GetFrames();

                    foreach (TagLib.Id3v2.Frame frame in frames)
                    {
                        if (frame.FrameId.Data.SequenceEqual(new byte[] { 84, 69, 78, 67}))
                            fileAnlyRslt.EncodedWith = frame.ToString();
                    }

Answer: Here's my solution (uses LINQ):
var mp3File = TagLib.File.Create(path);
var tags = new TagLib.Id3v2.Tag(mp3File, 0);

var frame = tags.GetFrames()
                .Where(f => Encoding.UTF8.GetString(f.FrameId.Data) == "TENC")
                .First();
var encoder = frame != null ? frame.ToString() : "";


How to implement a button share to Instagram and WhatsApp Stories

Question: We need to implement a Share Button in our app that allows users to share images to WhatsApp Statuses or Instagram Stories.
Spotify currently has a button that allows you to share a Story to Instagram. However I haven't been able to find any documentation on how to implement this for Instagram or WhatsApp.
Can this functionality be implemented in iOS and Android? If so how?
Answer: You can take a look to the official documentation: https://developers.facebook.com/docs/instagram/sharing-to-stories/
Despite the instruction, my app still crash because it can't find the proper activity like explained in this question: Sharing to Facebook Stories
I'll let you now i will make some progress


Bash on Ubuntu on Windows users

Question: I can't seem to access my normal Windows filesystem on the Ubuntu command line in Windows, any tips? Not even sure if this is supported yet.
Comment: I'm fairly certain that the environment is sandboxed, meaning it can't see any files outside the Ubuntu-related files; but I could be wrong.
Comment: I read somewhere that it was sandboxed, but you could access your filesystem with the bash line
Comment: I honestly don't know much about it. I suppose you could see if a `/mnt/` folder exists and if anything exists under that.
Comment: Yes, Cygwin uses /cygdrive/C, so I would expect this Ubuntu on Windows to mount the C drive as /mnt/C or something like that.
Answer: The windows file systems are located in /mnt/<Drive letter> by default. Keep in mind that there are caveats with file permissions given they aren't supported on ntfs.
Comment: To be accurate, NTFS supports ACL based file permissions, which are richer than Linux' DACs. WSL exposes files/folders in the Windows filesystem with the user's effective permission set, but may revert to 777 in some cases where mapping between DAC & ACL looks to be permissive.
Answer: You must enter the following:
cd /mnt/c/dev

Bash on Ubuntu on Windows users


configure jetty ssl in heroku

Question: I have a standalone launcher for jetty inside server directory. I have some jeytty configuration  code there. I need to configure jetty to work with http and https connectors.
As I understand heroku supplies custom port to launch jetty on. It's not clear what port can i use to configure SSL connector. Also it's unclear should I provide any certificate for jetty if I use piggyback addon.
Answer: You shouldn't need to configure Jetty for SSL at all. Heroku will terminate the SSL endpoint at the routing layer and handle it for you from there. The config options in Jetty are for when Jetty is expecting to act as the SSL endpoint.

configure jetty ssl in heroku


browser performance impact of Knockout.js form with thousands of observables

Question: I'm creating a form where the user will be able to add multiple rows with knockout.js, each row will have a 5 inputs and the user could potentially add hundreds of rows.
I want to use observable array and make it's properties also observable, for each input.
So it would be likely for some users there could be approx 5000 observable properties on the page.
Is there any performance issues which could arise from such an approach?  Could is slow down the browser? And if there is, are there any methods to protect against it.
Comment: "it depends" - on so many things, it really isn't possible to say. If you're concerned, make a quick'n'dirty codepen or similar that writes out hundreds of dummy rows.
Comment: In my experience, the more observables you have bound to a page, the slower the binding process becomes. Here are some tips; http://www.knockmeout.net/2012/03/knockoutjs-performance-gotcha-1ifwith.html
Answer: We're using controls with observables en observableArrays that hold 20k+ records clientside and we're now hitting a bit of a javascript/knockout wall. with 5k it still went pretty smooth but it also strongly depends on the client's browser/hardware.
1 major issue while updating all items in an obs. array is that if you'll iterate the change it would hang the page until the end of the iteration. You could use the apply method to get around that if logic allows that. Function.prototype.apply()
I'd say if you're 100% sure it won't grow over 5k, go for it, it'll work. But honestly  nowadays you'd probably be better of leaving most of the data on the server and only retrieve what you need at that point.
Comment: I was thinking on your assignment .. if you're looking to create an excel like environment, you'd probably like to know that it's not feasible to have all fields as `` actively montoring, it's better to implement something that replaces each "cell/span-value" by an input element onclick/focus so you only have 1 onchange event hooked at each given moment, leaving some memory for the 5k records :)
Comment: thanks that's good to know. Interestingly the data is not coming from the server, the client uploads a CSV which they need to be able to edit the values of :)


Duplicate grant_type parameter Uber API

Question: I'm trying to get OAuth access to Uber, using Cortana's Connected account.
All necessary for authentication data, a.k.a. auth url, token url, client secret, etc. was taken from Uber API description and passed to Cortana, so she must do all low-level job for me.
But when I'm trying to login in to uber, I receving such answer:
"error": "The token response status code was not 200.",
"serviceRequest": {
    "Host": "login.uber.com",
    "Headers": {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic VXF6cGVzeWVwYXFPZDBrc0FsUTh3U0dTHFvb2k6TFg0TWFhVDRwU0NFNlM3ZDJVMGJSdlU0VnJhTnRncFJPVlo4UkNqQg=="
    },
    "Method": "POST",
    "Path": "/oauth/v2/token",
    "UrlParameters": {
        "redirect_uri": "https://www.bing.com/agents/oauth",
        "grant_type": "authorization_code",
        "code": "some code private here :)"
    },
    "PostData": "redirect_uri=https%3a%2f%2fwww.bing.com%2fagents%2foauth&grant_type=authorization_code&code=SOME_AUTHORIZATION_CODE"
},
"serviceResponse": {
    "Headers": {
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "X-Uber-App": "login",
        "Strict-Transport-Security": "max-age=604800",
        "X-Content-Type-Options": "nosniff",
        "X-XSS-Protection": "1; mode=block",
        "Cache-Control": "no-store",
        "Date": "Sat, 28 Oct 2017 10:30:57 GMT",
        "Set-Cookie": "session=421370309da06baf_59f45c61.RKb0a7144yyiV9HlZgssA5ZvSqE; Domain=login.uber.com; Secure; HttpOnly; Path=/",
        "Server": "nginx",
        "Content-Length": "84",
        "Content-Type": "application/json"
    },
    "StatusCode": 400,
    "ResponseData": "{\"error_description\": \"Duplicate grant_type parameter.\", \"error\": \"invalid_request\"}"
},

As you can see, in property ResponseData I have an error: Duplicate grant_type parameter.
What could it be?
Answer: Do you need to repeat the auth parameters for the token request as URL params when they are included in the POST data. I am assuming that "some code private here :)" and SOME_AUTHORIZATION_CODE are the same.
Comment: Yes, you right, this is same codes. But it's not me repeating them. Request made by Cortana and as far as I know, I can't affect to its content.
So, in general, looks like it's how Cortana works — this service duplicates parameters in the request.

Duplicate grant_type parameter Uber API


How to add circular image in flutter PDF

Question: How to add a Round shape image in flutter pdf.
my image Container code is
Container(
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                        ),
                        child: Image(
                          image,
                          height: 70,
                          width: 70,
                        )),

I also used DecorationImage but this is not working
 Container(
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: image, fit: BoxFit.cover))),

These 2 methods are not working
What should I do?
Comment: Does this answer your question? [How to do Rounded Corners Image in Flutter](https://stackoverflow.com/questions/51513429/how-to-do-rounded-corners-image-in-flutter)
Comment: No, My Question is rounded image add in Flutter pdf. This question is normal screen design
Comment: can I ask what package you're using  for pdf.
Comment: pdf [link][https://pub.dev/packages/pdf]
Answer: Check this link
it could be helpfull https://github.com/DavBfr/dart_pdf/blob/master/demo/lib/examples/resume.dart
  pw.ClipOval(
                      child: pw.Container(
                        width: 100,
                        height: 100,
                        color: lightGreen,
                        child: pw.Image(profileImage),
                      ),
                    ),

Answer: There is a flutter package that will let you create flutter UI widgets inside your PDf
https://pub.dev/packages/pdf/example
here is an example:
import package
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

Future<void> createMyPDF() async {
  final pdf = pw.Document();
  final image = pw.MemoryImage(
    File('image.jpg').readAsBytesSync(),
  );

  pdf.addPage(pw.Page(
      // build PDF UI
      build: (pw.Context context) => pw.Center(
            child: pw.Container(
              decoration: pw.BoxDecoration(
                border: pw.Border.all(color: PdfColors.black),
              ),
              child: pw.Image(image),
            ),
          )));
  // save my pdf as exapmle.pdf
  final file = File('example.pdf');
  //write file in storage
  await file.writeAsBytes(await pdf.save());
}

call the function on any event to  save pdf file


Hot dryer cord after use

Question: This question is a follow-up to this question titled "Dryer door switch" which I asked a bit ago.
Thank you to @SiHa who answered my question! I just was using my dryer (which now works). It is a Malber dryer (attached is a picture of the label on the back). It uses a 3 prong outlet, and I am located in the United States. I noticed after using it that the cord was rather warm, and the prongs on the plug were quite hot. Might this be connected to the door switch? Is it something to be concerned about?
Just some more details: I do not recall this happening before. Also, the dryer was on for longer than necessary to dry the things inside.
Comment: So hot that you can't hold and have to let go, or just warm?
Comment: How does the plug feel when plugging in?  Does it feel solid and tight or on the loose side?  If it feels loose then  outlet might be worn out and needs replacement.
Comment: Faulty receptacle, or to be more precise loose connection on receptacle that is arc faulting.
Comment: @JPhi1618 too hot to touch.
Comment: @crip659 it feels solid
Answer: There is a little resistance between the plug and receptacle. The surfaces must be clean ( fairly free of oxidation) , and as commented, fit together tightly. Simply pushing the plug in and out a few times should rub it clean, alternately clean the prongs a little with sand paper. You may be able to spring the prongs some, so that they are a tighter fit. As commented, all screw connections must be tight. It is heating according to I squared times R. I is current and the dryer uses a lot, there is nothing you can do about that. You are working on R = resistance. Tight, clean connections to minimize R ; there will always be a little R so it will be warm even when in good shape. As, commented , a new tight fitting , clean plug is an option.

Hot dryer cord after use


Wordpress HTML title is messed up

Question: I'm unable to get the title in my custom WordPress theme to display properly. The title attribute is set as follows: <title><?php wp_title( '|', true, 'right' ); ?></title>
I took that code straight from the 2012 theme. When I activate the 2012 theme the title looks perfect, but when I use my custom theme with that same code above, I get the address of my website as the title on the homepage, and on every other page, I just get the page name followed by a " | ". Any idea of what could be causing this? Ive looked for second title tags, but so far nothing. Its ruining my SEO.
Added this to my functions.php:
function twentytwelve_wp_title( $title, $sep ) {
    global $paged, $page;

    if ( is_feed() )
        return $title;

    // Add the site name.
    $title .= get_bloginfo( 'name' );

    // Add the site description for the home/front page.
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) )
        $title = "$title $sep $site_description";

    // Add a page number if necessary.
    if ( $paged >= 2 || $page >= 2 )
        $title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) );

    return $title;
}
add_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 );

Comment: It would be easier to answer your question were you to post a screenshot, or a link to the page (preferably the latter). Also, as mentioned by @j08691, make sure you examine the WordPress Codex closely. They've done a remarkable job of documenting every feature of the CMS.
Comment: Did you read this entire page http://codex.wordpress.org/Function_Reference/wp_title?
Answer: The blog name is missing. That's why only the page title is displayed. Try something like this to have an idea:
<title>
    <?php
    bloginfo( 'name' );
    echo " | ";
    if ( is_home() ) {
      _e( "Home" );
    }
    else {
      // Get the custom Title for this page, if any.
      if ( defined( 'Title' ) ) {
        $LimitWords = Title;
        echo string_limit_words( $LimitWords, 4 ) . " ...";
      }
      else {
      // Get the default Title
        $LimitWords = wp_title( '', FALSE );
        echo string_limit_words( $LimitWords, 4 ) . " ...";
      }
    }
    ?>
  </title>

For that code to work, you have to add this function in functions.php in the style sheet directory:
  if ( !function_exists( 'string_limit_words' ) ) {
    function string_limit_words( $string, $word_limit ) {
      $words = explode( ' ', $string, ( $word_limit + 1 ) );
      if ( count( $words ) > $word_limit ) array_pop( $words );
      return implode( ' ', $words );
    }
  }

Comment: What do you mean the blog "name" is missing? When switching to another theme, the blog name appears. So wouldn't that mean that the blog name IS set?
Comment: `` That's what is in your question. There, the blog name is missing.
Comment: But that's the exact code from the 2012 theme. And it works fine in the 2012 theme. I understand what you're saying, but now I'm just confused about how 2012 theme works with that code, and my theme doesn't work with it.
Comment: I couldn't say either. Not without seeing it, but try the code in my answer so can have a better idea of what's needed.
Comment: Hrm... I just got it to work. I ctrl + f'ed my way to find a function in the 2012 theme that dealt with the title. I'm updating my post to show what I added. Note: It works great now. Sorry, for wasting your time.
Comment: I'm marking this as the answer since you helped lead me in the right direction.

Wordpress HTML title is messed up


Best way to check if content of page has been changed?

Question: I have a crawler that crawl hundred of thousands of pages and index/parse the contents of the page, and one thing I'm struggling with is to check if the content of a page has been updated, in an efficient way, without having to crawl it and check the content of the page.
Obviously I could just load the whole page, and re-parse everything and compare it all to what I have stored in my database. However that is very inefficient and use a lot of computing resulting in high hosting bills.
I'm thinking of comparing hashes, the problem with this is that if the page has changed a single byte or character, the hash would be different. So for example if the page display the current date on the page, every single time the hash would be different and tell me that the content has been updated.
So... How would you do this? Would you look at the kb size of the HTML? Would you look at the string length and check if for example the length has changed more than 5%, the content has been "changed"? Or is there some kind of hashing algoritm where the hashes stay the same if only small parts of the string/content has been changed?
Comment: How about a two step process?  You could use hashes to screen for pages that might have changed.  If the hashes match, the page is unchanged.  If not, you can parse to determine whether the change was significant.  This should be decently efficient as long as there are not too many false positives (i.e. changed hashes without a real change in content).
Comment: Is the `last-modified` header (or optionally, `ETag`) reliable on the site you're scraping?  If so, just use that.
Comment: ... and use a `HEAD` http request. Not a plain `GET`.
Comment: Im crawling many different kind of domains and sites and we are scaling up to new domains aswell. So a method that is reliable on all domains would be preferable.
Comment: About `last-modified` - unfortunately not all servers return this date correctly. I think it is not reliable solution. I think better way - combine hash and content length solution. Check hash, and if it changed - check string length.
Comment: About content length - you can try strip all tags and check string length after then. In this case you can forgot about HTML changes. Also you can replace all consecutive spaces to one, to prevent it effect to hash
Answer: You could try and use the value contained in the "last-mofidied" header in the response from the server. Parsing this into a nice object would allow for simple date comparisons, letting you check if you should re-scrape. For example (in Python using the brilliant requests library:
<code>import requests
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
site_last_modified_date = r.headers["Last-Modified"]

# from here, just parse the date and compare it with the last recorded date
</code>
Comment: Unfortunately not all servers return this date correctly. I think it is not reliable solution
Comment: Thank you for your answer but as I stated in the comments earlier, since we crawl many different servers and domains we want to find a more reliable solution that works everywhere.


Does Phonegap support root relative path? What are the best practices?

Question: I'm really baffled after reading PhoneGap on iOS with absolute path URLs for assets
and have a couple of questions:

Does Phonegap supports root relative path? For instance Ionic framework for Hybrid Mobile development has such kind of path in their samples:

What are the best practices for Phonegap's path?
Answer: Basically in phone gap development everything that concerns your code resides in the www folder.
-myApp
   -www
      -index.html
      -img
      -js
      -css
      -libraries
      -templates

The best would be to just refer the files as js/file.js and css/file.css i.e relative to index.html.
Root relative paths may conflict depending on the platform and thus would be a unnecessary hassle.
Root Relative Paths:
doing something like this :
<link href="/css/app.css">

This will work in your browser if you have a local server setup and have set your myApp/www folder as the root.
But when you build your app in cordova and test it on your phone, it will display incorrectly as it does not have any reference to that server root and will reference it as file:///.
Absolute paths
An absolute path would require you to mention the complete address. When you are creating your app, your code resides in the myApp/www folder. But when you build the app(assuming android), it is moved to the platforms/android/assets/www folder. So your absolute paths will again be wrong.
Remote Server
Your app obviously interacts with a remote server . If you store your images on your remote server, then you must refer to them with absolute paths in your application.
Comment: thanks for your answer. However it mostly covers the second question. Could you give me more details about quirks with root relative path? I can't find any docs about it. And what about Ionic style with src="//ionic/js/ionic.bundle.min.js" ?
Comment: @natvarun So, Ionic guys screwed thing up and fixing it now ;)
Comment: In my case, setting paths relativd to `index.html` doesn't work. `library/css/libs/slick/slick.js` results in `file:///library/css/libs/slick/slick.js` once encapsulated in an Android app, which obvisouly isn't found. Do you understand why I am facing this behaviour ?
Comment: I guess you should start a new thread - it is not likely that someone will answer in the comment + it is a bad practice and not really fits stack rules
Answer: I stumbled upon this old thread while trying to solve the same/similar challenge with images not rendering on the device but, oddly, would render when running with a live server or with the Chrome browser.
If you're reading this, the filespec to your image is also case-sensitive. Chrome doesn't care, but Cordova (Phonegap) does!
Answer: Refer this link
https://github.com/apache/cordova-ios/issues/883#issuecomment-643657781
you can add prefrence tag in config.xml lik this
<preference name="scheme" value="app" />

In cardova & phonegap they use custom protocol(app://) for refering to file available locally.


with / without www issue in codeigniter session

Question: I have a little problem with codeigniter. The problem is in the session with www and without www.
If I access the page in www.myweb.com, all data is loaded completely: css, js, and php template such as header.php and footer.php. However, it fails to load or to read the session such as userdata and facebook token.
It only loads the session if I access the web without www such as http://myweb.com.
What is wrong with this? Please help me, anybody.
Answer: This is due to the two sites having different "domains" so the session does not carry over from one to another. One way to fix this is to change your .htaccess file to direct traffic from the non-preferred URL to the preferred URL. There is more detail on how to set this up in this post: different session with url's with-www and without-www
Comment: Thanks for the link. I will give it a try


Question on proving $γ∨ρ=γ∘ρ∘γ$

Question:
in theorem 5 of Group congruences on eventually regular semigroups by S. Hanumantha Rao. he saied it suffices to prove $ρ∘γ∘ρ⊆γ∘ρ∘γ$. Why?
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: I don't know what is your general definition for the join of two congruences, but in any algebra the join of two congruences $\gamma$ and $\rho$ (or indeed, in any set the join of those equivalence relations) is given by
$$\gamma \vee \rho = \bigcup_{n\geq 1}(\gamma \circ \rho)^n.$$
Now, if $\rho \circ \gamma \circ \rho \subseteq \gamma \circ \rho \circ \gamma$, then
\begin{align}
(\gamma \circ \rho \circ \gamma)^2
&=\gamma \circ \rho \circ \gamma \circ \gamma \circ \rho \circ \gamma\\
&=\gamma \circ \rho \circ \gamma \circ \rho \circ \gamma\\
&\subseteq \gamma \circ \gamma \circ \rho \circ \gamma \circ \gamma\\
&=\gamma \circ \rho \circ \gamma,
\end{align}
whence $(\gamma \circ \rho \circ \gamma)^n=\gamma \circ \rho \circ \gamma$, for all $n\geq1$, by induction, yielding
$$\gamma \vee \rho = \bigcup_{n \geq 1} (\gamma \circ \rho)^n \subseteq \bigcup_{n\geq 1} (\gamma \circ \rho \circ \gamma)^n = \gamma \circ \rho \circ \gamma,$$
while the reverse inclusions is obvious.
I hope you can justify the several steps.
For example, I'm using the fact that composition of binary relations is associative.
In several ones I use $\gamma \circ \gamma = \gamma$, where one inclusion follows from transitivity, while the other follows from reflexivity.
In general, for two binary relations, $\alpha$ and $\beta$, if $\alpha$ is reflexive, then $\alpha \subseteq \alpha \circ \beta$.
I think these hints justify all the steps.
Let me know if you still have any doubts.

Question on proving $γ∨ρ=γ∘ρ∘γ$