text:
Q: Improving Mergesort. Improvement 3). Use one less copy between input and temp arrays I am currently working on a project for my algorithms class and am at a bit of a standstill. We were assigned to do improvements to merge sort, that was in the book, by implementing specific changes. I have worked fine through the first 2 changes but the 3'rd one is killer.
Merge sort, the one we are improving, copies the contents of the input array into the temporary array, and then copies the temporary array back into the input array. So it recursively sorts the input array, placing the two sorted halves into the temporary array. And then it merges the two halves in the temporary array together, placing the sorted sequence into the input array as it goes.
The improvement is that this double copying is wasteful can be done without. His hint is that: We can make it so that each call to Merge only copies in one direction, but the calls to Merge alternate the direction.
This is supposedly done by  blurring the lines between the original and temporary array.
I am not really looking for code as I am confident that I can code this. I just have no idea what i'm supposed to be doing. The professor is gone for the day so I can't ask him until next week when I have his course again.
Has anyone done something like this before? Or can decipher and put it into laymans terms for me :P
The first improvement, simply has it use insertion sort whenever an Array gets small enough that it will benefit greatly, timewise, from doing so.
The second improvement stops allocating two dynamic arrays (the 2 halves that are sorted) and instead allocates 1 array of size n and that is what is used instead of the two dynamic arrays. That's that last one I did. The code for that is :
//#include "InsertionSort.h"
#define INSERTION_CUTOFF 250
#include <limits.h>  // needed for INT_MAX (the sentinel)
void merge3(int* inputArray, int p, int q, int r, int* tempArray)
{
  int i,j,k;
  for (i = p; i <= r; i++)
  {
    tempArray[i] = inputArray[i];
  }
  i = p;
  j = q+1;
  k = p;
  while (i <= q && j <= r)
  {
    if (tempArray[i] <= tempArray[j])
    {
      inputArray[k++] = tempArray[i++];
    }
    else
    {
      inputArray[k++] = tempArray[j++];
    }
  }
}//merge3()

void mergeSort3Helper(int* inputArray, int p, int r, int* tempArray)
{
  if (r - p < INSERTION_CUTOFF)
  {
    insertionSort(inputArray,p,r);
    return;
  }
  int q = (p+r-1)/2;
  mergeSort3Helper(inputArray,p,q,tempArray);
  mergeSort3Helper(inputArray,q+1,r,tempArray);
  merge3(inputArray,p,q,r,tempArray);
}//mergeSort3Helper()

void mergeSort3(int* inputArray, int p, int r)
{
  if (r-p < 1)
  {
    return;
  }
  if (r - p < INSERTION_CUTOFF)
  {
    insertionSort(inputArray,p,r);
    return;
  }
  int* tempArray = malloc((r-p)+1*sizeof(int));
  tempArray[r+1] = INT_MAX;
  mergeSort3Helper(inputArray,p,r,tempArray);
//  This version of merge sort should allocate all the extra space
//  needed for merging just once, at the very beginning, instead of
//  within each call to merge3().
}//mergeSort3()

A: The algorithm is like this:
A1: 7 0 2 9 5 1 4 3
A2: (uninitialized)
Step 1:
A1 : unchanged
A2: 0 7 2 9 1 5 3 4
Step 2:
A1: 0 2 7 9 1 3 4 5
A2: unchanged
Step 3:
A1: unchanged
A2: 0 1 2 3 4 5 7 9
This involves you copying only one way each time and follows the steps of mergesort. As your professor said, you blur the lines between the work array and the sorted array by alternating which is which, and only copying once things are sorted.

A: I suspect it would be difficult and ultimately unprofitable to avoid all copying.  What you want to do instead is to avoid the copy you currently do with each merge.
Your current merge3(inputArray, p,q,r, tempArray) returns the merged result in its original array, which requires a copy; it uses its tempArray buffer only as a resource.  In order to do better, you need to modify it to something like merge4(inputArray, p,q,r, outputArray), where the result is returned in the second buffer, not the first.
You will need to change the logic in mergeSort3Helper() to deal with this.  One approach requires a comparable interface change, to mergeSort4Helper(inputArray, p,q,r, outputArray), such that it also yields its result in its second buffer.  This will require a copy at the lowest (insertion sort) level, and a second copy in the top-level mergeSort4() if you want your final result in the same buffer it came in.  However, it eliminates all other unnecessary copies.
Alternately, you could add a boolean parameter to mergeSort4Helper() to indicate whether you want the result returned in the first or second buffer.  This value would alternate recursively, resulting in at most one copy, at the lowest level.
A final option might be to do the merging non-recursively, and alternate buffers at each pass.  This would also result in at most one copy; however, I would expect the resulting access pattern to be inherently less cache-friendly than the recursive one.


text:
Q: Apache Camel: place message back in original location after being processed I've run into a strange obstacle using Apache Camel's file component. The gist of the problem is this: I'm using the file component to load in all messages from a directory. I then use a processor to perform some operation on the files loaded. If the process succeeds, then I move the file to a different location and delete the original file. If the process fails however, I leave the message in it's original directory. The code looks something like this:
from("fileLocation")
   .process(new MessageProcessor())
   .choice()
       .when(header("processPassed").isEqualTo(true))
          .to("file:newLocation")
   .otherwise()
       .to("fileLocation");

If the processor passes then everything works great. However, if the processor fails and I'm trying to return the message back to its original location, that doesn't work. Any idea on how to fix this?

A: I think there are two problems  affecting you. Firstly you cannot write the file back to the original location because Camel is processing it and second there is a risk that you'll repeatedly process the same file. To get around this you can use two options:

*

*preMove to use a working directory

*idempotent to prevent the same file be processed a second time.

Here is a slightly modified version of your code that I believe does what you require
    from("file:fileLocation?idempotent=true&preMove=working")
       .process(new MessageProcessor())
       .choice()
           .when(header("processPassed").isEqualTo(true))
              .to("file:newLocation")
       .otherwise()
           .to("file:fileLocation");

More details available in the File Endpoint documentation.

A: Read the documentation, there is a moveFailed option that you can specify.
It is a good thing to have the files placed in some error folder, and not the original location though. Then you will know where to look for bad files.
Update:
Since it's a firm requirement that you need to leave the files in place, you need to setup a persistent idempotent repository.
This is mostly copied from docs, and will save the absolute file paths of the processed files into a file on disk - so that it will never process the same (filename) again.
<!-- this is our file based idempotent store configured to use the .filestore.dat as file -->
<bean id="fileStore" class="org.apache.camel.processor.idempotent.FileIdempotentRepository">
    <!-- the filename for the store -->
    <property name="fileStore" value="some/folder/.idempotentrepo/filestore.dat"/>
    <!-- the max filesize in bytes for the file.-->
    <property name="maxFileStoreSize" value="<some size>"/>
</bean>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="file://some/folder/?idempotentRepository=#fileStore&noop=true"/>
        <to uri="mock:result"/>
    </route>
</camelContext>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serial-port communication I'm developing a software that lets you manage the serial-port communication in an easier way, through a C++ wrapper class. But I've run into some doubts;
for example, I wanna show a simple message on the other screen:
1)There is the need of a "listening server" (and then set it up)? Or it gets written directly, like this example:
#include <fcntl.h>
#include <unistd.h>
int main()
{
  int fd = open("/dev/tty2", O_RDWR);
  write(fd, "Hello World", sizeof("Hello World"));
  return 0;
}

(just to show the behavior)
2) I run the program on the sender computer. On the second one, what I've to do?
The two machines run Linux both.
Please give me as much information as you can, I've never treated this (old) communication style.
Edit: In every program I've found so far, both the read and write are in the same program. I'd know why.

A: Personally tested, yes, you've to set a listener and a writer program. Kind of client-server, I'd say.

A: Often sending and receiving are implemented in one program. So you have the same program on both machines even if you send always from the same machine and receive on the other.
If you want to communicate both ways you need sending and receiving in the same application. But then you need a synchronization mechanism.


text:
Q: Are there C# methods to get the number of folders up or down from a reference path? I am looking for a simple API set of methods that find out if a folder is a subdirectory of another folder, and how many steps there are between this. Something like:
int numberOfFoldersDown(string parentFolder, string subfolder)  { ... }

It seems quite useful, though tedious to write, so I thought it should be somewhere in the System.IO.Path or System.IO.Directory assemblies, but I can't find any helpful methods there. Are these functions available, or should I write them myself?

A: Nothing built-in AFAIK.
Here's some recursive example that uses both Path and Directory methods:
internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp\", @"c:\temp\"));                   // 0
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp\", @"c:\temp\zz\"));                // 1
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\", @"c:\temp\zz\"));               // -1
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\", @"c:\temp2\zz\hui\55\"));       // 3
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\zz\", @"c:\temp2\zz\hui\55\"));    // 2

        Console.Read();
    }

    public static int NumberOfFoldersDown(string parentFolder, string subfolder)
    {
        int depth = 0;
        WalkTree(parentFolder, subfolder, ref depth);
        return depth;
    }

    public static void WalkTree(string parentFolder, string subfolder, ref int depth)
    {
        var parent = Directory.GetParent(subfolder);
        if (parent == null)
        {
            // Root directory and no match yet
            depth = -1;
        }
        else if (0 != string.Compare(Path.GetFullPath(parentFolder).TrimEnd('\\'), Path.GetFullPath(parent.FullName).TrimEnd('\\'), true))
        {
            // No match yet, continue recursion
            depth++;
            WalkTree(parentFolder, parent.FullName, ref depth);
        }
    }
}

A: You could iterate through all folders, getting the path name and once you get a path name, loop through that string checking for each '/' and then count how many many / there are, so for example:
C:/Users/Program Files/
There are 3 / so there are 3 hops to the file/folder you want
Hopefully this is some helpful information to what you want.

A: as long as I know the only way to do it is
parent folder : Split the path on "\" and think to remove the drive letter and colon
subfolder     : navigate it recursively (which can be time consuming)

