Q:

Negation of "If...Then" Statements

I am just being introduced to how logic is used in mathematics and my lecturer mentioned that $\sim(P\rightarrow Q) \equiv p\wedge\sim q$. This is quite hard to grasp at first glance, so he gave an example: The negation of "if $x\neq 0$ then $y=0$" is "$x\neq 0 \wedge y\neq 0$".
Well, my question is, why should that be the case? Why is the negation of "if $x\neq 0$ then $y=0$" not "$x\neq 0 \wedge y=0$"?
Any explanations will be greatly appreciated :)
EDIT: Thank you all for your comments! I think I understand the logic better now!

A:

One can show $A\Rightarrow B \equiv \neg A\lor B$ using truth tables. By De Morgan's laws one concludes
$$\neg (A\Rightarrow B) \equiv \neg (\neg A\lor B) \equiv A\land \neg B. $$

$x\neq 0\ \land\ y=0$ does not negate the initial statement, but implies it, in fact. For if "$x\neq 0\ \land\ y=0$", then certainly "if $x\neq 0$, then $y=0$".

A:

If a implies b, that means every time a occurs, b must also occur. So if a occurs and not b, we now the implication ist false.

A:

"If I come from Paris then I am French".
The negation is certainly not "I come from Paris and I am French" - because what if I really do come from Paris and am French? In that case, both the statement and its "negation" are true!

"If a person is French then they come from Paris". This is false, of course, but why?
To falsify "If a person is French then they come from Paris", I need to demonstrate an example of someone who is French but who does not come from Paris.


Q:

Angular Lazy Loading Submodule

I have an application which uses lazy loading in multiple levels. The initial path of '/' is caught in the main app.routes and redirected to a lazy loaded module. That module also has its own submodule-1.routes and is just a container for other feature modules.  In the submodule-1.routes, I am lazy loading the feature module.  From what I can tell it seems that the modules are not being lazy loaded.
I have tried to create the routes in submodule-1 itself, and lazy load the feature modules from there but that hasnt helped.
Below is the folder structure
app
app.module.ts
app.routing-module.ts
-modules
--login
---login.module.ts
---login-routing.module.ts
---pages
----login-user
-----login-user.module.ts(LoginUserPageModule)
-----login-user-page.ts(LoginUserPage)
--signup
---signup.module.ts
---signup-routing.module.ts
----pages
-----signup-email
------signup-email.module.ts(SignUpEmailPageModule)
------signup-email-page.ts(SignUpEmailPage)

Below is my main routes in app.routes.ts:
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'signup-email', loadChildren: './modules/signup/signup.module#SignupModule' },
  { path: 'login', loadChildren: './modules/login/login.module#LoginModule' },

];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Signup Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { SignupRoutingModule } from './signup-routing.module';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    SignupRoutingModule
  ],
  exports:[]
})
export class SignupModule { }

SignupRoutes.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

export const SIGNUP_ROUTES: Routes = [
    {
        path: '',
        loadChildren: './pages/signup-email/signup-email.module#SignupEmailPageModule'
    }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forChild(SIGNUP_ROUTES)
  ],
  exports: [RouterModule]
})
export class SignupRoutingModule { }

SignupEmailPageModule
import { SignupEmailPage } from './signup-email.page';

const routes: Routes = [
  {
    path: '',
    component: SignupEmailPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule
    ,RouterModule.forChild(routes)
  ],
  declarations: [SignupEmailPage]
})
export class SignupEmailPageModule {}

Login Module
@NgModule({
  declarations: [],
  imports: [
    LoginRoutingModule
  ],
  providers:[
  ]
})
export class LoginModule { }

LoginRoutes
export const LOGIN_ROUTES: Routes = [
    {
        path: '',
        loadChildren: './pages/login-user/login-user.module#LoginUserPageModule'
    }
];

@NgModule({
  declarations: [],
  imports: [
    RouterModule.forChild(LOGIN_ROUTES)
  ],
  exports: [RouterModule]
})
export class LoginRoutingModule { }

LoginUserPageModule
const routes: Routes = [
  {
    path: '',
    component: LoginUserPage
  }
];

@NgModule({
  imports: [
    IonicModule,
    RouterModule.forChild(routes),
    SharedModule
  ],
  declarations: [LoginUserPage]
})
export class LoginUserPageModule {}

Since the default path of '/' is being directed to login which is working, i expect the signup module to be lazy loaded, and visible only once. However, below is the image that i see from Augury on the initial load of the application which makes it seem like both LoginModule and SignupEmailModule are being loaded multiple times and not lazy loaded at all. As a result, I see the LoginUserPage and SignupEmailPage already loaded as in the image below from Augury.

After removing the the { preloadingStrategy: PreloadAllModules } from app.routing.ts. I do see that the modules are now loaded lazily, however, when I access each of the lazy loaded modules, I see an extra 'lazy' node in the Augury graph as below. I'm not sure why that is, and if it should be there ?
Also, whenever a lazyloaded route is loaded, the other route goes back to showing as lazy, should it not just stay loaded from that point on ? Why does it go back to showing as 'lazy' in the graph, almost as if it hasnt been loaded.
Augury graph after accessing the default path which is also lazy loaded

Augury graph after accessing the lazy loaded route of 'signup' page

A:

In your app.routes.ts you set preloadingStrategy: PreloadAllModules, this means your modules are being preloaded. So instead of loading your modules when they are first requested (lazily), the modules get loaded asynchronously in the background. It's kind of an in between strategy between eager and lazy loading but it means that all your modules get loaded in the end. From the documentation:

After each successful navigation, the router looks in its configuration for an unloaded module that it can preload. Whether it preloads a module, and which modules it preloads, depends upon the preload strategy.
The Router offers two preloading strategies out of the box:

No preloading at all which is the default. Lazy loaded feature areas are still loaded on demand.
Preloading of all lazy loaded feature areas.


Q:

Trouble with PUT request using Node.js (express), Angular, and MongoDB

I'm stuck trying to figure out how to update my data to MongoDB (I'm using Monk with MongoDB, Node, Express, and Angular). I have no trouble with POST and DELETE, but can't figure out where I'm going wrong with PUT.
Error I get:
PUT http://localhost:3000/api/habits/[object%20Object] 500 (Internal Server Error)

Where I'm confused is with what I should be sending with Angular, and how to receive it in Node, since I understand I need to send the updated object for the record, but then how should I be accessing the ID to look it up in Mongo?
For example with my POST (more code context below), it makes sense that I'm sending the object "newHabitData"
$http.post('http://localhost:3000/api/habits', newHabitData)

But with PUT examples I see, they send the object (named id) as a :parameter
app.put('/api/articles/:id', function (req, res){

I've been using these tutorial which is the closest I could find to understanding how to use PUT:
http://aleksandrov.ws/2013/09/12/restful-api-with-nodejs-plus-mongodb/
http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4
A million thanks for some advice!
ANGULAR:
// Works Fine
$scope.addHabit = function(){
    var newTitle = $scope.newTitle.trim();
    if(!newTitle){
        return;
    }
    var newHabitData = {
        title: newTitle,
        count: 0,
        status: 'active'
    };

    $http.post('http://localhost:3000/api/habits', newHabitData)
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

    $('.habit-form__input-title').val('').focus();
    $scope.newTitle = '';

}

// Works Fine
$scope.habitDestroy = function (id) {
    $http.delete('/api/habits/' + id._id)
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

// NOT WORKING - I WANT TO INCREMENT THE COUNT, THEN SAVE
$scope.habitCheckIn = function(id){
    id.count = ++id.count;

    $http.put('/api/habits/' + id)  // Should I be sending the entire object? Seems to make most sense to me
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
}

NODE:
// Get all habits -- WORKS FINE
router.get('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    collection.find({},{},function(e,data){
        res.json(data);
    });
});

// Create one habit -- WORKS FINE
router.post('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    collection.find({},{},function(e,data){
        collection.insert({
            title: req.body.title,
            count: req.body.count
        }, function(err, habit){
            if(err){
                res.send(err);
            }

            collection.find({},{},function(e,data){
                res.json(data);
            });
        });
    });
});

// Delete one habit -- WORKS FINE
router.delete('/api/habits/:habit_id', function(req, res){
    var db = req.db;
    var collection = db.get('habits');

    collection.find({},{},function(e,data){
        collection.remove({
            _id : req.params.habit_id
        }, function(err, todo){
            if(err){
                res.send(err);
            }

            collection.find({},{},function(e,data){
                res.json(data);
            });
        })
    })
})

// Update Habit -- NOT WORKING
router.put('/api/habits/:habit_id', function(req, rest){
    var db = req.db;
    var collection = db.get('habits');

    // the real ID is _id, so should I be doing req.params.habit_id._id ? Or is findById asking for the entire object, and it finds the actual id itself? This is where I'm lost, can't figure it out.
    collection.findById(req.params.habit_id, function(e,data){
        if(e){ res.send(e); }
        data.title = req.body.title;
        data.count = req.body.count;
        data.save(function(err){
            if(err){
                res.send(err);
            res.json(data);
            }
        })
    })
})