Many other point have to be considered in this but this is the big idea!
Edit :
Ok here is a sample of what you need... more job to be done but it's a good start I think...
The advantage is that you work with unknown folder structure and not just a string representing a path.
public static class FoldersHelper
{
    public static int ParentFolderCount(string path)
    {
        int parentcnt = 0;

        if (System.IO.Directory.Exists(path))
        {
            string pathroot = Path.GetPathRoot(path);
            path = path.Remove(1, pathroot.Length);
            parentcnt = path.Split('\\').Count()-1;
            return parentcnt;
        }
        else
        {
            throw new Exception("not a folder exception");
        }

        return 0;
    }

    public static int ChildFolderCount(string path)
    {
        int childcnt = 0;
        int maxchild = 0;

        if (System.IO.Directory.Exists(path))
        {
            if (Directory.GetDirectories(path).Length > 0)
            {
                foreach (string subpath in Directory.GetDirectories(path))
                {
                    childcnt = ChildFolderCount(subpath) + 1;
                    if (childcnt > maxchild) maxchild = childcnt;
                }
            }
        }
        else
        {
            throw new Exception("not a folder exception");
        }

        return maxchild;
    }

}

A: Find the path somehow, maybe by iterating them all.
When you found one split the path on backslash, put the parts in an array. reverse the array, iterate through that array checking if the foldername matches the parentfoldername string. if it does, return the index + 1 for the steps?


text:
Q: Dictionary Not Working Properly I have been utilizing dictionaries throughout my code, and they all work the way I want expect for this dictionary:
switchState["index"+("\(cellNumber)")] = cellNumber

This is inside a for in were cellNumber is one of the variables. The cellNumber represents a UISwitch a user turned on.
This dictionary continues to overwrite itself, I cannot figure out why. The "index"+("\(cellNumber)") should give the dictionary a new key to store the cellNumber correct?
I'm trying to store this into NSUserDefaults as an NSDictionary and swift makes me have a String for the key or it won't store it. So when I do store the Dictionary only one value exists. Can you see an issue with the above Code or is there another way to do this.
Thanks for the help.

A: // Dictionaty<key,Value>
// subscript(key: Key) -> Value?
// key can be Int, Double, String .... any Type: Hashable
// value can be Any (any number, string, struct, enumeration .... class)

var dict: Dictionary<Int,Int> = [1:1]

//  key    value
dict[10] = 100
dict[1] = 64364
dict[76575] = 1

dict.forEach { (key, value) -> () in
    print("storage for key: \(key) has value: \(value)")
    /*
    storage for key: 76575 has value: 1
    storage for key: 1 has value: 64364
    storage for key: 10 has value: 100
    */
}

var dict2 = [1:"alfa",2:"beta",3:"game"] // [2: "beta", 3: "game", 1: "alfa"]

dict2.forEach { (key, value) -> () in
    print("storage for key: \(key) has value: \(value)")
    /*
    storage for key: 2 has value: beta
    storage for key: 3 has value: game
    storage for key: 1 has value: alfa
    */
}
let key = 2
dict2.updateValue("HELLO", forKey: key) // returns string "beta" (old stored value)
print("now the value for key \(key) has value:", dict2[key])
/*
now the value for key 2 has value: Optional("HELLO")

why Optional?
*/
print("the value for key \(-3) has value:", dict2[-3])
/*
the value for key -3 has value: nil

How to remove value?
*/
dict2.removeValueForKey(1)  // returns string "alfa" (old value)
dict2[1]                    // return nil, as expected

You must save the value of the switch as Bool for the key cellNumber as String
var dict: [String:Bool] = [:]
for i in 10...15 {
    let j = i % 3
    dict.updateValue(j == 0, forKey: "switch\(i)")
}
print(dict)
/*
["switch12": true, "switch13": false, "switch11": false, "switch14": false, "switch10": false, "switch15": true]
*/

A: First of all, the code can be simplified to:
swiftchState["index\(cellNumber)"] = cellNumber

You should check that for every loop, the cellNumber value changes.


text:
Q: How to change the text of "Add new event" in Calender web part? I have tried all the methods suggested online. But none seems to work. I tried the following,
<script>
  document.all("Add new document").innerHTML="Add ur new text";
</script>

and this
http://techtrainingnotes.blogspot.com/2010/08/sharepoint-2010-change-add-new-item-and.html
<script>
var ttnA = document.getElementsByTagName('A');
var ttnCounter = 0;
for (var j=0; j<ttnA.length; j++)
{
  if (ttnA[j].id == 'idHomePageNewItem')
  {
    ttnCounter ++;
    if (ttnCounter == 2)
      { ttnA[j].innerHTML='your new text goes here' }
  }
}
</script>

How can I change the text of the "Add new event" in web part? and where to add the java script exactly?

A: I attempted to add a Calendar web part that had an "Add new event" link but none of mine did. Without seeing your web part though, I would imagine that it's much like editing the "Add new item" link to lists (and list web parts).

*

*Open the site in Sharepoint Designer.

*In the Preview pane, click somewhere near the link you'd like to edit. The List View Tools menu will appear in the ribbon.

*Click on the Design tab.

*Locate and click on Options, and select Summary Toolbar.

*To the right of Options, click on Customize XSLT, and select Customize Entire View.

*Now return to the link and hover over it with your mouse. You should now see a small tab with an > arrow. Click on it and select Hyperlink Options....

*At the top, you should see a field titled Text to display. Change the value of the field to whatever you'd like. Click OK when finished.

*Save your site and refresh in browser.


text:
Q: Get app logs on crash We have a situation here where we want to see some logging when our IONIC1 app crashes (even if it keeps crashing).
We thought about reading the logcat, but this only works if you have a rooted device.... It works then, but since we can't have all the devices here with us to manually run the adb script to grant root log to a logging app, I don't know what to do.
Anyone who had the same situation, and came with a solution?
Thanks in advance!

A: you should try some 3rd party logging tools, would recommend you start with Fabric! (Specifically for Crashlytics)
https://fabric.io/home
UPDATE:
If you want to write your logcats to a file, try something along these lines:
 try {
        Process process = Runtime.getRuntime().exec("logcat -d ");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            log.append(line).append("\n");
        }
    } catch (IOException ignored) {
    }
    String address = writeToLogcatFile(c, log.toString());
    boolean success = !address.equals("");

Also consider creating your own logger and just adding the ability to export it, just make a bunch of functions that calls your logging as appropriate
 public static void v(String TAG, String msg) {
    Logv(TAG, msg);
    if(showOnScreen) {
        Galgo.log(TAG + ": V: " + msg);
    }
}
 private static void Logv(String tag, String msg) {
    if(BuildConfig.DEBUG){
        log.v(tag, msg);
    } else {
        logToTheFileToExportOrDBOrSomethingElse();
    }
}


text:
Q: Phalcon2 module app routing just installed Phalcon2 and working around multi-module app.
I've have such structure.

And my index file http://pastebin.com/zqaRKCdC
When navigating to / , see the front-module index controller, but if I go to /admin, see the same. Maybe anyone have an idea what I'm missing?
P.S One of Module.php - http://pastebin.com/CpGDSuyE


text:
Q: Record add/show/delete for file functions not working The question's title pretty much explains the situation. I am not used to using files and associated commands (such as fseek, fwrite, etc).
Anyhow, the following program must simulate a menu, and present the user with a choice of either adding, editing, deleting or showing records for a file. It is a rather simplistic task, but I just can't figure out what I'm doing wrong.
 #include <stdio.h>

typedef struct{
 int code;
 char description[100];
 int volume;
}product;

int main() {

int pick =0, i;
product *p;
FILE *filePtr;

void add(FILE *filePtr, product* p);
void removal(FILE *filePtr, product* p);
void show(FILE *filePtr, product* p);
void edit(FILE *filePtr, product* p);
void description(FILE *filePtr, product* p);

if ( ( filePtr = fopen( "stock.dat", "rb+")) == NULL ) {
    printf("The file could not be read");
}
else {

do{
   printf("    ************ MAIN MENU ************\n");
   printf("  ** -------------welcome------------- **\n");
   printf(" **                                      ** \n");
   printf("*  Please select one of the commands below *\n");
   printf("********************************************\n");
   printf("* Press 1 to remove products from the list *\n");
   printf("* Press 2 to change a product's quantity   *\n");
   printf("* Press 3 to add a new product to the list *\n");
   printf("* Press 4 to view product list             *\n");
   printf("* Press 5 to exit the programm             *\n");
   printf("********************************************\n");
   scanf("%d", &pick);

   switch ( pick ) {

   case 1:
      removal(filePtr, p);
    break;

   case 2:
      edit(filePtr, p);
    break;

   case 3:
     add(filePtr, p);
   break;

   case 4:
     show(filePtr, p);
   break;

   default:
      printf("Error! Please enter a correct number");
   break;
 }
 }while (pick != 5);

  }

fclose(filePtr);

return 0;
}

void removal(FILE *fileptr, product * p) {
    int code;

    product empty = { 0, " ", 0 };

    printf("\n\nYou are about to delete a record, please enter the product's code");
    scanf("%d", &code);

    fseek( fileptr, (code - 1) * sizeof(p), SEEK_SET);
    fread( &p->code, sizeof(p), 1, fileptr);

    if (p->code == 0){
        printf("Product code not found, please retry");
    } else {
        fseek( fileptr, (code -1) * sizeof(p), SEEK_SET);

        fwrite( &empty, sizeof(p), 1, fileptr);

        printf("Code was found, product removed successfully\n\n");
    }
}

 void add(FILE *fileptr, product * p){

  int code, quantity;

  printf("You are about to add a new product in the list\n Please input the product's code\n");

  scanf("%d", &code);

  fseek( fileptr, (code-1) * sizeof(p), SEEK_SET);
  fread(&code, sizeof(p), 1, fileptr);

    fseek(fileptr, (code-1) * sizeof(p), SEEK_SET);
    fwrite( &code, sizeof(p), 1, fileptr);

    printf("Now enter the product's remaining quantity");
    scanf("%d", &quantity);

    fseek(fileptr, (quantity-1) * sizeof(p), SEEK_SET);
    fwrite( &quantity, sizeof(p), 1, fileptr);

 }

 void edit(FILE *fileptr, product * p){

  int code, volume;

  printf("\nYou are about to edit a existing product's quantity\n Please enter the product's code\n");
  scanf("%d", &code);

  fseek(fileptr, (code -1) * sizeof(p), SEEK_SET);
  fread(&code, sizeof(p), 1, fileptr);

  if (p->code == 0){
    printf("\nThe code you entered is not in the list, please retry\n");
  }else{
    printf("\nCode found!\n Product's  current quantity is %d", &p->volume);
    printf("\n Please enter the new quantity");
    scanf("%d", &volume);

    p->volume = volume;

    fseek(fileptr, (volume -1) * sizeof(p), SEEK_SET);
    fwrite(&volume, sizeof(p), 1, fileptr);

    }

 }

void show(FILE *fileptr, product * p){

 int i=1;

 printf("\n\n\n               ****SHOWING ALL PRODUCTS****\n\n\n");
 printf("PRODUCT CODE      QUANTITY IN STOCK\n");

 while (i<100 && !feof(fileptr)){
    fscanf( fileptr, "%d%d", &p->code, &p->volume);
    printf("%d            %d\n", &p->code, &p->volume);
    fseek(fileptr, (p->code + 1) * sizeof(p), SEEK_SET);
    fscanf( fileptr, "%d%d", &p->code, &p->volume);
    i++;
   }
 printf("You may scroll back up to view the list\n\n");

 }

To give an idea of what is happening: if the user enters option 4, the program, instead of showing no records, shows random values, but even if the user chooses to add a product (by picking choice 3, which is the add function), it won't be shown later and as a result, can't be deleted even if the user chooses to do so. Again, I'm rather new at programming (I am sure you hear this a lot :P). I had posted a similar question before, but did not get a solution.
EDIT I edited a big portion of the code, basically the file opens in binary and now, the struct product p, passes to each function. Problem now supposedly fixed, program run once showing correct values and records, however crashes by itself for uknown reason. Any additional help would be great

A: There's definitely a problem with your show function...
For starters, make the following changes to it (marked using comment):
void show(FILE *fileptr){

    typedef struct{
        int code;
        char description[100];
        int volume;
    } product;

    product p;

    int i=1;

    // removed the re-opening of the file

    printf("\n\n\n               ****SHOWING ALL PRODUCTS****\n\n\n");
    printf("PRODUCT CODE      QUANTITY IN STOCK\n");

    // moved the first fscanf() into the while loop
    while (i<100 && !feof(fileptr)){
        fscanf( fileptr, "%d%d", &p.code, &p.volume);
        printf("%d            %d\n", &p.code, &p.volume);
        fseek(fileptr, (p.code + 1) * sizeof(p), SEEK_SET);
        i++;
    }
    printf("You may scroll back up to view the list\n\n");

}


text:
Q: Why do TINA simulator have not a single optocoupler in it's library? I am using Texas Instrument's TINA simulation software. I want to do simulation of circuit i.e. that can be used as USB charging device for smartphones .It is a buck converter that converts 110Vdc into 5Vdc,2A. I have a schematic in which there is one opto-coupler (O1)named TCMT1100  not available in the TINA library. There is no  TINA library file of TCMT1100 available on internet too. When I tried checking for alternate component ,it is also not available . Even there is not a single opto-coupler available in TINA library
So can anybody help me regarding this issue?

A: TINA is a free tool supplied by Texas Instruments to help in designing products using TI parts. It is a TI business tool. The TCMT1100 is made by Vishay, and Vishay does have SPICE model for this part, so you can technically include this into TINA library as a subcircuit or other proper import method.


text:
Q: setRootViewController: doesn't work as expected after setViewControllers: have been called I created a view controller programmatically and set it as a root controller. All worked perfect as it was expected:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
CustomViewController *vc = [[CustomViewController alloc] init];
[[self window] setRootViewController:vc];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;

Then I added an UITabBarViewController, set its 'viewControllers' property to point to (an array to) the main viewController 'vc'.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
CustomViewController *vc = [[CustomViewController alloc] init];

UITabBarController *tbc = [[UITabBarController alloc] init];
NSArray *controllers = @[vc];
[tbc setViewControllers:controllers];

[[self window] setRootViewController:vc];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;

and the view stoped to show at the screen upon launch, also there is warning about the root view controller wasn't set. After adding the string below the view of 'vc' controller is finally loaded, but there is a blank line at the bottom of the screen, as if the UIBarController modified [[UIMainScreen bounds].
[[self window] addSubview:vc.view];

I'm new to iOS development, and I'm a bit confused. It seems I don't understand some very fundamental things about the view controllers hierarchy, but after reading the "View Controller Programming Guide" by Apple, I still don't understand where am I wrong.
The setRootViewController: method should auto assign the _view of argument view controller as default view of the window, but it doesn't happen if the named view controller was already previously pointed by viewControllers property of UITabBarViewController. Though I checked the debugger and found that 'vc' object isn't changed after setViewControllers: method is called.
Could you please explain me what is going on or point me to a documentation I should read?
UPDATE: I'm not going to insert the 'vc' controller into the 'tbc' controller. What I'd like is to display the 'vc' view fullscreen, as it would normally displayed without the code about 'tbc'.
From my point of view, adding another view (tbc in my case) should NOT affect this behaviour.
Of course, that's pretty useless from practical point of view, but I'd like to know what's going on under the hood.

A: You should set tbc as rootViewController.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
CustomViewController *vc = [[CustomViewController alloc] init];

UITabBarController *tbc = [[UITabBarController alloc] init];
NSArray *controllers = @[vc];
[tbc setViewControllers:controllers];

[[self window] setRootViewController:tbc];
[[self window] addSubview:tbc.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;

A: When you add vc to the tab bar controller, it becomes a child of that controller. The root view controller of the window can't be a child, which is why you get that error. If you want vc to be full screen, then don't put it in the tab bar controller, and then at some point, you switch the window's root view controller to be the tab bar controller (if that's what you want).
You haven't said what you want to use vc for. A better way, depending on its use, might be to present it modally (so it takes the whole screen) from whichever controller is in the first tab of your tab bar controller. Do this from viewDidAppear, and it will be the firsts thing the user sees when the app starts up.


text:
Q: best way in java to rename a file , there are about 500 files in a directory I have 500 pdf files in a directory. I want to remove first five characters of a filename and rename it.

A: Use File.listFiles(...) to list the files in the directory, String.substring(...) to form the new file names, and File.rename(...) to do the renaming.
But I suggest that you have your application check that it can rename all of the files without any collisions before you start the renaming.
But @Pascal's comment is spot on.  Java is not the simplest tool for doing this kind of thing.

A: Sample code for you to rename the List of files in a given directory. In the below example, c:\Projects\sample is the folder, the files which are listed under that have been renamed to 0.txt, 1.txt, 2.txt, etc.
I hope this will solve your problem
import java.io.File;
import java.io.IOException;

public class FileOps {

    public static void main(String[] argv) throws IOException {

        File folder = new File("\\Projects\\sample");
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {

                File f = new File("c:\\Projects\\sample\\"+listOfFiles[i].getName());

                f.renameTo(new File("c:\\Projects\\sample\\"+i+".txt"));
            }
        }

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

A: something like this should do (Windows version):
import java.io.*;

public class RenameFile {
    public static void main(String[] args) {
        // change file names in 'Directory':
        String absolutePath = "C:\\Dropbox\\java\\Directory";
        File dir = new File(absolutePath);
        File[] filesInDir = dir.listFiles();
        int i = 0;
        for(File file:filesInDir) {
            i++;
            String name = file.getName();
            String newName = "my_file_" + i + ".pdf";
            String newPath = absolutePath + "\\" + newName;
            file.renameTo(new File(newPath));
            System.out.println(name + " changed to " + newName);
        }
    } // close main()
} // close class

A: As in your requirement, using java can achieve this like follows,
//path to folder location
String filePath = "C:\\CMS\\TEST";

//create direcotory TEST
File fileDir = new File(filePath);

if (!fileDir.exists()) {
   fileDir.mkdirs();
}

//create two file named 12345MyFile1.pdf, 12345MyFile2.pdf
File file1 = new File(filePath, "\\12345MyFile1.pdf");
file1.createNewFile();
File file2 = new File(filePath, "\\12345MyFile2.pdf");
file2.createNewFile();

//rename the file
File file = new File(filePath);
String[] fileList = file.list();//get file list in the folder

for (String existFileName : fileList) {
   String newFileName = existFileName.substring(5);//remove first 5 characters

   File sourceFile = new File(filePath + File.separator + existFileName);
   File destFile = new File(filePath + File.separator + newFileName);

   if (sourceFile.renameTo(destFile)) {
       System.out.println("File renamed successfully from: " + existFileName + " to: " + newFileName);
   } else {
       System.out.println("Failed to rename file");
   }
}

A: Java is a bad choice for this kind of work. A much better choice would be a JVM scripting language like Groovy. If you want to pursue this option
Step 1:
Download and install Groovy
Step 2:
Start the groovy console
Step 3:
Run this script
def dirName = "/path/to/pdf/dir"

new File(dirName).eachFile() { file ->
    def newName = file.getName()[5..-1]
    File renamedFile = new File(dirName + "/" + newName)
    file.renameTo(renamedFile)

    println file.getName() + " -> " + renamedFile.getName()
}

I'm assuming here that all the files are in the directory /path/to/pdf/dir. If some of them are in subdirectories of this directory, then use File.eachFileRecurse instead of File.eachFile.

A: If you're on Windows you should use the command prompt or a .bat file. Windows supports wildcard renames natively at the OS level so it will be orders of magnitude faster than Java, which has to iterate over all the names and issue rename calls for each one.

A: If you're on MacOS X and want to rename all files inside folders and subfolder from an External Drive, the code below will do the job:
public class FileOps {

    public static void main(String[] argv) throws IOException {
        String path = "/Volumes/FAT32/direito_administrativo/";
        File folder = new File(path);
        changeFilesOfFolder(folder);
    }