UPDATE - THE CODE BELOW GOT IT TO WORK.
Thanks to saintedlama for getting me in the right direction.
Not sure if this is the right way to do it, but it works.
I followed my POST format by accessing the req.body values, not the id passed in as a parameter.
So instead of this:
router.put('/api/habits/:habit_id', function(req, res) {

I did this:
router.put('/api/habits', function(req, res) {

Then I accessed the id and the updated count/title using the req.body._id and req.body.count values
router.put('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    var id = req.body._id;

    if(!req.body) {
        return res.send(400);
    } // 6

    collection.findById(id, function(e,data){
        if(e) {
            return res.send(500, e);
        } // 1, 2

        if(!data) {
            return res.send(404);
        } // 3

        var update = {
            title : req.body.title,
            count : req.body.count
        }; // 4

        collection.updateById(id, update, function(err) { // 5
            if(err) {
                return res.send(500, err);
            }

        });
    });
});

A:

The code fragment to update existing habits should work just fine with some small corrections

When running in an error always use return
Always send a status back. In this case we'll send 500
Check for not found and return 404
Use simple update object. This will only update fields contained in the update object
The mongodb document returned by monk has no save function, the document needs to be updated via the collection
Check if the request has a body and send 400 - Bad Request

You can pass a object id as hex or ObjectId to findById as stated in the Monk docs.
router.put('/api/habits/:habit_id', function(req, rest){
    var db = req.db;
    var collection = db.get('habits');

    if(!req.body) { return res.send(400); } // 6

    collection.findById(req.params.habit_id, function(e,data){
        if(e) { return res.send(500, e); } // 1, 2

        if(!data) { return res.send(404); } // 3

        var update = { title : req.body.title, count : req.body.count }; // 4

        collection.updateById(req.params.habit_id, update, function(err) { // 5
            if(err) {
                return res.send(500, err);
            }

            res.json(data);
        });
    });
});

The code above can be further simplified by using the findAndModify function of Monk.


Q:

File browser-like element in Mac OS programming of Xcode

Sorry that my title is not clear enough. What I wanted to ask is based on a screen capture:

I want to make an app like this. But there are two elements I do not know what the classes are: A and B (C and D are NSSplitView. I just knew).
Could any one just tell me what ducuments to follow to create UIs like the appearance of A and B? Thank you!

A:

Create A UI in NSOutlineView is the way to display hierarchical data that can be expanded and collapsed, such as directories and files in a file system.
B is made by  Gradient buttons set images to gradient buttons to get B UI
or
Use NSToolBar to use formal ui design.


Q:

Is method overloading a form of polymorphism or something else?

I have a long standing doubt. Could someone please tell me whether method overloading is a form of polymorphism or is it something completely different?

A:

Method overloading is just a syntax sugar allowing you to have methods with same name but different arguments. It has nothing to do with polymorphism. Method overloading is typically used to define two methods accepting different arguments, e.g.:
public void println(boolean x) //...
public void println(char x) //...

or to skip certain parameters and use some defaults:
public String substring(int beginIndex) //...
public String substring(int beginIndex, int endIndex) //...

Method overriding, on the other hand, is a foundation of inheritance and is more closely related to polymorphism.

A:

Polymorphism, literally means something which has multiple behavior.
In java, we can have a static and runtime polymorphism.
Overloading is static polymorphism since it allows different behavior by means of passing varying arguments. But this is resolved at the complile time only, hence static.
Overriding, is dynamic polymorphism since the actual call to the function depends on the type of object invoking it which is available only at the runtime, hence dynamic.


Q:

Need help troubleshooting MIPS code to count lowercase letters

I wrote this code in MIPS to count the # of lowercase letters input by a user:
.data
msg1: .asciiz
count_lower: .space 41
.text
.globl main
main:
la $a0, msg1 #load address of msg1 to store string
li $a1, 100 #msg1 is 100 bytes
li $v0, 8 #syscall for read str
syscall

add $s1, $0, $0 #interger to print later
la $t0, count_lower
sw $a0, 0($t0) #store input string in $t0
loop:
lb $t1, 0($t0) #load char from $t0
beqz $t1, exit #if no more chars, exit
blt $t1, 'a', else #This line and line below are for if char is not lowercase
bgt $t1, 'z', else
addi $s1, $s1, 1 #if char is lowercase, +1 to $s1
sll $t0, $t0, 8 #shift one byte to get to next char
sll $t1, $t1, 8 #shift one byte to get to next char

else:
sll $t0, $t0, 8 #shift one byte to get to next char
sll $t1, $t1, 8 #shift one byte to get to next char
j loop #jump back to loop

exit:
move $a0, $s1 #move interge to print into $a0
li $v0, 1 #print interger in $a0
syscall
li $v0, 10 #exit
syscall

But when I run it, all it does it print the integer "0" no matter what string is input. Can anyone help me troubleshoot? I wrote comments in the code to explain my thought proccess.
EDIT:
1 .data
2 msg1: .space 100
3 .text
4 .globl main
5 main:
6 li $v0, 8 #syscall for read str
7 la $a0, msg1 #load address of msg1 to store string
8 li $a1, 100 #msg1 is 100 bytes
9 move $t0, $a0 #save user input to $t0
10 syscall
11 add $s1, $0, $0 #interger to print later
12 add $t1, $0, $0 #initialize $t1
13 loop:
14 sb $t0, 0($t1) #store rightmost char into memory 0
15 lb $t1, 0($t0) #load char from memory 0 into $t1
16 beqz $t1, exit #if no more chars, exit
17 blt $t1, 'a', else #This line and line below are for if char is not
18 lowercase
19 bgt $t1, 'z', else
20 addi $s1, $s1, 1 #if char is lowercase, +1 to $s1
21 srl $t0, $t0, 8 #shift one byte to get to next char
22 add $t1, $0, $0 #re-initialize $t1
23 j loop #jump back to loop
24 else:
25 srl $t0, $t0, 8 #shift one byte to get to next char
26 add $t1, $0, $0 #re-initialize $t1
27 j loop #jump back to loop
28
29 exit:
30 move $a0, $s1 #move interge to print into $a0
31 li $v0, 1 #print interger in $a0
32 syscall
33 li $v0, 10 #exit
34 syscall

A:

This doesn't do what you seem to think it does:
sw $a0, 0($t0) #store input string in $t0

That instruction only stores the address of the string at ($t0) (i.e. in the first 4 bytes of count_lower).
I really don't see why you need two buffers for this. Just read the characters from the same buffer that you specified for syscall 8.
Also, your declaration of msg1 is incorrect. Your comment says #msg1 is 100 bytes, but your declaration is msg1: .asciiz, which certainly doesn't reserve 100 bytes. That should be changed to msg1: .space 100.


Q:

pygame.error: display Surface quit after filling the surface black

After I paint my surface black in pygame. I get the error
pygame.error: display Surface quit.

Full error:
>
D:\Programme\Anaconda3\envs\gameDev\python.exe "C:/Users/xxx/PycharmProjects/Workspace/pygame snake/main.py"
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:/Users/xxx/PycharmProjects/Workspace/pygame snake/main.py", line 81, in <module>
    thegame.execute()
  File "C:/Users/xxx/PycharmProjects/Workspace/pygame snake/main.py", line 74, in execute
    self.render(self._display_surf)
  File "C:/Users/xxx/PycharmProjects/Workspace/pygame snake/main.py", line 41, in render
    _display_surf.fill((0,0,0))
pygame.error: display Surface quit
<Surface(Dead Display)>

I tried instead of:
_display_surf.fill((0,0,0))

using:
_display_surf.fill(pygame.color("black"))
But that didnt work either.
Here is my full source code:
import pygame
from pygame.locals import *

class Player(object):
    x = 10
    y = 10
    speed = 1

    def moveRight(self):
        self.x = self.x + self.speed

    def moveLeft(self):
        self.x = self.x - self.speed

    def moveUp(self):
        self.y = self.y - self.speed

    def moveDown(self):
        self.y = self.y + self.speed

class game:
    def __init__(self):
        self.resolution = (800, 500)
        self._running = True
        self._display_surf = None
        self.player = Player()

    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode(self.resolution)
        pygame.display.set_caption("Snake!")
        self._running = True

    def on_cleanup(self):
        pygame.quit()

    def render(self, _display_surf):
        print(_display_surf)
        _display_surf.fill((0,0,0))
        pygame.draw.rect(self._display_surf, (0, 128, 255), pygame.Rect(self.player.x, self.player.y, 30, 30))
        pygame.display.flip()

    def loop(self):
        pass

    def on_event(self, event):
        if event.type == pygame.quit():
            print("quiet")
            self._running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                self.player.moveRight()

            elif event.key == pygame.K_LEFT:
                self.player.moveLeft()

            elif event.key == pygame.K_UP:
                self.player.moveUp()

            elif event.key == pygame.K_DOWN:
                self.player.moveDown()

    def execute(self):
        if self.on_init() == False:
            self._running = False

        while self._running:
            for event in pygame.event.get():
                self.on_event(event)

            self.render(self._display_surf)
            self.loop()
        self.on_cleanup()

if __name__ == "__main__":
    thegame = game()
    thegame.execute()

I expect that I have a black surface and nothing happens. But instead, it crashes when I try to paint it black. Hope somebody can help
Solution:
For anybody who is intrested in
instead of
        if event.type == pygame.quit():
            print("quiet")
            self._running = False

i need to to
        if event.type == pygame.QUIT:
            print("quiet")
            self._running = False

A:

The code

 if event.type == pygame.quit():
     print("quiet")

doesn't do what you expect it to do. pygame.quit() is a function call and uninitializes all pygame modules. The function returns None and so the condition fails. The code runs through and crashes at the next instruction which tries to access a pygame module.
You've to compare event.type to the event enumerator constant pygame.QUIT, which identifies the quit event instead:
if event.type == pygame.QUIT:
    print("quiet")
    self._running = False

See the documentation of pygame.event.


Q:

Checking if stack allocation fails?

Is there a way to correct failed static allocation or program just fails with Segmentation or Bus Fault when run?
Post was inspired by how C99 allows crazy stuff like char text[n];
EDIT: Thanks. I now understand the part in bold is not a static alloc. So just to check, if something like char text[1234]; fails would the possible recovery strategies be the same?

A:

char text[n] allocates a variable-size array on the stack. It simply involves incrementing the stack pointer by n.
There is not much a userspace process can do if a stack overflow occurs - it's up to the operating system to either send a signal to the process and terminate it or resize the stack.


Q:

Thread.Yield() causes CPU spikes?

In a project of mine, I noticed the server spiking in CPU usage as the number of clients connected increase.

10 clients: 0% mostly, spikes to 7% randomly.
  15 clients: 0% mostly, spikes to 10% randomly.
  25 clients: 10% mostly, spikes to 60% randomly.
  50 clients: 50% mostly, spikes to 60%, CPU is overall at 100% (due to gameservers).
  (Note: there are 8 logical cores on the CPU)

I narrowed down the problem to Thread.Yield, on this line: https://github.com/vercas/vProto/blob/master/vProto/Base%20Client/Package%20Sending.cs#L121
As soon as I comment that line out, CPU usage stays at 0% constantly even with 100 clients!
Why is Thread.Yield doing this?

A:

It is due to the way Thread.Yield releases processing. It forces the current process thread to release prematurely. This in turn sends out messages to all other processes telling them to do their own thing. Switching process context is expensive in terms of swapping out memory, loading cached processes, and moving through the process list out of sequence.
From MSDN:

If this method succeeds, the rest of the thread's current time slice is yielded. The operating system schedules the calling thread for another time slice, according to its priority and the status of other threads that are available to run.
Yielding is limited to the processor that is executing the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority. If there are no other threads that are ready to execute on the current processor, the operating system does not yield execution, and this method returns false.
This method is equivalent to using platform invoke to call the native Win32 SwitchToThread function. You should call the Yield method instead of using platform invoke, because platform invoke bypasses any custom threading behavior the host has requested.

UPDATE
There has been some challenge to the statement that Thread.Yield causes expensive context switching. Here are additional references:
Difference between Thread.Sleep0 and Thread.Yield
Threading in C# - Joseph Albahari
MSDN - About Processes and Threads
MSDN - Multitasking Considerations

The recommended guideline is to use as few threads as possible, thereby minimizing the use of system resources. This improves performance. Multitasking has resource requirements and potential conflicts to be considered when designing your application. The resource requirements are as follows:

The system consumes memory for the context information required by both processes and threads. Therefore, the number of processes and threads that can be created is limited by available memory.
Keeping track of a large number of threads consumes significant processor time. If there are too many threads, most of them will not be able to make significant progress. If most of the current threads are in one process, threads in other processes are scheduled less frequently.


Q:

Key generation example for in-app purchases on android

In the in-app purchase sample application in sdk\extras\google\play_billing, there is a comment as follows.
/* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY
         * (that you got from the Google Play developer console). This is not your
         * developer public key, it's the *app-specific* public key.
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an attacker to replace the public key with one
         * of their own and then fake messages from the server.
         */

Can some one help with me with an example to generate the key at runtime from pieces or use bit manipulation? That part is unclear to me.
Thanks

A:

It just means that you should not leave your key in a plain string constant because probably not even by obfuscating it can be hidden from the curious eyes...
So build the key from different pieces of strips as, for example, let´s suppose the key is "123456". You can have the same String by concatenating 1L + "23", then parsing it to Long, multiplying by 1000 and adding 456:
    Long longVal = 1L;
String code = longVal.toString() + "23";
longVal = Long.parseLong(code) * 1000L + 456;

In bytecode after compilation it´ll be a little twisted and, even by decompiling everything will look even uglier and hard to read. BTW. Maybe you can bitwise it a bit, also.
More info: Protect string constant against reverse-engineering


Q:

Maximum index size for array

The following code is crashing my program.  I found the problem is the size of the array.  If I reduce the size to 320*320, it works fine.  Does it make sense that this wound be a limitation?  If so, what is a work around?  I am coding in Objective C for IPhone.  Any help would be appreciated.
Thanks!
 int life_matrix[320*350];
 x_size=320;
 y_size=350;
 for (int counter=0; counter < x_size; counter++)
 {
  for (int counter2=0;counter2 < (y_size); counter2++)
  {
   life_matrix[counter*(int)x_size+counter2] = rand()%2;
  }
 }

A:

The array is allocated on stack and usually the stack size is limited. If you need a big array, usually it is a good idea to allocate it on heap.

A:

leiz's advice is correct, you really should be allocating this dynamically otherwise you run the risk of running into a situation were the size of the array is larger than the available memory on the stack.
Also the formula you are using to map a 2-dimensional grid to a 1-dimensional array is incorrect. You should be multiplying by y_size instead of x_size.
life_matrix[counter*(int)y_size+counter2] = rand()%2;

or you could flip your counters
life_matrix[counter2*(int)x_size+counter] = rand()%2;

Another approach to solving this would be to use it as a 1-dimensional array for initialization:
for(int n = 0; n < x_size * y_size; ++n) {
    life_matrix[n] = rand()%2;
}


Q:

Rescuing Windows XP after formatting the boot disk

My computer has two physical disks:

Disk 0 (C:) Windows 7
Disk 1 (D:) Windows XP x64

I've been running a 64-bit version of XP installed on D: for some years but I didn’t realize it was initially booting off C:
Last weekend I decided to see if I could dual-boot the PC with Windows 7 so I formatted the C: Drive using an old XP boot disk and installed Windows 7, which went well but now I can’t boot XP on D:
I installed EasyBCD into Windows 7, created a boot entry for Windows XP x64 on D: and then created the following boot.ini and copied into C:\WINDOWS but when I start up and select the entry for XP I get system messages telling me I’m missing files like the NTLDR. Is there a way I would be able to get this to dual boot now?
[boot loader]
timeout=10
default=multi(0)disk(0)rdisk(1)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(1)partition(1)\WINDOWS="Microsoft Windows XP" /fastdetect

A:

And when you start your computer with the boot xp cd? And run a shell and using fixboot?
Here is some more information.
Fixboot
Also fixmbr can help you. Fixmbr


Q:

Is the X-Men: Evolution Toad immune to his own slime?

In the animated TV show X-Men: Evolution, there is a two-part episode called 'The HeX Factor', where Wanda Maximoff (the Scarlet Witch) is added to the Brotherhood by Mystique to give them more firepower against the X-Men.
Upon seeing Quicksilver, she goes into a rage, attacking them, only to be attacked by Avalanche and Toad. When Toad spits a wad of slime at her, she reverses it in mid-air, causing it to strike him in the face and explode.
However, when this has happened to others, the slime has stuck, blinding them. Is Toad protected from his powers, or was this just a random event?

A:

It's generally accepted in the Marvel universe that mutants are immune to their own powers. Hence why Cyclops doesn't blast his eye sockets out every time he uses his powers. There are exceptions, but they usually become real plot points.


Q:

Locked write, unlocked read

Algorithmic question
How to allow only the following types of threaded operations on an object?

multiple simultaneous reads, no writes
single write, no reads

Example: wrapper for STL container allowing efficient search from multiple threads. For simplicity, let assume no iterator can be accessed from outside of the wrapper in question.
Let's assume we have semaphores and mutexes at out disposal.
I know that boost libraries has this concept implemented. I'd like to understand how is this usually done.

A:

Use boost::shared_mutex to handle frequent read, infrequent write access patterns.
As you've noted, STL containers are 'leaky' in that you can retrieve an iterator which has to be treated as either an implicit ongoing operation for write (if non-const) or read (if const), until the iterator goes out of scope.  Writes to the container by other threads while you hold such an iterator can invalidate it.  Your wrapper would have to be carefully designed to handle this case and keep the wrapper class efficient.


Q:

Assigning viewModel on Controller Init?

I am using MVVM and want to assign my viewModel to the viewController on the Controllers init. I thought I would achieve this like so:
class LoginViewController: UIViewController, UITextFieldDelegate {

    init(loginViewModel: LoginViewModel) {
        self.loginViewModel = loginViewModel
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }

However I get the error:

Super.init isn't called on all paths before returning from initializer

Is this not the correct route to take? also how would I init the viewModel correctly when it requires an object to do so, but it has to perform a network request first? Init with a blank object instance?
Thanks
edit: this is what im trying now
initWithViewAndViewModel:(loginView: LoginView, loginViewModel: LoginViewModel) {
        super.init()
        self.loginView = loginView
        self.loginViewModel = loginViewModel
    }

A:

As a best practice,
Step 1:
required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

Step 2:
init(loginViewModel : LoginViewModel) {
        super.init(nibName: nil, bundle: nil)
        initWithModel:(loginViewModel: LoginViewModel)
    }

Step 3: implement initWithModel function


Q:

In Isaiah 28:16 what does it mean that the cornerstone is "tested"?

[Isa 28:16 NIV] (16) So this is what the Sovereign LORD says: "See, I lay a stone in Zion, a tested stone, a precious cornerstone for a sure foundation; the one who relies on it will never be stricken with panic.

A:

In Isaiah 28:16 what does it mean that the cornerstone is “tested”?

[Isa 28:16 NIV] (16) So this is what the Sovereign LORD says: "See, I
  lay a stone in Zion, a tested stone, a precious cornerstone for a sure
  foundation; the one who relies on it will never be stricken with
  panic.

The Apostle Peter, by quoting Isaiah's words, showed that the prophecy applied to Jesus,  " a precious corner stone" Peter wrote:
1 Peter 2:4-7 (NET Bible)
A Living Stone, a Chosen People

4 "So as you come to him, a living stone rejected by men but[b] chosen
  and precious[c] in God’s sight, 5 you yourselves, as living stones,
  are built up as a spiritual house to be a holy priesthood and to offer
  spiritual sacrifices that are acceptable to God through Jesus Christ.
  6 For it says in scripture, “Look, I lay in Zion a stone, a chosen and
  precious cornerstone, and whoever believes in him will never be put to
  shame.” 7 So you who believe see  his value, but for those who do not
  believe, the stone that the builders rejected has become the
  cornerstone."

How was Jesus tried and tested cornerstone?
I lay a stone in Zion, a tested cornerstone, Jesus was that precious cornerstone chosen by God to be the foundation of his city, for three and a half years he was tested to the utmost, in all matter of trials ,temptations, persecutions, and even nailed to  death. In all his trials He remained  obedient and faithful to the end, never going contrary to his Father's will, He loved  his  Father to the end. Being tested  in the flesh the quality of his faith was hardened  and proven something  altogether different to being faithful in heaven.
The scriptures record his trials:
Hebrews 2:18  (NASB)

18 "For since He Himself was tempted in that which He has suffered, He
  is able to come to the aid of those who are tempted."

Hebrews 4:15  (NASB)

15 "For we do not have a high priest who cannot sympathize with our
  weaknesses, but One who has been tempted in all things as we are, yet
  without sin."

Hebrews 5:7-8  (NASB)

7 "In the days of His flesh, [b]He offered up both prayers and
  supplications with loud crying and tears to the One able to save Him
  from death, and He was heard because of His piety. 8 Although He was a
  Son, He learned obedience from the things which He suffered."

Revelation 3:14  (NASB)

14 “To the angel of the church in Laodicea write: The Amen, the
  faithful and true Witness, the Beginning of the creation of God, says
  this:

1 Timothy 6:13  (NASB)

13 "I charge you in the presence of God, who gives life to all things,
  and of Christ Jesus, who testified the good confession before Pontius
  Pilate."

Jesus Christ resisted every attempt to break down his integrity, he endured all trials and continued faithfully on regardless of the opposition of sinners against him.The apostle John also uttered prophecy covering Zion many years after the literal Zion was destroyed. John  wrote ,Rev. 14:1(NASB)
The Lamb and the 144,000 on Mount Zion

14 "Then I looked, and behold, the Lamb was standing on Mount Zion,
  and with Him one hundred and forty-four thousand, having His name and
  the name of His Father."


Q:

Function error: "Binary operator '+' cannot be applied to operands of type 'Double' and 'Int'"

I am currently working on a school assignment for my coding class. In this assignment, we are creating a function that takes a number grade (a Double) and divides it by the numberOfHours to get a GPA variable. I have run into an error though in my code:

Binary operator '+' cannot be applied to operands of type 'Double' and 'Int'

I do not understand this error and I am trying to fix the code by changing what's an Int and what's a Double, but it doesn't seem to be working.
The code where the error is coming from is:
// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
    let addedHours: Int = hours + attemptedHours
    let calculatedGPA: Double = hours / grade
    //gpa = gpa + grade
    print(calculatedGPA)
    return calculatedGPA
}

Full code below:
//  My Functions Playground.swift
//
//
//: Playground - noun: a place where people can play

import UIKit

/*
 We're going to track your GPA from one semester to the next. Assume at the end of your sophomore years, you have attempted 60 hours and have earned 222.5 grade points. Assign attempted hours and grade points to variables. Write a function that updates your current GPA and assigns it to the GPA var (you'll update it along the way). Label your function arguments. Print your new GPA from within the function.

 At the end of the current semester, add 16 hours and 60 grade points to your record. Call the gpa function to update your overall gpa.

 Test your gpa at the end of the year to see if any administrative action needs to be taken. If the gpa is less than 1.8, the student will need to be placed on suspension. If less than 2.0, we need to put the student on probation. If over 3.5, we'll put the student on the dean's list, and if over 3.9, we'll put the student on the president's list. Create a switch that prints the recommended adminstrative action. If no action is required, print, "Carry on. Nothing to see here." Create internal and external labels for your arguments.

 */

var gpa: Double
var attemptedHours: Int
var earnedGradePoints: Int

// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
    let addedHours: Int = hours + attemptedHours
    let calculatedGPA: Double = hours / grade
    //gpa = gpa + grade
    print(calculatedGPA)
    return calculatedGPA
}

// call the function
gpaUpdater(moreHours: 16, moreGPA: 60)

// add the new hours and grade points here and call the function again
func switchFunction() {
    switch gpa {
    case gpa..<1.8:
        print("You will be placed on suspension")
    case 1.8...2.0:
        print("You will be placed on probation")
    case 3.5...3.8:
        print("You will be put on the dean's list.")
    case 3.9..<gpa:
        print("You will be put on the president's list.")
    default:
        print("Carry on. Nothing to see here.")
    }
}
switchFunction()

A:

Change this line
let addedHours: Int = hours + attemptedHours

to
let addedHours =  Int(hours) + attemptedHours


Q:

Full Calendar Dropping Event Objects After Data Transform

I am having a strange issue with full calendar. I am trying to create a mouseover for different types of events and have had some issues with attributes of an event object disappearing between the "eventDataTransform" and "eventMouseover" functions
This is for a web application that will be loading data from an API to populate full calendar. I am able to get all of the object's attributes when I do not perform a transformation on the event. I am inspecting the object and show that it is present when the object is transformed and not so when it is moused over.
calendar = $("#k_calendar").fullCalendar({
  isRTL: KUtil.isRTL(),
  header: {
    left: "prev,next today",
    center: "title",
    right: "month"
  },
  editable: false,
  eventLimit: false,
  navLinks: true,
  weekends: true,
  eventSources: [
    // Loaded from a previous source
    data,
    "{% url 'pentesting-api:pentest-events' %}"
  ],
  displayEventTime: false,
  // Where the error is
  eventDataTransform: function (eventData) {
    if (eventData.hasOwnProperty('vendor')) {
      eventData.end = moment(eventData.end).add(1, 'days').format();
      eventData.title = eventData.full_name;
      eventData.backgroundColor = statusColors[eventData.status];
      eventData.allDay = true;
      return eventData;

    }
    else {
      eventData.title = eventData.event_name;
      eventData.backgroundColor = eventColors[eventData.event_type];
      // all attributes are on the object here
      console.log(eventData);
      return eventData;
    }
    // Using the below commented out code works but doesn't distinguish between events
    // eventData.end = moment(eventData.end).add(1, 'days').format();
    //   eventData.title = eventData.full_name;
    //   eventData.backgroundColor = statusColors[eventData.status];
    //   return eventData;
  },
  eventMouseover: function (event, jsEvent, view) {
    closePopovers();
    // console.log(event);
    if (event.hasOwnProperty('event_type')) {
      console.log('this mouse over');
      // object dropped the 'end' attribute
      console.log(event);
      let start_base, end_base, start_date, end_date, start_time, end_time;
      start_base = event.start.format().split('T');
      start_date = start_base[0];
      start_time = start_base[1].split('-')[0].split(':')[0] + ':' + start_base[1].split('-')[0].split(':')[1];
      end_base = event.end.format().split('T');
      end_date = end_base[0];
      end_time = end_base[1].split('-')[0].split(':')[0] + ':' + end_base[1].split('-')[0].split(':')[1];
      popoverElement = $(jsEvent.target);
      $(jsEvent.target).popover({
        title: event.event_name,
        content: function () {
          let content;
          content = 'Event Type: ' + event.event_type +
            '
Start: ' + start_date + ' ' + start_time +
            '
End: ' + end_date + ' ' + end_time +
            '
Resource: ' + event.resource;
          return content
        },
        trigger: 'hover',
        html: true
      }).popover('show')
    }
    else {
      var end = event.end.subtract(1, 'days').format().split('T')[0];
      popoverElement = $(jsEvent.target);
      $(jsEvent.target).popover({
        title: event.title,
        content: function () {
          var content;
          content = 'Pentest ID: ' + event.id +
            '
Pentest Status:' + event.status +
            '
Start Date: ' + event.start.format() +
            '
End Date: ' + end +
            '
Resources: ' + event.tester +
            '
Duration: ' + event.duration;
          return content
        },
        trigger: 'hover',
        html: true
      }).popover('show')
    }
  },
  eventMouseout: function (event, jsEvent, view) {
    $(jsEvent.target).popover('hide')
  }
})});

I am expecting the input from the mouseover includes the 'end' object attribute, however, it is not present. When doing the if, else eventDataTransformation, all of the object attributes are there including the 'end' attribute. When the data event is logged in the eventMouseover function, every attribute is there except for 'end'.
Event data transform object (what I want)
{
  "id": 11,
  "resource": "1",
  "event_name": "Test Event",
  "start": "2019-03-29T08:52:44.330075-07:00",
  "end": "2019-03-29T08:52:44.330173-07:00",
  "event_type": "Demo",
  "pentest_id": null,
  "title": "Test Event",
  "backgroundColor": "#ADD8E6"
}

Object being passed to the eventMouseover function (same object but missing the 'end' attribute)
id: "_fc12"
allDay: false
backgroundColor: "#ADD8E6"
className: Array []
end: null
event_name: "Test Event"
event_type: "Demo"
id: 11
pentest_id: null
resource: "1"
source: Object { calendar: {…}, uid: "4", url: "/api/pentesting/events/", … }
start: Object { _isAMomentObject: true, _i: "2019-03-29T08:52:44.330075-07:00", _f: "YYYY-MM-DDTHH:mm:ss.SSSSZ", … }
title: "Test Event"
<prototype>: Object { … }
pentesting:1781:23

A:

According to the specifications (documented well in this bug report - https://github.com/fullcalendar/fullcalendar/issues/3688), the end date MUST be different than the start date (or the end date will be 'null'!)
I would also be careful on making the end date BEFORE the start - in your eventMouseover you are subtracting a day - you should probably do a quick check to make sure the end is > (not = as you will have the 'null' issue...) the start.  I didn't find anything on having the end before the start, but I'm pretty sure fullCalendar would 'dismiss' it (likely with a null as well since end is optional).


Q:

Trying to delete a single value from array

I am trying to delete a value from a passed array at the selected index. Basically taking the selected index of a list box that displays the arrays and using it to delete an entry. For some reason nothing is deleted and stays the same when I run the program. I am programing in Visual Studio 2010 in C#
public double [] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];

    for (int i = selectedIndex; i < ary.GetUpperBound(0); i++)
    {
        redoneArray[i] = ary[i + 1];
    }
    //redoneArray[ary.GetUpperBound(0)] = 0;
    return redoneArray;
}