    public static void changeFilesOfFolder(File folder) {
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            int count = 1;
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    File f = new File(folder.getPath() + "/" + listOfFiles[i].getName());
                    f.renameTo(new File(folder.getPath() + "/" + count + ".flv"));
                    count++;
                } else if (listOfFiles[i].isDirectory()) {
                    changeFilesOfFolder(listOfFiles[i]);
                }
            }
        } else {
            System.out.println("Path without files");
        }
    }
}

A: This will change all the file names of the folders you mentioned:
for (int i = 0; i < folders.length; i++) {
    File folder = new File("/home/praveenr/Desktop/TestImages/" + folders[i]);
    File[] files2 = folder.listFiles();

    int count = 1;
    for (int j = 0; j <files2.length; j++,count++) {
        System.out.println("Old File Name:" + files2[j].getName());
        String newFileName = "/home/praveenr/Desktop/TestImages/" + folders[i]+"/file_"+count+"_original.jpg";
        System.out.println("New FileName:" + newFileName);
        files2[j].renameTo(new File(newFileName));
    }

}


text:
Q: ffmpeg conversion from MOV to mp4 - how to conserve creation date Windows 10 1909, latest updates.
I am helping a friend move his photos and videos from one Apple ID to another.
I have downloaded all items to my PC using iCloud for PC. I then proceeded to re-upload all the photos to the new Apple ID.
2'000 of the videos are MOV, which I cannot upload to iCloud. I seem to need to convert them to mp4 in order to upload them.
I have converted all of the MOVs to mp4 using the following batch
FOR /F "tokens=*" %%G IN ('dir /b *.MOV') DO ffmpeg -i "%%G" -f mp4 -vcodec copy -acodec mp3 "%%~nG.mp4"

This worked fine and I managed to upload the (now) mp4's to iCloud. Unfortunately all the mp4's now carry yesterday's date as creation date. In iCloud (and on the iPad) all the videos are now displayed with a creation date of 12.6.2020 and it is impossible to find a particular video. Also the context to the photos is lost.
Question:

*

*Is there any way to (batch) convert 2'000 MOV to mp4 while preserving the creation date?

*alternatively: is there any way to upload the original MOV files to iCloud?

A: You can use a utility like touch or use powershell to copy the timestamp from the source mov to the destination mp4. Using touch, it would look like touch "%%~nG.mp4" -r "%%G" when you use the same for loop.

A: The follwing seems to work:
FOR /F "tokens=*" %%G IN ('dir /b *.MOV') DO ffmpeg -i "%%G" -f mp4 -map_metadata 0 -vcodec copy -acodec mp3 "Converted\%%~nG.mp4"

-map_metadata 0 transfers the global metadata from the MOV to the mp4 file. The mp4s now have correct creation dates and iCloud sorts them under the correct date (at least the first 50 that I uploaded)


text:
Q: Adding a new bounty on a question that already has a bounty and is newer than 48 hours? I want to add another bounty (or increase it) on a question that already has a bounty which is newer than 48 hours.
If this is possible, please explain how?

A: Here in below link it is explained,
https://stackoverflow.com/help/privileges/set-bounties
The question already has a bounty. To start a second bounty on this question, you must wait for the current bounty to be awarded first.


text:
Q: How to map a function to the value parts of rules I want to map the function to the value part of these rules and get the following result:
{1 -> f[1, 2], 2 -> f[2, 3], 3 -> f[3, 4], 4 -> f[4, 5], 5 -> f[5, 6],
  6 -> f[6, 7], 7 -> f[1, 8], 8 -> f[8, 9], 9 -> f[9, 10],
 10 -> f[10, 11], 11 -> f[11, 12], 12 -> f[7, 12], 13 -> f[2, 8],
 14 -> f[3, 9], 15 -> f[4, 10], 16 -> f[5, 11], 17 -> f[6, 12],
 18 -> f[2, 9], 19 -> f[3, 10], 20 -> f[5, 10], 21 -> f[6, 11]}

But I can't implement the requirements by the following ways:
pole = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {1, 8}, {8,
        9}, {9, 10}, {10, 11}, {11, 12}, {7, 12}, {2, 8}, {3, 9}, {4,
        10}, {5, 11}, {6, 12}, {2, 9}, {3, 10}, {5, 10}, {6, 11}};
Map[f, Thread[Range[Length[pole]] -> pole], {2}]

What can I do to meet this requirement?