Here is the delete button portion of code
private void btnDelete_Click(object sender, EventArgs e)
{
    int selectedIndex;
    if (this.lstClients.SelectedIndex <= 1)
    {
        return;
    }

    //else if ((this.lstClients.SelectedIndex - 2) < arrayIndex)
    else
    {
            selectedIndex = this.lstClients.SelectedIndex - 2;
            this.lstClients.Items.RemoveAt(this.lstClients.SelectedIndex);
            lbSI.Text = (this.lstClients.SelectedIndex - 2).ToString();
            redrawArray(mFirstNameArray, selectedIndex);
            redrawArray(mLastNameArray, selectedIndex);
            redrawArray(mAgeArray, selectedIndex);
            redrawArray(mHeightArray, selectedIndex);
            redrawArray(mStartWeightArray, selectedIndex);
            redrawArray(mGoalWeightArray , selectedIndex);
            redrawArray(mTotalWeeksArray, selectedIndex);
            //arrayIndex += -1;
            lstClients.Items.Clear();
            loadListBox();
    }

}

And here is my main code that loads it into the list
private void loadListBox()
{
    string currentClient;
    int lineNumber = 0;
    string formattedName;
    string strAvgBMI;
    string strLowBMI;
    string strHghBMI;
    double dStartAvgBMI;
    double dStartLowBMI;
    double dStartHghBMI;
    double dEndAvgBMI;
    double dEndLowBMI;
    double dEndHghBMI;

    lstClients.Items.Add("   CLIENT NAME      AGE    HEIGHT(in)   START WEIGHT    START BMI    GOAL WEIGHT    GOAL BMI     WEEKS");
    lstClients.Items.Add("=================  =====  ===========  ==============  ===========  =============  ==========  =========");

    for (int index = 0; index < arrayIndex; index++)
    {
        if (mFirstNameArray[index] == null)
        {
            continue;
        }
        lineNumber++;
        formattedName = mFirstNameArray[index];
        formattedName += " ";
        formattedName += mLastNameArray[index];
        mStartBMI[index] = calcBMI(mHeightArray[index], mStartWeightArray[index]);
        mEndBMI[index] = calcBMI(mHeightArray[index], mGoalWeightArray[index]);
        currentClient = index.ToString() + "   ";
        currentClient += formattedName.PadRight(18) + " ";
        currentClient += mAgeArray[index].ToString("##").PadLeft(4) + "      ";
        currentClient += mHeightArray[index].ToString("##.#0").PadRight(4) + "          ";
        currentClient += mStartWeightArray[index].ToString("###.0").PadRight(4) + "         ";
        currentClient += mStartBMI[index].ToString("##.#0").PadRight(4) + "         ";
        currentClient += mGoalWeightArray[index].ToString("###.0").PadRight(4) + "         ";
        currentClient += mEndBMI[index].ToString("###.#0").PadRight(4) + "       ";
        currentClient += mTotalWeeksArray[index].ToString("##").PadRight(4);

        lstClients.Items.Add(currentClient);
    }
    dStartAvgBMI = sumAvg(mStartBMI, arrayIndex);
    dStartHghBMI = maxArray(mStartBMI, arrayIndex);
    dStartLowBMI = minArray(mStartBMI, arrayIndex);
    dEndAvgBMI = sumAvg(mEndBMI, arrayIndex);
    dEndHghBMI = maxArray(mEndBMI, arrayIndex);
    dEndLowBMI = minArray(mEndBMI, arrayIndex);

    strAvgBMI = "";
    strHghBMI = "";
    strLowBMI =  "";
    strAvgBMI = "                                            Average:      " + dStartAvgBMI.ToString("0#.#0") + "                       " + dEndAvgBMI.ToString("0#.#0");
    strHghBMI = "                                            High:         " + dStartHghBMI.ToString("0#.#0") + "                       " + dEndHghBMI.ToString("0#.#0");
    strLowBMI = "                                            Low:          " + dStartLowBMI.ToString("0#.#0") + "                       " + dEndLowBMI.ToString("0#.#0");
    lstClients.Items.Add(strAvgBMI);
    lstClients.Items.Add(strHghBMI);
    lstClients.Items.Add(strLowBMI);
}

A:

I'd strongly recommend using a List<double> instead, since it has a more graceful and efficient strategy for adding and removing items.
There is a significant problem with your algorithm, because you haven't actually used selectedIndex to filter out the 'deleted' item. I think it should look like this
public double[] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];
    int i = 0;
    for (; i < selectedIndex; i++)
    {
        redoneArray[i] = ary[i];
    }
    for (; i < redoneArray.Length; i++)
    {
        redoneArray[i] = ary[i + 1];
    }
    return redoneArray;
}

Or even better:
public double[] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];
    Array.Copy(ary, redoneArray, selectedIndex);
    Array.Copy(ary, selectedIndex + 1,
               redoneArray, selectedIndex, redoneArray.Length - selectedIndex);
    return redoneArray;
}

Update
The real problem, however, is that you're redrawArray method returns a new array rather than modifying the existing array. You'd have to use assign the result array back to your variables, like this:
mFirstNameArray = redrawArray(mFirstNameArray, selectedIndex);
mLastNameArray = redrawArray(mLastNameArray, selectedIndex);
mAgeArray = redrawArray(mAgeArray, selectedIndex);
mHeightArray = redrawArray(mHeightArray, selectedIndex);
mStartWeightArray = redrawArray(mStartWeightArray, selectedIndex);
mGoalWeightArray = redrawArray(mGoalWeightArray , selectedIndex);
mTotalWeeksArray = redrawArray(mTotalWeeksArray, selectedIndex);


Q:

Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

I am having trouble with an anonymous delegate lambda in C#. I just converted the app to C#5 and the delegates went all haywire on me. Any help would be great. The specific error is:

Cannot convert lambda expression to type 'Delegate' because it is not
  a delegate type

public void UpdateUserList()
{
  if (!Monitor.TryEnter((object)this.LvPerson, 150))
      return;

  if (this.InvokeRequired)
  {
      this.Invoke((Delegate) (() => this.UpdateUserList()));
  }
  else
  { ... }
}

I have also tried
this.Invoke(() => {this.UpdateUserList();});

I'm not sure where the issue is as this was working before I moved the project from Visual Studio 2008 to Visual Studio 2015.
Thanks again for the help!

A:

The Invoke method expects a Delegate type instance, because you use a lambda expression it cannot automatically translate the expression into something like new Delegate() because Delegate has no public constructors. Using
this.Invoke(new Action(() => {this.UpdateUserList();}));

Should solve the problem as Action is a subclass of Delegate. To get rid of the redundant new Action(...) when using Invoke you can write a set of extension methods that take as argument an Action, this way the new Action(...) will be handled by the C# compiler so you won't have to write it every time making your code cleaner.
In case you are using Invoke for some asynchronous operations that may involve other threads look into Task Parallel Library (TPL) and Task-based Asynchronous Pattern (TAP), the latter has built in support into C# and Visual Basic.NET, using await will no longer require a call to Invoke() and allow you to run some operations on the background freeing your UI.


Q:

How do I play a local DVD copy in "DVD mode" using Xine and/or Mplayer?

I have a local copy of entire DVD's VIDEO_TS directory.
How can I use Xine or Mplayer to play it in a "DVD mode"?
That means for me:

that menus are recognized as such,
I can select language and other DVD-related options from DVD's menu,
rather than from command line
I can navigate through titles, rather than VOB files.