A: MapIndexed[#2[[1]] -> f @@ # &, pole]

{1 -> f[1, 2], 2 -> f[2, 3], 3 -> f[3, 4], 4 -> f[4, 5], 5 -> f[5, 6],
   6 -> f[6, 7], 7 -> f[1, 8], 8 -> f[8, 9], 9 -> f[9, 10],
   10 -> f[10, 11], 11 -> f[11, 12], 12 -> f[7, 12], 13 -> f[2, 8],
   14 -> f[3, 9], 15 -> f[4, 10], 16 -> f[5, 11], 17 -> f[6, 12],
   18 -> f[2, 9], 19 -> f[3, 10], 20 -> f[5, 10], 21 -> f[6, 11]}

Also
MapIndexed[#2[[1]] -> # &, f @@@ pole]

Thread[Range[Length[pole]] -> f @@@ pole]

Normal @ f @@@ AssociationThread[Range[Length[pole]], pole]

rules = Thread[Range[Length[pole]] -> pole];
Normal @ f @@@ Association @ rules

MapAt[Apply[f], rules, {All, 2}]


text:
Q: Windows 7 May 2017 Updates specific differences? For Windows 7, what, specifically, is included in the May 2017 Security Monthly Quality Rollup that is not included in the May 2017 Security Only Quality Update?

A:
What, specifically, is included in the May 2017 Security Monthly
  Quality Rollup that is not included in the May 2017 Security Only
  Quality Update?

The KB4019264 indicates the following

*

*This Monthly Rollup update does not include security fixes for
  Internet Explorer. In order to obtain the security fixes for Internet
  Explorer, the Cumulative Security Update for Internet Explorer
  KB4018271 should also be installed. Note that the Security Monthly
  Quality Rollup does contain security updates for Internet Explorer.

*If you use update management processes other than Windows Update and you automatically approve all security updates classifications for
  deployment, the May 2017 Security-Only Quality Update KB4019263, the
  May 2017 Security Monthly Quality Rollup KB4019264, and the Cumulative
  Security Update for Internet Explorer KB4018271 are deployed. We
  recommend that you review your update deployment rules to make sure
  the desired updates are deployed.

Additionally the KB4019264 article indicates:

This security update includes improvements and fixes that were a part
  of update KB4015552 (released April 18, 2017) and also resolves the
  following:

*

*Addressed issue where, after installing security update KB4015549, applications that use msado15.dll stop working.

*Updated Internet Explorer 11's New Tab Page with an integrated newsfeed.

*Deprecated SHA-1 Microsoft Edge and Internet Explorer 11 for SSL/TLS Server Authentication. See Advisory 4010323 for more information.

*Security updates to Internet Explorer, Microsoft Graphics Component, Windows COM, Microsoft ActiveX, Windows Server, Windows kernel, and
  Microsoft Windows DNS.

The KB4019263 article indicates that:

This security update includes quality improvements. No new operating
  system features are being introduced in this update. Key changes
  include:

*

*Updated Windows Cryptography API to deprecate SHA-1 for SSL/TLS Server Authentication, including in Microsoft Edge and Internet
  Explorer 11 . See Advisory 4010323 for more information.

*Security updates to Microsoft Graphics Component, Windows COM, Microsoft ActiveX, Windows Server, Windows kernel, and Microsoft
  Windows DNS.

As for the reason a Windows 7 KB article talks about Microsoft Edge, it's simply, they actually used identical verbage for the Windows 10 patch for that bullet.

A: As per Microsoft's release, which you can find here

The monthly security release includes all security fixes for vulnerabilities that affect Windows 10, in addition to non-security updates.

So the monthly update, includes all updates up until that point, where as the security only update only contains security updates, not bug fixes and improvements.
This is so deployments that automatically approve security grade updates can continue to do so without automatically approving all the updates with each release.


text:
Q: CSV Upload Issue I am uploading the csv file in php mysql with the following code:
en<?php
session_start();
if(!isset($_SESSION["UID"]))
{
header("Location: index.php");
}
if(isset($_POST["import"]))
{
//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= '';
$db= 'crm_6feb'; // Database Name.
$conn=mysqli_connect($host,$db_user,$db_password) or die("unable to connect to database");

echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
    $file = fopen($filename, "r");
    //$sql_data = "SELECT * FROM prod_list_1 ";
    $count = 0;
    while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
    {
        //print_r($emapData);
        //exit();
         $count++;
         if($count>1){
    echo    $sql = "insert into enquiry(en_name,en_mobile,en_landline,en_email,en_address,salesid,date_recieved,duplicate,date_add,ip) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]',$emapData[5],$emapData[6],'$emapData[7]',$emapData[8],'$emapData[9]')";
        $RES = mysqli_query($conn, $sql) or die("error in insert");
        }
    }
    fclose($file);
    echo 'CSV File has been successfully Imported';
    header('Location: importleads.php');
}
else
    echo 'Invalid File:Please Upload CSV File';
}?>
<!DOCTYPE html>

<title>Add Order Status</title>
<link rel="stylesheet" type="text/css" href="css/style.css">

<?php include("includes/header.php");?>

Add Order Status

<form enctype="multipart/form-data" method="post" role="form">

File Upload
<input type="file" name="file" id="file" size="150">

Only Excel/CSV File Import.

<button type="submit" class="btn btn-default" name="import" value="import">Upload</button>
</form>

Now, after I click upload button, I get the following message as an error :

C:\wamp\tmp\phpBEC.tmp error in insert

The excel contents is as follows:
Name| Mobile| Alternate Number|Email| Address| Sales id| Date Rec| Dupli|Date Add| Ip

Kindly suggest where i am doing things wrong.
Awaiting revert for your help.


text:
Q: PowerShell include input variable in output CSV I was hoping someone could help with what I thought was somthing simple.  I have a PowerShell script that reads a file of email addresses then executes an Exchange O365 command and creates a CSV file.  This works great.  However, I was hoping to include in the output line the contents of the variable used in the input. In other words possibly concatenate it to the output of the command.
$Emails = Get-Content "C:\Allqueue.csv"

foreach ($Email in $Emails) {
    Get-MoveRequest $Email |
        select displayname, alias, UserPrincipalName |
        Export-Csv -Append "C:\AllqueueResults.txt"
}

Unfortunately, the Get-Mailbox results do not include the email address, so it can't be used in the select statement.
My initial attempt was to just add $Email to the select statement like this.
select displayname, alias, UserPrincipalName, $Email

But that just created a column.
Any help would be greatly appreciated.

A: You can add a new column with the email address with a calculated property:
select displayname, alias, UserPrincipalName, @{n='Email';e={$Email}}


text:
Q: Why is the window.eventListener not being removed in my React code, although I am calling it? I am working on the following code:
  const [userNick, setUserNick] = useState("");
  const [eventListenerActive, setEventListenerActive] = useState(false);

  const promptOnLeaving = (ev) => {
      ev.returnValue = true;
  }

  useEffect(() => {
    if(userNick !== "" && !eventListenerActive){
      console.log("ADDING EVENT LISTENER")
      window.addEventListener('beforeunload', promptOnLeaving)
      setEventListenerActive(true);
    }
    else if(userNick === "" && eventListenerActive){
      console.log("REMOVING EVENT LISTENER")
      window.removeEventListener('beforeunload', promptOnLeaving)
      setEventListenerActive(false)
    }
  }, [userNick])

I want to add an event listener to my window, that listens on the beforeunloading-event, e.g the side will be closed, redirected or reloaded.
Since there are multiple input fields in the UI, I want to ask the user if he is sure he wants to close the page, although there are some form fields open.
One of them is the user nickname (here userNick).
When the user nick is empty, I want to remove the event listener, since there isn't any data that would be lost on a reload, so I, therefore, don't need to prompt the user.
On the other hand, if the user has entered text inside the UserNick input field, I want to add the event listener and prompt him, if he is sure he wants to close the page.
My problem here is, that the event listener doesn't get removed when the user empties the input field.
Adding the listener works without a problem and the listener itself does what it should.
But I can't seem to remove the listener properly.
When the else if block gets executed, my eventListenerActive state gets reset, and on the next user input there will be another eventListener making it 2 already.
I tried to add and remove the evenListeners through external buttons with the onClick-event, and that did actually work.
Additionally, I also read that the event-handling function should not be anonymous, when I want to remove it, so I gave it a name here to.
So what am I doing wrong here, that the eventListener won't be removed?
Thanks in advance

A: I figured it out myself.
This article was very helpful:
Removing event handlers in React
The actual problem was, that javascript internally compares the handler function when the listener was added with the handler function when the listener is being removed.
Since React re-renders the component, the handler function gets initialized again which results in an unmatch between the "old" handler function and the "new" one.
I had to add a useCallback-function to my handler, so the handler get memoized and stays the same when compared on removeEventListener:
  const promptOnLeaving = useCallback((ev) => {
    ev.returnValue = true;
  }, [])


text:
Q: Get woocommerce category ID by name What are other methods to get ID of category by name.
I have loop and need to check if category exist if it is then return category ID else make new one.
This is the function what check for the category ID in woocommerce and it was working fine, but not anymore.
    function get_product_category_id($product_name){

    $product_cat = get_term_by( 'name', $product_name, 'product_cat' );

    if ( $product_cat ) {
        return $product_cat->term_id;
    }
    return 0;
  }

This function works if i use with Wordpress post categories but not anymore with Woocommerce categories.
And now my function to assigning category to product is not working, because i cant get woocommerce category id...
wp_set_object_terms($product_id, $cat_id, 'product_cat');


text:
Q: Postgres - how can I move a large table out of production while maintaining access to production data to interpret and use the large table? Our production database includes a table that is at about 100 million records and will likely get to a billion records before too long. Every other table is small--less than a million records.
The large table depends on the small tables. Individual records are calculated from the small tables and can only be properly interpreted using the context the small tables provide.
We want copies of the small tables for use in staging and testing. We also want them for interpretation of archived versions of the large table. It would be easy to get and maintain these copies if the large table weren't in the production db, so it's tempting to move that table somewhere else. However, we want the systems that interact with the large table to have up-to-date information on the small tables.
Is there a nice way to move the large table out of the production database while maintaining its access to updates on the small tables that are in the production database?


text:
Q: Basic Topology: Cofinite Topology $A$ = $R$ - {$(n+1)/(n+2):n \in Z+$}
The definition of the cofinite topology in my text is as follows:
Let $X$ be any set.  The collections $T$ of all subsets $U$ of $X$ such that either $U = \varnothing$ or $X - U$ is a finite set is a topology for $X$.
Given A above, determine $Cl(A), Int(A), Ext(A)$ and $Bd(A)$.
Initially, I determined that $R$ - ($R$ - {$(n+1)/(n+2):n \in Z+$}) = {$2/3, 3/4, 4/5, 5/6,...$}.
(a) $Cl(A)$: The smallest closed set that will contain this set is $R$.  Is that correct?
(d) $Bd(A)$:  My thought is that $Bd(A)$ would be {$2/3, 3/4, 4/5, 5/6,...$}.  I feel like if I can understand $Bd(A)$ then I can work backwards to understand $Int(A)$ and $Ext(A)$.

A: (a) The Cl$(A)$ is indeed $\mathbb{R}$, since a closed set is either finite or all of $\mathbb{R}$; and no finite set contains $A$.
(b) First notice that the boundary of a subset is closed, and hence finite or all of $\mathbb{R}$, so it cannot be $\{2/3,3/4,\cdots\}$.
Since Int$(A) \subset A$, we get $\mathbb{R} -$ Int$(A)\supset \mathbb{R} - A$. But  $\mathbb{R} -$ Int$(A) = $Cl$(A) - $Int$(A) = $Bd$(A)$. Therefore, Bd$(A) \supset \mathbb{R} - A = \{2/3,3/4,\cdots\}$ and hence is infinite. Since Bd$(A)$ is closed, it must therefore be all of $\mathbb{R}$. And so Int$(A) = \emptyset$.

A: Def'n: A subset $S$ of a space $X$ is dense in $X$ iff $\bar S=X.$
In the co-finite topology on an infinite set $X,$ every infinite subset of $X$ is dense in $X,$ because if $Y$ is a non-empty open subset of $X$ then $Y\cap S\ne \phi.$ And if $S$ is an infinite, co-infinite subset of $X$, then $S$ and its complement have empty interior, because no non-empty open set can be a subset of either of them.
So both $A$ and its complement are dense in $R,$ and each of them has empty interior.


text:
Q: Efficient minimal spanning tree in metric space I have a large set of points (n > 10000 in number) in some metric space (e.g. equipped with Jaccard Distance). I want to connect them with a minimal spanning tree, using the metric as the weight on the edges.

*

*Is there an algorithm that runs in less than O(n2) time?

*If not, is there an algorithm that runs in less than O(n2) average time (possibly using randomization)?

*If not, is there an algorithm that runs in less than O(n2) time and gives a good approximation of the minimum spanning tree?

*If not, is there a reason why such algorithm can't exist?

Thank you in advance!
Edit for the posters below:
Classical algorithms for finding minimal spanning tree don't work here. They have an E factor in their running time, but in my case E = n2 since I actually consider the complete graph. I also don't have enough memory to store all the >49995000 possible edges.

A: Apparently, according to this: Estimating the weight of metric minimum spanning trees in sublinear time there is no deterministic o(n^2) (note: smallOh, which is probably what you meant by less than O(n^2), I suppose) algorithm. That paper also gives a sub-linear randomized algorithm for the metric minimum weight spanning tree.
Also look at this paper: An optimal minimum spanning tree algorithm which gives an optimal algorithm. The paper also claims that the complexity of the optimal algorithm is not yet known!
The references in the first paper should be helpful and that paper is probably the most relevant to your question.
Hope that helps.

A: When I was looking at a very similar problem 3-4 years ago, I could not find an ideal solution in the literature I looked at.
The trick I think is to find a "small" subset of "likely good" edges, which you can then run plain old Kruskal on.  In general, it's likely that many MST edges can be found among the set of edges that join each vertex to its k nearest neighbours, for some small k.  These edges might not span the graph, but when they don't, each component can be collapsed to a single vertex (chosen randomly) and the process repeated.  (For better accuracy, instead of picking a single representative to become the new "supervertex", pick some small number r of representatives and in the next round examine all r^2 distances between 2 supervertices, choosing the minimum.)
k-nearest-neighbour algorithms are quite well-studied for the case where objects can be represented as vectors in a finite-dimensional Euclidean space, so if you can find a way to map your objects down to that (e.g. with multidimensional scaling) then you may have luck there.  In particular, mapping down to 2D allows you to compute a Voronoi diagram, and MST edges will always be between adjacent faces.  But from what little I've read, this approach doesn't always produce good-quality results.
Otherwise, you may find clustering approaches useful: Clustering large datasets in arbitrary metric spaces is one of the few papers I found that explicitly deals with objects that are not necessarily finite-dimensional vectors in a Euclidean space, and which gives consideration to the possibility of computationally expensive distance functions.


text:
Q: Illegal Instruction: 4 for iOS I have currently updated an app and pushed to App Store. After the approval process, it can be downloaded from AppStore.
The issue is, "some" of the users report that they cannot switch on the app, either update or download from scratch.
Some of the devices they use:

*

*iPod Touch (5th Generation)

*iPhone 5

*iPad 2 ''newly added''

The console log shows like this:
UIKitApplication:{app-identifier} exited abnormally with signal 4: Illegal Instruction: 4
I have also got the crash report like this:
Incident Identifier: 1912AA89-01F4-4BFE-8BD8-2D8EB3B4B988
CrashReporter Key:   4e0582bb30455ff2c12665099359dfddd3ec9bab
Hardware Model:      iPod5,1
Process:         'app_name' [551]
Path:            /var/mobile/Applications/C589BCAA-B833-4708-93CA-CDD2ABCBA38A/'app_name'.app/'app_name'
Identifier:      'app_name'
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2013-07-16 15:45:42.278 +0800
OS Version:      iOS 6.1.3 (10B329)
Report Version:  104

Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x00000000e7f5e2fa
Highlighted Thread:  0

I cannot find much information on the Internet related to Illegal Instruction: 4, some of those are listed here and here.
They lead me to suspect the case is due to:
compiler issue

*

*new CPU

*like A6 / A6x

*armv7s

Does anyone know the reason?

A: Apple did not give any comment, after doing the Support request.
We uploaded the new ipa with all the same settings to iTunes Store again, and ask for Expedited Review. Apple approves the app in one day. Then, problem no longer exists.


text:
Q: How to go from handlebars.js to react I had a project about a month ago that used handlebars.js for templates, and now we have to update it to use react.js instead. How would I approach that? This is one of the pages I'm in charge of changing.
Home page:

      Geek Emporium

Your one stop shop for all your nerdy needs!

        {{#each posts as |post|}}

        {{> post-info-homepage post }}

        {{/each}}


text:
Q: What is the best way to go about protecting a user's password going from iPhone app -> PHP -> MySQL? I need to send the following up to my server to be stored via POST:
&username=xxxx&password=zzzzz
Should I encrypt this before sending? Or just send it via HTTPS (SSL) to my PHP page?
On the PHP page should I then do the encryption to save it to the MySQL server?
Need a little help here as to what is the best iPhone app -> PHP -> MySQL way to do this.

A: Sending it over HTTPS should be fine for communicating between the iPhone app and PHP. You should hash the password, using a good password hashing algorithm, as soon as possible.
If you're not familiar with good password hashing practices, you might find this useful:
How do you use bcrypt for hashing passwords in PHP?

A: You can encrypt password using md5() or make your own encryption/decryption function.
Here is the example
From client end
 $password = md5('password');

To check with database
 //security check
 $user = mysql_real_escape_string($_POST['username']);

 mysql_query("SELECT user_name, email FROM users WHERE username='".$user."' AND MD5(password)='".$password."'");

A: HTTPS/SSL should be enough if you simply want to protect your data during transmission. Obviously you may also need to store encrypted values in your MySQL db. In this case you should also encrypt your credentials before doing your sql query.

A: HTTPS should be sufficient to protect the data en-route, as others have said. On the server side, you should not store the password in any reversible form (unless for some reason you need the plaintext, such as to pass it to a third party). I would recommend using a salted cryptographic hash.
Essentially, what you do is this: when the user sets a password, you generate a new random string (the salt) and then store the password as the result of hash(salt + password). This hash should be a strong cryptographic function (nowadays I would recommend SHA-256 or similar). In this way, the user's plaintext password cannot be retrieved, even if your server is compromised.
When the user submits their password, you can simply compute hash(salt + password) again and check that the result matches what is stored in the database.


text:
Q: Closest matrix that achieves positive semidefinite condition Suppose we have two symmetric positive semidefinite $n$ dimensional matrices $A$ and $B$. We use the notation $X\leq Y$ means that $Y-X$ is positive semidefinite.
Suppose $A \not\leq B$ i.e. $B-A$ has at least one negative eigenvalue. We are interested in perturbing $A$ to some positive semidefinite $\tilde{A}$ such that $\tilde{A} \leq B$ while minimizing $|A-\tilde{A}|_1$ where $|\cdot|_1$ is the nuclear norm and defined by
$$|X|_1 := \text{Tr} \left( \sqrt{X^\dagger X} \right)$$
and $X^\dagger$ is the transpose conjugate of $X$.
To make things simpler, I will now consider the case where $A$ is a rank-$1$ matrix. Is it true that
$$\tilde{A} = \lambda A$$
for some $\lambda < 1$? An immediate corollary is that $\tilde{A}\leq A$.

EDIT: After a bit of searching, I found a result for the same question but where the norm considered is the induced 2-norm (spectral norm) or the Frobenius norm.
For the induced 2-norm (spectral norm), it holds that $\tilde{A} = A - \lambda I$ where $\lambda$ is the smallest positive number such that $\tilde{A}\leq B$ is true. So for this case, my conjecture that $\tilde{A} = \lambda A$ is false but the statement $\tilde{A}\leq A$ is true.
For the Frobenius norm case, we first write the polar decomposition of $B-A = UH$. Then $B -\tilde{A} = \frac{1}{2}(B - A + H)$ is the solution. Since $H= ((B-A)^\dagger(B-A))^{1/2}\geq B-A$, one can again conclude that $\tilde{A}\leq A$
I do not know what happens for the 1-norm though.

EDIT 2: Here is another look at the problem that almost works. Suppose the solution $\tilde{A}\not\leq A$. We prove that there exists some $A'$ such that $A'\leq B, A'\leq A$ and $|A'-A|_1\leq|\tilde{A}-A|_1$.
Let us diagonalize $\tilde{A}-A = ZDZ^\dagger = ZD^{+}Z^\dagger + ZD^{-}Z^\dagger$ where $D$ is diagonal, $D^{\pm}$ is also diagonal and includes the nonnegative and negative eigenvalues respectively. By assumption $\tilde{A}\leq B \implies A + ZD^{+}Z^\dagger + ZD^{-}Z^\dagger \leq B$. Define $A':= A + ZD^{-}Z^\dagger$.
Since $ZD^{+}Z^\dagger$ is positive semidefinite, it holds that $A' = A + ZD^{-}Z^\dagger \leq B$.
Since $ZD^{-}Z^\dagger$ is negative definite, it follows that $A'\leq A$.
Finally, $|A' - A|_1 = |ZD^{-}Z^\dagger|_1 = |D^{-}|_1 \leq |D^{+}+D^{-}|_1 =  |Z(D^{+}+D^{-})Z^\dagger|_1 = |\tilde{A} - A|_1$
EDIT 3 Unfortunately, the $A'$ constructed is not positive semidefinite in general.

A: Some thoughts on the problem:
As a further simplification, I suggest that we say that $\tilde A$ does not only satisfy $\tilde A \leq B$, but also has a rank of $1$.  If your hypothesis is correct, then this assumption should not change our answer. Write
$$
A = \alpha xx^T, \quad \tilde A = \beta yy^T
$$
for some scalars $\alpha, \beta > 0$ and unit vectors $x,y$. The minimization problem now becomes
$$
\min_{y \in \Bbb R^n, \beta > 0} |\alpha xx^T - \beta yy^T|_1 \quad \text{s.t.} \quad \beta yy^T \leq B.
$$
Now, I make several claims:

*

*$yy^T \leq B \iff \beta \leq [y^TB^+y]^{-1}$
where $B^+$ denotes the Moore-Penrose pseudoinverse of $B$. I give some proofs of this here.

*$\alpha xx^T - \beta yy^T$ has the same nuclear norm as that of the $2 \times 2$ matrix $\pmatrix{\alpha  & \alpha (x^Ty)\\ -\beta (x^Ty) & -\beta}$. (explanation below).

*The nuclear norm turns out to be $|M|_1 = \sqrt{(\beta - \alpha)^2 + 4(1 - (x^Ty)^2)}$.
My first approach would be to, by considering the nuclear norm as a function of $\beta$, maximize the nuclear norm given a particular choice of $y$.

The nuclear norm of a symmetric matrix is the sum of the absolute values of its eigenvalues. With that said, we want the eigenvalues of $M = \alpha xx^T - \beta yy^T$.
$$
M = \pmatrix{x & y} \pmatrix{\alpha & 0 \\ 0 & -\beta} \pmatrix{x & y}^T.
$$
Because $AB,BA$ have the same non-zero eigenvalues, $M$ will have the same non-zero eigenvalues as the $2 \times 2$ matrix
$$
N = \pmatrix{\alpha & 0 \\ 0 & -\beta} \pmatrix{x & y}^T\pmatrix{x & y} = \pmatrix{\alpha x^Tx  & \alpha x^Ty\\ -\beta x^Ty & -\beta y^Ty}.
$$
Point 3:
$$
\lambda^2 + (\beta - \alpha) \lambda + ((x^Ty)^2 - 1)\alpha\beta \implies\\
\lambda = \frac{\alpha - \beta \pm \sqrt{(\beta - \alpha)^2 + 4(1 - (x^Ty)^2)}}{2}
$$


text:
Q: Is there a way to set a fallback git commit template? Reading the docs doesn't tell me whether this can be done or not, which indicates to me it can't be done, but I want to check with some smarter people. I think it would be very helpful to indicate both a project template template = .git/gitmessage and a global template template = ~/.gitmessage to fallback to if the project one doesn't exist. I have tried adding 2 template entries in ~/.gitconfig and pointed one at a global template and one at a local template and that didn't work no matter what order I put them in.
Relevant documentation:

When editing the commit message, start the editor with the contents in the given file. The commit.template configuration variable is often used to give this option implicitly to the command. This mechanism can be used by projects that want to guide participants with some hints on what to write in the message in what order. If the user exits the editor without editing the message, the commit is aborted. This has no effect when a message is given by other means, e.g. with the -m or -F options.

A: Git has two kinds of configuration options: options which can have multiple values and options which can have at most one value.  I believe that commit.template is the latter.
The general pattern for options which take at most one value is that more narrowly scoped config files take precedence over more broadly scoped configuration files.  That is, the .git/config in the repository (the local file) takes precedence over ~/.gitconfig (the global file), which in turn takes precedence over /etc/gitconfig (the system file).
If you want to set this option globally, you can do that in your ~/.gitconfig file and then set a project-specific option in the config file in the repository.  That should override the value in your global file and therefore use the project-specific template.  For projects which don't have their own template, you'll use the one defined in the global file.


text:
Q: Can Node.js use another filename for the directory index file, instead of `index.js`? When we write require('some/directory').
It will look for some/directory/index.js if some/directory is a directory.
But what if I want to use another file name like _index.js? (So it can be sorted ahead its sibling files in the dir-tree.)

A: The default file name is index.js, but you can use another file through package.json.
In this file, you should have key name:
  "main": "index",

replace by any name you prefer, even in another directory:
  "main": "./lib/index",

see https://docs.npmjs.com/files/package.json

A: It is hardcoded inside of the node core, you can see it here in action:
https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L224
As it says in docs, first it tries to get the package from node_modules, if there is no such package - tries to get it from index.js from that folder, and as a last resort it tries to open specified (if any) package.json in that folder. If none found - it fails with an error, stating that there is no such module

A: This is not possible.
The default file name is hard-coded and should be either index.js or index.node according to this:
https://nodejs.org/api/modules.html#modules_folders_as_modules

A: Super simple solution that works for me:
someFileYouWantAsIndex.js
// ...code
// ...code
module.exports = { whatever };

index.js
const stuff = require('./someFileYouWantAsIndex.js');
module.exports = stuff;


text:
Q: How TCP window size is impacted on setting SO_RCVBUF (using setsockopt) after three way handshake? I accept a TCP connection with default values and I observe SYN, ACK being sent with a window size of 64K and a window scale factor of 7.
After 3 way handshake is complete and exchanging some control packets for my app, I use setsockopt() to set SO_RCVBUF to 20K. My question is when the advertised window will get updated in this case?
As the sb_hiwat has been modified to a smaller value, shouldn't I see a window update packet right away? What I am seeing is a gradual decrease in advertised window which takes ~4 seconds to reach from ~7MB to 20K.

A: I don't know why you would ever want to reduce the receive buffer at all.
You may not even be able to once transmissions have started, but in any case if there is data in the receive buffer you certainly can't expect it to get set to less than that immediately. Otherwise data would have to be discarded, and TCP doesn't allow that.
I suggest you leave it alone.


text:
Q: How to predict the risk of an event? I'm working on a medical problem, where I want to analyze the effect of taking cholesterol medications on the occurrence of heart attack. Once a medication with a specific dosage is prescribed, it'll be used by a patient for $k$ consecutive periods (i.e., refills periods).
Moreover, I have a retrospective data of several patients, where each patient

*

*is prescribed with different dosages,

*has the fixed $k$ periods of refill,

*may have some instances of heart attack during those $k$ periods, and

*has other risk factors (as confounding factors).

Now, if a patient takes a specific dosage of that medication for $k$ consecutive periods (in a prospective sense), how can I predict the risk of heart attack at any time during those $k$ periods? I guess there might be some relevance to Cox survival analysis, but I'm not quite sure. So, any comment/help is really appreciated!
Thanks.

A: First thought that comes to mind is using a binary logistic regression. You can predict probability of a heart attack happening after fitting your dataset to a logistic model.
Here is the formula for generating the probability of $Y_i = 1$
$
P(Y_i = 1|\, x_{i1},\ldots,x_{ip}) = \frac{e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip}}}{1+e^{\beta_0 + \beta_1 x_{i1} + \ldots + \beta_p x_{ip} }} = \pi_i
$


text:
Q: Which nodes will execute dataframe.write function? When my program executes the dataframe.write function, which nodes will execute this function? The slave nodes will write the results to disk directly or it will send all the results to driver to let driver do this job?

A: The worker nodes. Writing is distributed as is nearly all operations (except collect, take, toPandas, etc)


text:
Q: How to disable Migration Verification during every DbContext initialization I am using CodeFirst approach in Entity Framework 6 and running my migration script manually to create Db and later update the changes in the schema.
I have noticed that every time the context is initialized, it checks for the "INFORMATION_SCHEMA.TABLES" and "MigrationHistory" metadata in the database. That adds 2 additional queries for each call.
This may not be a desirable situation for production environment. Is there a way to set it only once during application startup and these 2 process does not executed every time the DbContext is initialized.
Thanks

A: Finally solved it the following way and wish to share the solution:
class MyCustomDbConfiguration : DbConfiguration
        {
        public MyCustomDbConfiguration()
            {
            SetDatabaseInitializer(new NullDatabaseInitializer<MyDbContext>());
            }
        }


text:
Q: Addition of limit switch for power supply stops circuit from working. Circuit works fine without the switch? I am having an issue with a limit switch to turn on and off a circuit. I am using a L7805 5V regulator with a regular 9V battery as the power supply for my circuit. When I plug in the 9V battery normally, the circuit functions fine, however, if I add a limit switch/microswitch to turn on and off the circuit, the circuit does not function. I've tested countless things to no avail:

*

*Different limit switches with different current ratings ranging from 2A to 5A and 50V to 250V AC or DC

*Confirmed that the limit switches work properly when pressed using the multimeter's the continuity function

*Made sure that the circuit works fine when I plug in the 9V normally by hand into the 5V regulators

*Switched the breadboards that the circuit is currently onto different breadboards

*Edit: Forgot to include that I've tried putting the limit switch in different places, I tried putting it between the 5V regulator and the 9V battery directly, and the 9V battery's ground and the 5V regulator's ground. Both do not seem to work either

I'm very confused at this point because the limit switches seem to function fine, and the circuit also functions fine without the limit switch. I did a search already and didn't find something similar to my issue, so apologies if this has already been asked. Any possible ideas/or even remote pointers would be much appreciated because I'm still new to electronics. A schematic of my circuit is also attached below in case it helps, its purpose is to drive a servo for a specific amount of time. Much thanks!

A: Your limit switch is normally open, and closes when the limit is reached.
I expect you want to have your circuit powered when the servo is in the middle of the range, and un-powered when it reaches the limit, your switch does the exact opposite powering the circuit only when you're at the limit.
To do this you need a normally closed limit switch (or a limit switch which has both sorts of contacts).


text:
Q: iPhone Developer Community voice over IP Anyone know if there exists any Broadcast/Groups system online that allows developers to become connected in real time to be able to voice chat and keyboard chat, specific to their needs, something a little more immediate as opposed to forums/stackoverflow/pm software.
I for example would like to join a voip chat related to mapkit for iPhone... So while I'm working with mapkit for the next few days, I'd like to become connected with likeminded developers, and from there add them to my friends list or something...
Unless I've just missed it, I'm not aware of anything like this...and if it doesn't exist, there's a free startup company idea for someone...

A: I am not aware of any VOIP chat forum but I do know that there is a text chat rooms option on stackoverflow. You can either create your own chatroom or join one of the existing ones, like:
https://chat.stackoverflow.com/rooms/682/iphone-ipad


text:
Q: Appending a ListBox list in AHK I have a text file with "usernames" on it:
; info.txt
user1
user2
user3
user4

What I want to do is create a ListBox with all the users I have in that file. My first thought was this:
Gui, Add, Button, , Log in
getUsers()
Gui, Show

getUsers()
{
    loop
    {
        FileReadLine, line, info.txt, %A_Index%
        if ErrorLevel
            Break
        Gui, Add, ListBox, cBlue, %line%
    }
}

But then instead of getting this:
Expected
I got this:
Reality
Which makes complete sense, but how can I do this correctly? I couldn't find any sort of append option for it.

A: Your code looks good, but the choices aren't added with one line each. Instead, you'll have to state a

a pipe-delimited list

(see here)
So your function will instead concatenate a string and then add it to the gui once:
getUsers()
{
    choices := "" ; if you leave this line out, it'll work too I guess, but you might get a warning if #warn was set so
    loop
    {
        FileReadLine, line, info.txt, %A_Index%
        if ErrorLevel
            Break
        choices .= line "|"
    }
    Gui, Add, ListBox, cBlue, %choices%
}


text:
Q: Buddypress and a wordpress child theme? Ok I'm lost I've read lot's of threads concerning how to to apply a buddypress child theme and now I've just read: http://bpdevel.wordpress.com/2013/11/13/the-future-of-the-bp-default-theme/
which seems to say that buddypress no longer supports child themes….
I'm really lost how do i go about apply changes to buddypress's default pages in a manner that will hold up for future updates and not screw with my parent theme…
I currently have /wp-content/themes/child-theme/buddypress/COPY FROM buddypress/bp-themes/bp-default/ in my child theme but it fails to recognize the theme files unless i move them up to the child theme folder… and when i do it then rips out the css and js for the buddypress pages….
How do i go about setting up buddypress's theme files in my child theme.
Kind reagrds
Chris.
P.S I've also read :
http://codex.buddypress.org/themes/theme-compatibility-1-7/template-hierarchy/
http://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/
which just confused me further…
Do i copy over the bp-legacy folder if i do won't this be discontinued…

A: BuddyPress now utilises a template hierarchy in the same way as WordPress does.
If you do nothing to a standard WordPress theme, BuddyPress will use the page.php template to display BuddyPress content. However, you can style BuddyPress differently to page.php and that's where the template hierarchy comes in.
To introduce your own custom BuddyPress templates, start by creating a new folder called 'buddypress' inside your WordPress theme. So your folder structure will look like this: /wp-content/themes/your-theme/buddypress/. All BuddyPress templates that you create from now on are contained within the /buddypress/ folder.
EXAMPLE: Use a custom template to display the example.com/members/username/activity/mentions/ page.
If at any point you need more info, you can refer to the BuddyPress Template Hierarchy article for an in-depth explanation.
Step 1: Create the folders:
/buddypress/members/single/

Step 2: Create the file:
/buddypress/members/single/index-action-{action}.php

Note: In this example, {action} will be mentions. If you were creating a template to style the favorites page then {action} will be favorites.
So you should have:
/buddypress/members/single/index-action-mentions.php

That's all there is to it. Whatever you put in your index-action-mentions.php file will display on the example.com/members/username/activity/mentions/ page.


text:
Q: How to intercept 404 using Owin middleware Background
First let me explain the background. I am working on a project that attempts to marry a backend server that uses Web API configured via OWIN- hosted on IIS now, but potentially other OWIN-supported hosts in the future- to a frontend using AngularJS.
The AngularJS frontend is entirely static content. I completely avoid server-side technologies such as MVC/Razor, WebForms, Bundles, anything that has to do with the frontend and the assets it uses, and defer instead to the latest and greatest techniques using Node.js, Grunt/Gulp, etc. to handle CSS compilation, bundling, minification, etc. For reasons I won't go into here, I keep the frontend and server projects in separate locations within the same project (rather than stick them all in the Host project directly (see crude diagram below).
MyProject.sln
server
  MyProject.Host
     MyProject.Host.csproj
     Startup.cs
     (etc.)
frontend
  MyProjectApp
     app.js
     index.html
     MyProjectApp.njproj
     (etc.)

So as far as the frontend is concerned, all I need to do is get my Host to serve my static content. In Express.js, this is trivial. With OWIN, I was able to do this easily using Microsoft.Owin.StaticFiles middleware, and it works great (it's very slick).
Here is my OwinStartup configuration:
string dir = AppDomain.CurrentDomain.RelativeSearchPath; // get executing path
string contentPath = Path.GetFullPath(Path.Combine(dir, @"../../../frontend/MyProjectApp")); // resolve nearby frontend project directory

app.UseFileServer(new FileServerOptions
{
    EnableDefaultFiles = true,
    FileSystem = new PhysicalFileSystem(contentPath),
    RequestPath = new PathString(string.Empty) // starts at the root of the host
});

// ensure the above occur before map handler to prevent native static content handler
app.UseStageMarker(PipelineStage.MapHandler);

The Catch
Basically, it just hosts everything in frontend/MyProjectApp as if it were right inside the root of MyProject.Host. So naturally, if you request a file that doesn't exist, IIS generates a 404 error.
Now, because this is an AngularJS app, and it supports html5mode, I will have some routes that aren't physical files on the server, but are handled as routes in the AngularJS app. If a user were to drop onto an AngularJS (anything other than index.html or a file that physically exists, in this example), I would get a 404 even though that route might be valid in the AngularJS app. Therefore, I need my OWIN middleware to return the index.html file in the event a requested file does not exist, and let my AngularJS app figure out if it really is a 404.
If you're familiar with SPAs and AngularJS, this is a normal and straight-forward approach. If I were using MVC or ASP.NET routing, I could just set the default route to an MVC controller that returns my index.html, or something along those lines. However, I've already stated I'm not using MVC and I'm trying to keep this as simple and lightweight as possible.
This user had a similar dilemma and solved it with IIS rewriting. In my case, it doesn't work because a) my content doesn't physically exist where the rewrite URL module can find it, so it always returns index.html and b) I want something that doesn't rely on IIS, but is handled within OWIN middleware so it can be used flexibly.
TL;DNR me, for crying out loud.
Simple, how can I intercept a 404 Not Found and return the content of (note: not redirect) my FileServer-served index.html using OWIN middleware?

A: The solution that Javier Figueroa provided really works for my project. The back end of my program is an OWIN self-hosted webserver, and I use AngularJS with html5Mode enabled as the front end. I tried many different ways writing a IOwinContext middleware and none of them works till I found this one, it finally works! Thanks for sharing this solution.
solution provided by Javier Figueroa
By the way, the following is how I apply that AngularServerExtension in my OWIN startup class:
        // declare the use of UseAngularServer extention
        // "/" <= the rootPath
        // "/index.html" <= the entryPath
        app.UseAngularServer("/", "/index.html");

        // Setting OWIN based web root directory
        app.UseFileServer(new FileServerOptions()
        {
            RequestPath = PathString.Empty,
            FileSystem = new PhysicalFileSystem(@staticFilesDir), // point to the root directory of my web server
        });

A: I wrote this little middleware component, but I don't know if it's overkill, inefficient, or if there are other pitfalls. Basically it just takes in the same FileServerOptions the FileServerMiddleware uses, the most important part being the FileSystem we're using. It is placed before the aforementioned middleware and does a quick check to see if the requested path exists. If not, the request path is rewritten as "index.html", and the normal StaticFileMiddleware will take over from there.
Obviously it could stand to be cleaned up for reuse, including a way to define different default files for different root paths (e.g. anything requested from "/feature1" that is missing should use "/feature1/index.html", likewise with "/feature2" and "/feature2/default.html", etc.).
But for now, it this works for me. This has a dependency on Microsoft.Owin.StaticFiles, obviously.
public class DefaultFileRewriterMiddleware : OwinMiddleware
{
    private readonly FileServerOptions _options;

    /// <summary>
    /// Instantiates the middleware with an optional pointer to the next component.
    /// </summary>
    /// <param name="next"/>
    /// <param name="options"></param>
    public DefaultFileRewriterMiddleware(OwinMiddleware next, FileServerOptions options) : base(next)
    {
        _options = options;
    }

    #region Overrides of OwinMiddleware

    /// <summary>
    /// Process an individual request.
    /// </summary>
    /// <param name="context"/>
    /// <returns/>
    public override async Task Invoke(IOwinContext context)
    {
        IFileInfo fileInfo;
        PathString subpath;

        if (!TryMatchPath(context, _options.RequestPath, false, out subpath) ||
            !_options.FileSystem.TryGetFileInfo(subpath.Value, out fileInfo))
        {
            context.Request.Path = new PathString(_options.RequestPath + "/index.html");
        }

        await Next.Invoke(context);
    }

    #endregion

    internal static bool PathEndsInSlash(PathString path)
    {
        return path.Value.EndsWith("/", StringComparison.Ordinal);
    }

    internal static bool TryMatchPath(IOwinContext context, PathString matchUrl, bool forDirectory, out PathString subpath)
    {
        var path = context.Request.Path;

        if (forDirectory && !PathEndsInSlash(path))
        {
            path += new PathString("/");
        }

        if (path.StartsWithSegments(matchUrl, out subpath))
        {
            return true;
        }
        return false;
    }
}

A: If you're using OWIN, you should be able to use this:
using AppFunc = Func<
       IDictionary<string, object>, // Environment
       Task>; // Done

public static class AngularServerExtension
{
    public static IAppBuilder UseAngularServer(this IAppBuilder builder, string rootPath, string entryPath)
    {
        var options = new AngularServerOptions()
        {
            FileServerOptions = new FileServerOptions()
            {
                EnableDirectoryBrowsing = false,
                FileSystem = new PhysicalFileSystem(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath))
            },
            EntryPath = new PathString(entryPath)
        };

        builder.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions);

        return builder.Use(new Func<AppFunc, AppFunc>(next => new AngularServerMiddleware(next, options).Invoke));
    }
}