A:

Assuming your dvd folder is /path/to/movie/VIDEO_TS, try
xine dvd:///path/to/movie/

or
vlc dvd:///path/to/movie/

mplayer plays the movie, but I couldn't get it to play it in DVD mode. Apparently, the packaged builds of mplayer don't quite have menu navigation support yet.
mplayer dvd:// -dvd-device '/path/to/movie'

If your build of mplayer has dvd menu support, you should be able to invoke it using dvdnav:// instead of dvd://


Q:

Recommend me a quick setup local http/php/mysql server for development (WIndows)

I need a quick and dirty http server to use for local application development, that supports php and mysql. Xampp will not work for me (64 bit Win 7), so Im looking for something similar.

A:

I've had good experience with The Uniform Server -- it's portable*, and it includes Apache, PHP, MySQL, and Perl in the box.  Their installation manual also says testing has been successful on 64-bit WinXP Pro.
* It's portable in the put it on your USB-stick and use it on any Windows computer sense.  They also claim to not touch the Windows registry at all.


Q:

How can I use an environment variable in a key inside of yaml file

I have the following .env file:
# ENV
ENVIRONMENT=local
SITENAME=reo

I have the following docker-compose.yml (part of it) file:
volumes:
  ${SITENAME}-sync:
     external: true

I get the following error:
 volumes value '${SITENAME}-sync' does not match any of the regexes: u'^[a-zA-Z0-9._-]+$'

Is it possible to have a variable as a key in a Yaml file?
I noticed that: key: ${SITENAME} does work.

A:

Environment variables are not possible for keys in docker-compose.yml, only for values. See here


Q:

Creating function to rename columns in pandas dataframe

I have dataframe as below:
df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})

I tried creating a function which allow to change the column name dynamically where I can just input the old column name and new column name in the function as below:
def rename_column_name(df, old_column, new_column):
    df = df.rename({'{}'.format(old_column) : '{}'.format(new_column)}, axis=1)
    return df

This function is only applicable if I only have one input as below:
new_df = rename_column_name(df, '$a' , 'a')

which give me this new_df as below:
new_df = pd.DataFrame({'a':[1,2], '$b': [10,20]})

However, i wanted to create a function that allow me to make changes on multiple/one column depending on my preference as such:
new_df = rename_column_name(df, ['$a','$b'] , ['a','b'])

And get the new_df as below
new_df = pd.DataFrame({'a':[1,2], 'b': [10,20]})

So, how do I make my function more dynamic to allow me the freedom to enter multiple/one column names and rename them?

A:

You don't need a function, you can do this using dict comprehension:
In [265]: old_names = df.columns.tolist()

In [266]: new_names = ['a','b']

In [268]: df = df.rename(columns=dict(zip(old_names, new_names)))

In [269]: df
Out[269]:
   a   b
0  1  10
1  2  20

Function that OP needs:
In [274]: def rename_column_name(df, old_column_list, new_column_list):
     ...:     df = df.rename(columns=dict(zip(old_column_list, new_column_list)))
     ...:     return df
     ...:

In [275]: rename_column_name(df,old_names,new_names)
Out[275]:
   a   b
0  1  10
1  2  20

You need to pass a list of columns to this function. It can be multiple columns or a single column. This should do what you were looking for.


Q:

how to define key bindings for both GNU Emacs and Aquamacs?

I use both GNU Emacs for OSX and Aquamacs. I like to define key bindings that utilize the Mac command key ⌘.
Unfortunately, the syntax for specifying the ⌘ key is different for each.
In Aquamacs, it looks like this:
(define-key osx-key-mode-map (kbd "A-h") 'replace-string)

In GNU Emacs for OSX, it looks like this:
(define-key key-minor-mode-map (kbd "s-h") 'replace-string)

Is there a way to specify these key bindings in a way that both GNU Emacs and Aquamacs will understand, so that I don't have to maintain and update two separate .emacs files every time I add a new key binding?

A:

Based on lawlist suggestion, you could even define a function to do it:
(defvar gnuemacs-flag (string-match "GNU" (emacs-version)))
(defvar aquamacs-flag (string-match "Aquamacs" (emacs-version)))

(defun define-hyper-key (key fun)
  (cond
   (aquamacs-flag
    (define-key osx-key-mode-map (kbd (concat "A-" key)) fun))
   (gnuemacs-flag
    (define-key key-minor-mode-map (kbd (concat "s-" key)) fun))))

;; The aquamacs/gnuemacs keybindings:
(define-hyper-key "h" 'replace-string)


Q:

Playing Chess via SMS Messaging

I know there are some pretty nice open-source chess engines with powerful AI, like Crafty, that also have a nifty command line interface.
I also know that I can send e-mails with my SMS-capable phone, and that I can reply to such an e-mail, and it will be sent to my phone as a SMS text message.
Is there any way I can combine the two?  For example, text message a command like "Nd3" to an e-mail monitored by a computer, which sends the command to Crafty, and e-mails back the response?
I wasn't sure which site to post this one on; hopefully this is appropriate.

A:

Instead of parsing emails back and forth, you could use one of the SMS gateways out there like Twilio that supports sending and receiving messages via HTTP POST requests. I don't know of any free ones off hand that do it this way, but using regular ol' HTTP could save you a lot of time fussing with email servers and such.
Full disclosure: I work at Twilio.


Q:

MySQL Join horizontal with vertical table

I have the following structure:
CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).
Example (telephone is a custom field):
TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.

Is that possible?
Thanks.
EDIT:
If not possible, you may suggest a optimal solution using subqueries, only with SQL though.

A:

So, depending on how much control you have over the query generation, if you can generate the SELECT columns in the same order as the PRIMARY KEY of field, you could try the following. I'm envisioning something where you know there's 2 keys in field, and what they are in advance (from an earlier query?).
SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId = 1 and fp2.fieldId = 2;

This gives me the result, given the sample data in the question:
personId | name   | email           | telephone      | Address   |
       1 | Test 1 | test1@gmail.com | +1 555 555 555 | First St. |

This hinges on the notion that you've avoided the sub-query by doing an initial query earlier to know the arbitrary fields defined in the fields table. You didn't specify how dynamic this table is expected to be, so this may not be an unreasonable simplifying assumption to make.
Barring that, you can try something like:
SELECT fp.personId,p.name,p.email,fp.value as telephone,fp2.value as Address
    FROM fieldPerson fp INNER JOIN person p ON p.id = fp.personId
                        INNER JOIN field f ON f.id = fp.fieldId
                        INNER JOIN fieldPerson fp2
    WHERE fp.fieldId != fp2.fieldId LIMIT 1,1;

This gives me the same output without having to know the field id numbers, but I do need to know the names of the fields to generate the column names. The LIMIT is there to remove one of the JOIN products, and has a distinctly unholy feeling to it, I agree. I feel like there's not too much advantage to approach 2, since you have to know the column names anyways.
I would agree with @Mojtaba, however, that if you can't live with a pre-query to know the dynamic field names and ids, then I believe you're going to have to put sub-SELECT statements in there to pull those at query time.

A:

SELECT p.*
     , group_concat(CASE f.name WHEN 'telephone' THEN fp.value END) telephone
     , group_concat(CASE f.name WHEN 'address'   THEN fp.value END) address
  FROM person p
  JOIN field f
    LEFT JOIN fieldPerson fp
      ON    fp.personId = p.id
        AND fp.fieldId = f.id
  GROUP BY p.id


Q:

18.04 No mouse buttons work

I can login.  I was previously unable to click on the 'next' button on the 'welcome to 18.04' splash after login to finally get that off of my screen.  But now I can't do anything.
My USB mouse cursor moves, but no buttons work; left, middle, right.  I have tried two different mice(?) but still no joy.  The left button works fine on the login purple screen, but then it no long works on the desktop.  I have (login settings) tried both the GNOME on Xorg, an the Ubuntu, but both have the same problem - buttons don't work!
Looking at other suggestions on other answers, I did sudo ubuntu-drivers autoinstall but no joy.  I also do sudo apt update and upgrade, but no joy.
I'm able to login to the computer that has the problem via ssh from another system that is running 17.10.
So my 18.04 computer is totally down and unable to be used.  How can I debug/fix this?

A:

From the comments...
It was the Workspaces to Dock GNOME extension that caused the mouse and keyboard issues. It's a known problem with this extension. Rename the directory back, and then it should be uninstalled at https://extensions.gnome.org/local/
Update #1:
It seems that the latest update to this GNOME extension has fixed this problem.
Update #2:
Although the extension update fixed the original problem, it created new problems with the workspace overview.


Q:

Jquery cfml - none of the script is executable

I have a CF page that has a CFdiv.  The Cfdiv is bound to an element on the page.  The main page contains the script. None of the script executes on elements in the CFdiv. There seems to be a problem with the ajax call.  When I take that code out, the rest of the code seems to be enabled in Firebug but still will not execute.
<script type="text/javascript">
  $(document).ready(function () {
    $('#candidatesubmit').on('click', function () {
      $.ajax({
      type: 'POST',
      url: 'actEditStatusForm.cfm',
      data: 'form=',
      error: function (xhr, textStatus, errorThrown)(
      // show error
      alert(errorThrown);),
      success: function (response1, textStatus, jqXHR)(
      alert('success');)
       });
    ColdFusion.Grid.refresh('candidatesGrid', true);
  });
  $(function () {$("#JDOrgChartRESOutlineSentToCand").datepicker({dateFormat: 'yy/mm/dd'});});
  $(function () {$("#IndepthWRec").datepicker({dateFormat: 'yy/mm/dd'});});
</script>

A:

First, you have some syntax errors. Perhaps this is just a problem as pasted above, and not in your real code. But make sure the body of your error and success functions are surrounded by curly brackets, not parentheses.
So instead of this:
error: function (xhr, textStatus, errorThrown)(
  alert(errorThrown);),

You should have this:
error: function (xhr, textStatus, errorThrown) {
  alert(errorThrown);
},

Second, your grid refresh is outside the success function of the ajax call. Since that call is asynchronous, the grid refresh is likely running before that call has completed. Move the refresh into your success callback function, like this:
success: function (response1, textStatus, jqXHR){
  ColdFusion.Grid.refresh('candidatesGrid', true);
  alert('success');
}

Third, if the content of the cfdiv is being loaded asynchronously, and the #candidatesubmit element is inside that dynamically loaded content, your function will not be bound to its click event because it won't be present when the main page's ready event is triggered.
So instead of directly binding to the element, use a delegation strategy by listening for events on an enclosing element that you know will be present in the initial page load. So instead of this:
$('#candidatesubmit').on('click', function () {

Try something like this:
$('#some_outer_div').on('click','#candidatesubmit', function () {

#some_outer_div will now be listening for any click events that bubble up from its descendant elements (even those that were not present when the page first loaded). If the target of one of those clicks is #candidatesubmit, the handler will fire.


Q:

Calling a method of One View controller from Another View Controller

I have a method "someMethod" declared in OneViewController.h
@interface OneViewController
{
UIView *tempView;
..

}
-(void) someMethod ;
@end

and implemented in OneViewController.m file
@implementation OneViewController

-(void) someMethod
{
tempView = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 200, 250)];
tempView.backgroundColor = [UIColor yellowColor];
if([[self.view subviews] containsObject:tempView])
[tempView removeFromSuperView];
   else
   [self.view addsubview:tempView];

}

I want to call someMethod when present at different viewController - secondViewController
(something like [OneViewController someMethod]), So that when I get back to OneViewController I can see the changes made by someMethod.
Do I need to use appDelegate methods?
I have tried following but it doesn't work.
neViewController *newViewController = [[OneViewController alloc] init];
[newViewController someMethod];

Thanks for any help in advance..

A:

In the SecondViewController, declare a reference for OneViewController class. You can have assign property. Set the reference before you move to SecondViewController. Now with the reference, you can call the instance method [_oneView someMethod].
Edit:
Declare
OneViewController *_oneView;

Also add the assign property,
@property(nonatomic,assign) OneViewController *_oneView;

Synthesize the variable in .m file.
While showing the SecondViewController from OneViewController, just add the following line.
secondView._oneView = self;

A:

sometimes calling a method directlry creating [classObject methodName] does not refelect the changes in views. Like if you want to change a UIScrollView property from scrollEnble = NO; to scrollEnable = YES;, it does not refelect.
You should use singleton of UIApplication.
Suppose you want to call ViewController1's method - (void)myMethod in ViewController2 then here are the steps:

In you AppDelegate import ViewController1 and create its object *vc. Delare property @property (strong, nonatomic) ViewController1 *vc;. synthesize also.
Now come to Viewcontroller1 class. Import AppDelegate.h in you Viewcontroller1's and in viewDidLoad write like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 appDelegate.vc1 = self;
Go to your ViewController2.h and import AppDelegate.h
Go to the line where you want to call ViewController2's method and write like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 [[appDelegate vc1] myMethod]; // to allow scrolling


Q:

EXT JS Open form on btn Click

Relativly new to EXTJS,
I have an edit form that I want to show when the user clicks the edit button.
previously I had been doing it like this:
edit_window_xtype: 'window name',

which works perfectly, in this case I have a need to only call the form when the button is clicked and not when the user double clicks a field in my grid.(this is what edit_window_xtype: 'window name' would accomplish)
I had
btnEdit_onClick: function (btn) {
    Ext.create('window name').show();
},

but that doesn't work.

A:

It appears I have alot to learn with Extjs.  Here is what I came up with, If someone has a better solution please let me know.  Always looking for better ways to accomplish something.  :)
btnEdit_onClick: function (btn) {
    var config = {
        xtype: 'MyWindow_Name',
        mode: 'edit',
        title: 'Edit Window',
        editId: this.id
    };
    var win = Ext.ComponentMgr.create(config);
    win.show();
};


Q:

Qtip is not showing up

This is probably a really simple solution. But, I am new to jquery, and qtip. For the life of me I cannot get my qtip to show up. All that is shown is the default tooltip. Anyone know what could be the problem?
<html>
<head>
<link type="text/css" rel="stylesheet" href="/jquery.qtip.min.css"/>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type='text/javascript' src="/jquery.qtip.min.js"></script>

<script>
$('a[title]').qtip()
</script>

</head>
<body>
<a title="why wont this tooltip work" href ="#">Hello there punk
</body>
</html>

Here is a simple example that wont work, any suggestions?

A:

Reading the docs i think this is the way to do
and this should be called only after document is ready
$(document).ready(function()
{
    $('body a[href]').qtip();
});


Q:

How to finish several SingleInstance Activities?

I have several activities with launchMode SingleInstance.  On log out i want to finish all activities  and open launchScreen.
val intent = Intent(context, LauncherActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
(context as AppCompatActivity).finishAffinity()
context.startActivity(intent)

However if i press back at Launcher activity i am forwarded to previously launched activities with singleInstance mode

A:

UPDATE 11/1/2018:
I've tested multiple approach to deal with it such as event propagation, intent flags, counting activity instances, etc. There is some weird scenarios such as starting multiple singleInstance activities sequentially. In this case, middle activities doesn't start at all (onCreate method isn't called) and after pressing back button, they'll be started. Therefore no one of the prior approaches works! As the issue is a bit strange, I tried to solve it using a bit strange way.
We maintain the logout state in a singleton object called LogoutHandler. It cooperates with a class LogoutAwareActivity which is inherited by all activities except LoginActivity because it should not be affected by logout mechanism. When the logout occurs, a flag is set in the LogoutHandler until the last child of LogoutAwareActivity has finished then clears the flag.
Here is an implementation of that:
LogoutHandler:
import java.util.*

object LogoutHandler {

    private var isLogout = false
    private var timerWatchDog: TimerWatchDog? = null

    fun isLogout() = isLogout

    fun onActivityDestroyed() {
        if (isLogout) {
            timerWatchDog?.refresh(Runnable {
                isLogout = false
                timerWatchDog = null
            })
        }
    }

    fun logout() {
        isLogout = true
        timerWatchDog = TimerWatchDog(500)
    }

    private class TimerWatchDog(private val delay: Long) : Runnable {

        private var timer: Timer? = null
        private var runnable: Runnable? = null

        fun refresh(runnable: Runnable) {
            this.runnable = runnable
            timer?.cancel()

            val timerTask = object : TimerTask() {
                override fun run() {
                    Thread(this@TimerWatchDog).start()
                }
            }
            timer = Timer()
            timer?.schedule(timerTask, delay)
        }

        override fun run() {
            runnable?.run()
        }
    }

}

LogoutAwareActivity:
import android.support.v7.app.AppCompatActivity

abstract class LogoutAwareActivity : AppCompatActivity() {

    override fun onResume() {
        super.onResume()
        if (LogoutHandler.isLogout()) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LoginHandler.onActivityDestroyed()
    }

}

A concrete Activity:
class ActivityA : LogoutAwareActivity() {

    // ...
}

Another concrete Activity:
class ActivityB : LogoutAwareActivity() {

    // ...
}

Your logout function:
fun logout() {
    val intent = Intent(context, LoginActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    LogoutHandler.logout()
    context.startActivity(intent)
}

Visual Result:
All of MainActivity, ActivityA, ActivityB and ActivityC are single instance.
Traversing between activities by pressing back button:

Going to LoginActivity then pressing back button:

A:

Before launching splash screen add this line
ActivityCompat.finishAffinity(this)


Q:

Python: list(filter object) empties the object

guys!
I'm using Python 3.6.1 and got into an interesting issue:
I'm using a simple itertools.filter() to get a sub-list from an items list, and then I just print it twice.
items = [1,2,3,4,5]
operateVersions = filter(lambda t: t, items)
print ("1: %s" % list(operateVersions))
print ("2: %s" % list(operateVersions))

The result is weird:
1: [1, 2, 3, 4, 5]
2: []

so, when i run list(operateVersions) it somehow rewrites operateVersions filter object instead of just returning the list interpretation
Is it an OK behavior? It doesn't look for me it is

A:

A filter is a special iterable object, and like a generator, you can only iterate over it once. So essentially it returns an empty list when you run it a second time.


Q:

how to disable SSH login with password for some users?

On Linux (Debian Squeeze) I would like to disable SSH login using password to some users (selected group or all users except root). But I do not want to disable login using certificate for them.
edit: thanks a lot for detailed answer! For some reason this does not work on my server:
Match User !root
PasswordAuthentication no

...but can be easily replaced by
PasswordAuthentication no
Match User root
PasswordAuthentication yes

A:

Try Match in sshd_config:
Match User user1,user2,user3,user4
    PasswordAuthentication no

Or by group:
Match Group users
    PasswordAuthentication no

Or, as mentioned in the comment, by negation:
Match User !root
    PasswordAuthentication no

Note that match is effective "until either another Match line or the end of the file." (the indentation isn't significant)

A:

Match in sshd_config works well. You should use Match all to end the match block if you're using openssh 6.5p1 or above. Example:
PasswordAuthentication no
Match User root
PasswordAuthentication yes
Match all

A:

There are a few ways that you can do this - first, you could concievably run a second sshd daemon on a different port with different config - its a bit of a hack, but with some chroot work it should work just fine.
Also, you could allow password authentication, but lock the passwords
for all but the one user. The users with locked passwords will still be
able to authenticate with public keys.


Q:

Lotus Notes create email folder

Goal: excel macro that creates a new lotus notes email subfolder
I am totally new when it comes to VBA and Lotus Notes in general.
I would appreciate if smb would indicate some directions in achieving my goal, because until know I wasn't able to find anything similar.
1) how do I connect to needed mail (regarding this I saw some info, but a clear code example would be great)
2) how do I create the subfolder with a specified name and indicate the folder where it should be created

A:

There is no API for a folder architechture because there really is no folder architecture. Nested folders are an illusion just based on the name of the folder.  I.e., the folder name "folder1\folder2" indicates that folder2 appears to be inside folder1, but the structure is flat as far as all APIs are concerned.
The NotesDatabase.EnableFolder() method will create a folder.  (It's a dumb name for the method!)  Existing folders can be accessed via NotesDatabase.GetView() method because from the high-level API point of view Folder and Views are treated as equals.  The NotesView.Remove() method can be used to delete a folder. The NotesView.Name property is read/write.


Q:

Monitoring File Changes in C#

I'm using C# for a mini project of mine, I am trying to monitor files that are changed, Deleted, And/or created. And export that to a file. But I am not quite sure how to monitor files. Any ideas?

A:

You can use the FileSystemWatcher class to monitor file creation, modifications, deletions and renames.
You have the following events available:

Changed
Created
Deleted
Renamed

A:

you can only monitor one Directory with FSW, if you want more you may have to make multiple instances of FSW. It monitors the directory not the file; if the file is moved (changed+created; changed+renamed) then you need another FSW for that destination folder.


Q:

Restoring unprocessed SKPaymentTransaction for non-renewing subscription

In my app I want to implement non-renewing subscriptions. I have set up (I believe correctly) my logic. I place the observer in the app delegate and then in the class that implements SKPaymentTransactionObserver I implement the following function:
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { }

Within this method I loop through all the updatedTransactions and I check every transactionState, and accordingly I implement my logic.
What troubles me is this: when the transaction is successful I have to contact our servers to update the user's profile and add more days to his/her subscription. This means that I have to call SKPaymentQueue.default().finishTransaction(transaction) after I have received a successful response from our servers. However there is a chance that something goes wrong from the moment that Apple's servers send that the transaction has been completed, until our servers respond.
A shortcut would be to mark the transaction as finished as soon as Apple responds, but by reading the documentation, it doesn't seem correct. How can I restore an unprocessed transaction? (in the case our servers do not respond and the SKPaymentQueue.default().finishTransaction(transaction) is not called).
Thank you in advance.

A:

You should mark the transaction as finished only after your server acknowledges it.
If something does go wrong (let's say a crash occurs) between the time the transaction succeeds but your server hasn't seen it, the transaction will stay incomplete, and will be accessible in SKPaymentQueue.default.transactions right after you add the observer to the queue.
You can then grab those transactions or the receipt and send it to your server for another attempt at increasing the duration of their subscription.
Additionally, from Apple's docs:

For example, consider the case of a user buying something in your app
  right before going into a tunnel. Your app isn’t able to deliver the
  purchased content because there’s no network connection. The next time
  your app is launched, StoreKit calls your transaction queue observer
  again and delivers the purchased content at that time. Similarly, if
  your app fails to mark a transaction as finished, StoreKit calls the
  observer every time your app is launched until the transaction is
  properly finished.


Q:

What convict records for Australia exist?

Esther Emma Leach, born Sydney 15/5/1824, may have been the daughter of a convict transported to Australia in 1813. How do I find convict records not from the first 3 fleets?

A:

There are several very comprehensive collections of records concerning the people exported to Australia from the United Kingdom between 1788 and 1866.

The Convict Database has been compiled from British Home Office (HO) records which are available on microfilm as part of the Australian Joint Copying Project (AJCP). The HO 11 Criminal – Convict Transportation Registers series has been indexed by the State Library of Queensland and the index contains the following information:
Name of convict, including any known aliases
  Place of trial *
  Term of years
  Name of ship and date of departure
  Place of arrival
  Miscellaneous notes e.g. Died at sea; Ticket of Leave, etc.
  * The date of trial is recorded on the original registers and will be gradually added to this database

A search of that database indicates that there were 53 convicts named Leach among the 123,000 records and that 1812 was a particularly bad year for men of that name. There were three among the 200 convicts aboard the Fortune when it sailed in November of that year (reaching Sydney in 1813)

Title: Thomas Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Middlesex Gaol Delivery for a term of 14 years on 10 July 1811.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 85 (44)
  Record number: 1103363
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1103363
Title: Robert Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Middlesex Gaol Delivery for a term of life on 15 January 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 86
  Record number: 1101510
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101510
Title: James Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at York County Assizes for a term of life on 07 March 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 90
  Record number: 1101892
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101892

Of course, all of that is based on the assumption that the putative convict father's name was Leach. If it was not, then you can use these links to run your own searches.
Update
And if it happens that Esther is actually Esther Locke (who married William Watson in 1842) then her father might well be

Title: Stephen Locke, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Surrey Assizes for a term of life on 27 July 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 89 (46)
  Author/Creator: Great Britain. Home Office. ; State Library of Queensland.
  Subjects: Locke, Stephen ; Fortune (Ship) ; Convicts -- Australia -- Registers ; Australia -- Genealogy
  Publisher: Canberra A.C.T. : Australian Joint Copying Project
  Is Part Of: Criminal : Convict transportation registers [HO 11]
  Record number: 1101887
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101887


Q:

Windows 10 node-gyp cannot build: MSBUILD failed with exit code 1

Windows 10,
Microsoft Visual Studio 2013,
Node v0.12.7,
node-gyp v2.0.2
I always get the error build error with node-gyp:
Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1

Also in red color description:
Could not write lines to file "Release\obj\validation\validation.tlog\validation.lastbuildstate". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Bigger excerpt of error:
https://gist.github.com/nerijusgood/63e54d9c376999a044bb
As I understand everything is running fine, however msbuild cannot write long path names. Is there a patch for this or windows workaround?

A:

Long file paths is a big issue with Visual Studio that Microsoft has stated that they have no plans to fix in the near future!
Try moving your solution folder to the root of the drive (c:\project)
Also NPM version 3+ changes the module folder structure so they are not nested so deep. (it says it's in beta but seems to have solved some problems for me)
Regarding your post on Github, (I've been running into an endless string of problems with NPM and node-gyp as well, apparently everything is made to work well on linux!)

You probably need to install VS2013 (you can use the express version, make sure it includes c++)
From the npm errors on github:
v120 is VS2013
v140 is VS2015
To make node-gyp use the correct version for the package you are installing you may need to set an environment variable in Windows.
set GYP_MSVS_VERSION=2013
(if you set it in your windows system properties make sure to restart your command prompt)

A:

Edit: The question in title is a bit different from OP's actual issue (which this answer addresses).
For node-gyp, or MSBUILD errors in general please see other questions.
To solve the "The specified path, file name, or both are too long." issue, update npm to version 3+. This has been bothering all windows users for a while now, and the answer is to flatten your dependencies. npm@3.x automatically flattens all dependencies to the root even during install.


Q:

Why can't java find StringEntity class even after importing org.apache.http packages?

I am using a  sample code from Microsoft Cognitive Services. It makes use of StringEntity class to make request to the REST API. The java compiler seems to be unable to find 'symbol' StringEntity? What could be the reason for this and how to resolve this?
Here goes the code -
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;

public class NEWS_FETCHER
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/news/search");

            builder.setParameter("q", "microsoft");
            builder.setParameter("count", "10");
            builder.setParameter("offset", "0");
            builder.setParameter("mkt", "en-us");
            builder.setParameter("safeSearch", "Moderate");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<Key goes here>");

            // Request body
            StringEntity reqEntity = new StringEntity("");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Most of it is taken from Microsoft API Test Sample.
https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

A:

The class StringEntity is in the package org.apache.http.entity, so you have to add the correct import for that:
import org.apache.http.entity.StringEntity


Q:

Folder/File browser with MVC 2?

How can you create a route that accept an undefined number of strings?
The folder browser should be able to browse the specified folder and all the sub folders.  Using JQuery to get the folders back from the server. The problem is how to build the JQuery?
$.ajax({
           type: "POST",
           url: "http://localhost:30218/Data/Folder1/Folder2/etc",
           dataType: "json",
           success: function (data) { }
       });

I mean, how can you create a MVC 2 url that could be like 10 subfolders deep? I don't want to define a static number of maximum folders that it can contain. How can you create the url and what routing should you use? Querystrings for subfolders?

A:

You can use the catchall on the last route segment, which is the asterisk character, like so:
"Files/{action}/{*path}"

That would cause everything at the end to be lumped together in the path parameter.