public class AngularServerOptions
{
    public FileServerOptions FileServerOptions { get; set; }

    public PathString EntryPath { get; set; }

    public bool Html5Mode
    {
        get
        {
            return EntryPath.HasValue;
        }
    }

    public AngularServerOptions()
    {
        FileServerOptions = new FileServerOptions();
        EntryPath = PathString.Empty;
    }
}

public class AngularServerMiddleware
{
    private readonly AngularServerOptions _options;
    private readonly AppFunc _next;
    private readonly StaticFileMiddleware _innerMiddleware;

    public AngularServerMiddleware(AppFunc next, AngularServerOptions options)
    {
        _next = next;
        _options = options;

        _innerMiddleware = new StaticFileMiddleware(next, options.FileServerOptions.StaticFileOptions);
    }

    public async Task Invoke(IDictionary<string, object> arg)
    {
        await _innerMiddleware.Invoke(arg);
        // route to root path if the status code is 404
        // and need support angular html5mode
        if ((int)arg["owin.ResponseStatusCode"] == 404 && _options.Html5Mode)
        {
            arg["owin.RequestPath"] = _options.EntryPath.Value;
            await _innerMiddleware.Invoke(arg);
        }
    }
}

A: Answer given by Javier Figueroa here works and really helpful! Thanks for that! However, it has one odd behavior: whenever nothing exists (including the entry file), it runs next pipeline twice. For example, below test fails when I apply that implementation through UseHtml5Mode:
[Test]
public async Task ShouldRunNextMiddlewareOnceWhenNothingExists()
{
    // ARRANGE
    int hitCount = 0;
    var server = TestServer.Create(app =>
    {
        app.UseHtml5Mode("test-resources", "/does-not-exist.html");
        app.UseCountingMiddleware(() => { hitCount++; });
    });

    using (server)
    {
        // ACT
        await server.HttpClient.GetAsync("/does-not-exist.html");

        // ASSERT
        Assert.AreEqual(1, hitCount);
    }
}

A few notes about my above test if anyone is intrested:

*

*It uses Microsoft.Owin.Testing.

*Test framework is NUnit.

*UseCountingMiddleware implementation is available here.

The implementation I went with which makes the above test pass is as below:
namespace Foo
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public class Html5ModeMiddleware
    {
        private readonly Html5ModeOptions m_Options;
        private readonly StaticFileMiddleware m_InnerMiddleware;
        private readonly StaticFileMiddleware m_EntryPointAwareInnerMiddleware;

        public Html5ModeMiddleware(AppFunc next, Html5ModeOptions options)
        {
            if (next == null) throw new ArgumentNullException(nameof(next));
            if (options == null) throw new ArgumentNullException(nameof(options));

            m_Options = options;
            m_InnerMiddleware = new StaticFileMiddleware(next, options.FileServerOptions.StaticFileOptions);
            m_EntryPointAwareInnerMiddleware = new StaticFileMiddleware((environment) =>
            {
                var context = new OwinContext(environment);
                context.Request.Path = m_Options.EntryPath;
                return m_InnerMiddleware.Invoke(environment);

            }, options.FileServerOptions.StaticFileOptions);
        }

        public Task Invoke(IDictionary<string, object> environment) =>
            m_EntryPointAwareInnerMiddleware.Invoke(environment);
    }
}

The extension is pretty similar:
namespace Owin
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public static class AppBuilderExtensions
    {
        public static IAppBuilder UseHtml5Mode(this IAppBuilder app, string rootPath, string entryPath)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            if (rootPath == null) throw new ArgumentNullException(nameof(rootPath));
            if (entryPath == null) throw new ArgumentNullException(nameof(entryPath));

            var options = new Html5ModeOptions
            {
                EntryPath = new PathString(entryPath),
                FileServerOptions = new FileServerOptions()
                {
                    EnableDirectoryBrowsing = false,
                    FileSystem = new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath))
                }
            };

            app.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions);

            return app.Use(new Func<AppFunc, AppFunc>(next => new Html5ModeMiddleware(next, options).Invoke));
        }
    }
}