text:
Q: CoreData serious application error Every once in awhile, I get the following error message in my application.  This happens after my application receives back a web service response via RestKit w/ CoreData integration:
CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  no object at index 3 in section at index 0 with userInfo (null)
2014-07-28 12:48:26.348 Identify[43074:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'
*** First throw call stack:
(
    0   CoreFoundation                      0x0270e1e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x0248d8e5 objc_exception_throw + 44
    2   CoreData                            0x006d7dbe -[NSFetchedResultsController objectAtIndexPath:] + 398
    3   Identify                            0x0002d03e -[WTSRecordListViewController configureCell:atIndexPath:] + 190
    4   Identify                            0x0002c5f6 -[WTSRecordListViewController controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:] + 646
    5   CoreData                            0x006df296 -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] + 5238
    6   Foundation                          0x02160049 __57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke + 40
    7   CoreFoundation                      0x02769f04 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
    8   CoreFoundation                      0x026c1efb _CFXNotificationPost + 2859
    9   Foundation                          0x02099e41 -[NSNotificationCenter postNotificationName:object:userInfo:] + 98
    10  CoreData                            0x005e1a13 -[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] + 83
    11  CoreData                            0x00680faf -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] + 367
    12  CoreData                            0x005dceb8 -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2152
    13  CoreData                            0x005e02fc -[NSManagedObjectContext save:] + 140
    14  Identify                            0x000d1ffd __61-[NSManagedObjectContext(RKAdditions) saveToPersistentStore:]_block_invoke + 125
    15  CoreData                            0x0060584f developerSubmittedBlockToNSManagedObjectContextPerform + 95
    16  CoreData                            0x0060578c -[NSManagedObjectContext performBlockAndWait:] + 140
    17  Identify                            0x000d1b83 -[NSManagedObjectContext(RKAdditions) saveToPersistentStore:] + 739
    18  Identify                            0x00048d28 __80-[WTSObjectManager getRecordsForUser:forGroup:startIndex:limit:success:failure:]_block_invoke_2 + 2456
    19  Identify                            0x0014f551 __66-[RKObjectRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke244 + 97
    20  libdispatch.dylib                   0x02f747b8 _dispatch_call_block_and_release + 15
    21  libdispatch.dylib                   0x02f894d0 _dispatch_client_callout + 14
    22  libdispatch.dylib                   0x02f77726 _dispatch_main_queue_callback_4CF + 340
    23  CoreFoundation                      0x0277343e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    24  CoreFoundation                      0x026b45cb __CFRunLoopRun + 1963
    25  CoreFoundation                      0x026b39d3 CFRunLoopRunSpecific + 467
    26  CoreFoundation                      0x026b37eb CFRunLoopRunInMode + 123
    27  GraphicsServices                    0x0367c5ee GSEventRunModal + 192
    28  GraphicsServices                    0x0367c42b GSEventRun + 104
    29  UIKit                               0x0114df9b UIApplicationMain + 1225
    30  Identify                            0x0000279d main + 141
    31  libdyld.dylib                       0x031be701 start + 1

Once it gets into this state, there is no way to fix it without removing the app and adding it back on to the device.  I am using the stock boilerplate code apple defines for Core Data fetch results controllers:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    NSLog(@"begin updates");
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            NSLog(@"inserting section");
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            NSLog(@"deleting section");
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    UITableView *tableView = self.tableView;

    switch(type) {
        case NSFetchedResultsChangeInsert:
            NSLog(@"inserting row");
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            NSLog(@"deleting row");
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            NSLog(@"update row");
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            NSLog(@"move row");
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    NSLog(@"end updates");
    [self.tableView endUpdates];
}

The configureCell method just looks like this and is failing when I'm getting the record from the fetchedResultsController:
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    //if a nil cell was passed into this method, just return
    if (!cell) {
        return;
    }

    WTSRecordCell *recordCell = (WTSRecordCell *)cell;
    WTSRecord *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
...
}

The following code is where I create the fetchedResultsController.  In my application, I create two separate instances of WTSRecordListViewController, one with a fetch request that returns back 'records' by user and the other returns 'records' by group.
- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController == nil) {
        WTSUserInfo *userInfo = [WTSConfiguration sharedConfig].orgConfig.userInfo;
        NSFetchRequest *fetchRequest = nil;
        if (self.type == RecordListTypeUser) {
            fetchRequest = [[WTSObjectManager sharedManager] fetchRequestForRecordsByUser:userInfo.username];
        } else if (self.type == RecordListTypeGroup) {
            fetchRequest = [[WTSObjectManager sharedManager] fetchRequestForRecordsByGroup:userInfo.groupId];
        }

        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createDt" ascending:NO];
        NSArray *sortDescriptors = @[sortDescriptor];
        [fetchRequest setSortDescriptors:sortDescriptors];

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"sectionName" cacheName:nil];
        aFetchedResultsController.delegate = self;
        self.fetchedResultsController = aFetchedResultsController;

        NSError *error = nil;
        if (![self.fetchedResultsController performFetch:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            DDLogWarn(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }

    return _fetchedResultsController;
}

I'm not sure what I am doing wrong here, and if this is some sort of bug in Apple's code.  Like I said previously, this happens only once in awhile (probably when the backend core data is in some sort of very specific state, since I can never seem to recreate it after it happens).
EDIT:
After some additional searching around, I found the code that is causing the problem.  In the success block in RestKit for the web service call I am making, I iterate through some database objects setting certain values.  When I am done iterating through the values, I call [context saveToPersistentStore]; that call is what is causing the fetched results controller methods to be fired.  If I comment out the saveToPersistentStore call, I don't get the exception.
The success block in RestKit gets executed on the main thread.  Also, according to my printouts, the block gets executed outside of the controllerWillChangeContent: and controllerDidChangeContent: methods.
EDIT 2:
The following code is where I make my web service call via RestKit.  In it, I iterate through the objects returned back in the mapping array setting how the records were fetched for later orphan purging.  I also execute a fetch request on the records not returned back from the fetch request and clear out a flag (also for orphan purging).
No where in my RestKit success blocks am I checking to make sure that the objects returned in the mapping request are deleted or objects returned from a fetch request are deleted before modifying them.  Is this something I need to do?
[self.rkObjectManager getObjectsAtPathForRouteNamed:kWTSRecordsRouteName object:nil parameters:params success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        NSArray *records = [mappingResult array];

        //we put the record ids we get back in the request in a set
        NSMutableSet *recordIds = [NSMutableSet new];

        //set in the record how this was fetched
        NSManagedObjectContext *context = nil;
        for (WTSRecord *record in records) {
            [recordIds addObject:record.recordId];
            if (!context) {
                context = record.managedObjectContext;
            }

            if (groupId) {
                record.fetchedViaGroup = [NSNumber numberWithBool:YES];
            } else {
                record.fetchedViaUser = [NSNumber numberWithBool:YES];
            }
        }

        //if the startIndex is 0, the user is refreshing.  We clear the 'fetchedVia*' field for any records that DID NOT come back in this request
        if (startIndex == 0) {
            NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"WTSRecord"];
            if (groupId) {
                request.predicate = [NSPredicate predicateWithFormat:@"recordId != nil AND fetchedViaGroup == 1 AND pendingDelete == 0"];
            } else {
                request.predicate = [NSPredicate predicateWithFormat:@"recordId != nil AND fetchedViaUser == 1 AND pendingDelete == 0", user];
            }

            NSArray *records = [context executeFetchRequest:request error:nil];
            for (WTSRecord *record in records) {
                if (![recordIds containsObject:record.recordId]) {
                    if (groupId) {
                        record.fetchedViaGroup = [NSNumber numberWithBool:NO];
                    } else {
                        record.fetchedViaUser = [NSNumber numberWithBool:NO];
                    }
                }
            }
        }

        //save the changes to the persistent store
        [context saveToPersistentStore:nil];

        success(records);
        dispatch_semaphore_signal(sem);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        failure(error);
        dispatch_semaphore_signal(sem);
    }];

EDIT 3
I found the code that is causing the problem in the above snippet:
//set in the record how this was fetched
            NSManagedObjectContext *context = nil;
            for (WTSRecord *record in records) {
                [recordIds addObject:record.recordId];
                if (!context) {
                    context = record.managedObjectContext;
                }

//              if (groupId) {
//                  record.fetchedViaGroup = [NSNumber numberWithBool:YES];
//              } else {
//                  record.fetchedViaUser = [NSNumber numberWithBool:YES];
//              }
            }

With the following lines commented out, I am able to make the call to saveToPersistentStore without issues.  What am I doing wrong here?  What is the acceptable way to modify objects that come back in a mappingResult and save the changes to the local data store?

A: My best answer without knowing all the details of how you have set up your view controller, is that this issue commonly occurred for me when I had.
A. Inserted a Table View into a View Controller
B. Saving data in the same View Controller.
Regardless of my circumstances, if you are going to save data in a view that also has a Table View you need to remove the following methods which are in your code:
- (void) controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath

AND
-(void) controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type

The error that occurs is because the fetched results suddenly has changes that the table view is not yet able to recognise ie. "no object at index 3 in section at index 0".
If you want to have the table respond to the changes you need to add a refresh method and call it after the data has been saved (sounds obvious but Stack Exchange has it's share of people who don't understand that) ie. [self refresh]; So in your -(IBAction *) save: (id) sender method (or void method if you're using that to save), call it from within there.
Hope this helps anyone in future.


text:
Q: Submit Multiple Selected Rows Jquery Datatables I am new to jquery.  I am working in Laravel 5.3.  I am loading jquery and datatables min.css and min.js through my master blade template.  I am consuming an API to get a list of livestock that belongs to a member and outputting with jquery datatables.  Each row is selectable so the user can select which animals they want to enter into a show.  The datatable is paginated and I can select animals on each page.  However, when I click Enter Show, all animals on the currently displayed page get submitted rather than only those selected, regardless of page, however, the number of animals selected is displayed correctly in the alert.  What can I do to fix this so only the selected rows are submitted?
My code:
                    <form action="/entershowoptions" method="POST" id="entriesSelected">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    <input type="hidden" name="show_id" value="{{ $show_id }}">
                    <input type="hidden" name="memberId" value="{{ $memberId }}">

                            Reg #
                            Name
                            DOB
                            Sex

                        @foreach($mygoatsarray as $mygoat)
                            @if($buckDivisionCount < 1 && $mygoat->GOAT_SEX == 'BUCK')
                                @continue
                            @elseif($doeDivisionCount < 1 && $mygoat->GOAT_SEX == 'DOE')
                                @continue
                            @else

                                {{ $mygoat->OLD_REG_NUM }}
                                <input type="hidden" name="entry_reg_num[]" value="{{ $mygoat->OLD_REG_NUM }}">
                                {{ $mygoat->GOAT_NAME }}
                                <input type="hidden" name="entry_reg_name[]" value="{{ $mygoat->GOAT_NAME }}">
                                {{ $mygoat->DATE_OF_BIRTH }}
                                <input type="hidden" name="entry_dob[]" value="{{ $mygoat->DATE_OF_BIRTH }}">
                                {{ $mygoat->GOAT_SEX }}
                                <input type="hidden" name="entry_sex[]" value="{{  $mygoat->GOAT_SEX }}">

                            @endif
                        @endforeach

                    <button id="submit">Enter Goats</button>

                    </form>

A: Add a call to  preventDefault() on the event (1st argument of the event callback) to prevent the form from submitting and then it will run the .ajax() submit. Try this in the example below:
Edit:
Instead of using $("#entriesSelected").table.rows('.selected').serialize(), use serialize() on an array of the inputs in the selected rows using a basic selector - i.e. $('.selected input').serialize().

$(document).ready(function() {
  var table = $('#goatTable').DataTable();

  $('#goatTable tbody').on( 'click', 'tr', function () {
      $(this).toggleClass('selected');
  } );

  $('#submit').click( function (e) {
    e.preventDefault();
    var selectedRowInputs = $('.selected input');

    //use the serialized version of selectedRowInputs as the data
    //to be sent to the AJAX request

    console.log('serlialized inputs: ',selectedRowInputs.serialize());
    /*
      $.ajax({
        type: "POST",
        url: "/entershowoptions",
        data: selectedRowInputs.serialize()
      });
    */
  });
});
<link href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet"/>

<form action="/entershowoptions" method="POST" id="entriesSelected">
  <input type="hidden" name="_token" value="23523">
  <input type="hidden" name="show_id" value="533">
  <input type="hidden" name="memberId" value="4567">

        Reg #
        Name
        DOB
        Sex

        1<input type="hidden" name="entry_reg_num[]" value="1">
        Dan<input type="hidden" name="entry_reg_name[]" value="Dan">
        01/03/2010<input type="hidden" name="entry_dob[]" value="01/03/2010">
        Male<input type="hidden" name="entry_sex[]" value="Male">

        2<input type="hidden" name="entry_reg_num[]" value="2">
        Elsa<input type="hidden" name="entry_reg_name[]" value="Elsa">
        02/03/2011<input type="hidden" name="entry_dob[]" value="02/03/2011">
        female<input type="hidden" name="entry_sex[]" value="female">

        3<input type="hidden" name="entry_reg_num[]" value="3">
        Fred<input type="hidden" name="entry_reg_name[]" value="Fred">
        03/03/2012<input type="hidden" name="entry_dob[]" value="03/03/2012">
        Male<input type="hidden" name="entry_sex[]" value="Male">

  <button id="submit">Enter Goats</button>
</form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Distributed training of a GRU network on Spark - PyTorch implementation I have an implementation of a GRU based network in PyTorch, which I train using a 4 GB GPU present in my laptop, and obviously it takes a lot of time (4+ hrs for 1 epoch). I am looking for ideas/leads on how I can move this deep-learning model to train on a couple of spark clusters instead.
So far, I have only come across this GitHub library called SparkTorch, which unfortunately has limited documentation and the examples provided are way too trivial.
https://github.com/dmmiller612/sparktorch
To summarize, I am looking for answers to the following two questions:

*

*Is it a good idea to train a deep learning model on spark clusters, since I read at places that the communication overhead undermines the gains in training speed

*How to convert the PyTorch model (and the underlying dataset) in order to perform a distributed training across the worker nodes.

Any leads appreciated.


text:
Q: Typeahead.js not showing async results I'm working on implementing typeahead.js in a search field and I'm having problems with async results only showing once in a while, while local results always work.
My suggestion backend returns data this JSON:
[{
    "query": "anders troelsen",
    "hits": "1197",
    "queryCount": "39"
},
{
    "query": "anders fogh jensen",
    "hits": "295",
    "queryCount": "38"
}]

In the code I want to transform the above JSON into an array of strings and then show it. This is the suggester code:
    var localSuggestResults = ["anders and", "anders ladekarl", "anders høg nissen"];

    var searchSuggestions = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: localSuggestResults,

        remote: {
            url: '/services/suggest?prefix=%QUERY',
            wildcard: '%QUERY',

            transform: function (suggestions) {
                var suggestionArray = suggestions.map(function(suggestion) {
                    return suggestion.query
                });

                return suggestionArray;
            }
        }

    });

    $("#query").typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        source: searchSuggestions
    });

Any suggestions for what I'm doing wrong? Thanks a lot!

A: it's late for response. but the library didn't change during this time.
asyncResult works when you set {async:true} in ajax options. set source to your own function that gets the result from server.


text:
Q: JWT token with Auth0 Java using Javalin I'm using Javalin and want to build authentication flow, with Auth0 I can make token and send it with header in request, But how I can get my User data from that token? How I can check which user is authenticated at that moment

A: There are examples on the github repo https://github.com/auth0/java-jwt/blob/master/EXAMPLES.md
To get information from a token created with claims
String token = JWT.create()
    .withClaim("username-claim", "username")
    .sign(algorithm);

You can verify and get a claim by doing the following
DecodedJWT jwt = JWT.require(algorithm)
    .build()
    .verify(token);

String usernameClaim = jwt.getClaim("username-claim").asString();


text:
Q: Chopping arithmetic on terms such as $\pi^2$, $\pi^3$ or $e^3$ I have a problem where I have to use 3-digit chopping with numbers such as $\pi^2$, $\pi^3$, $e^3$, etc.
If I wanted to 3-digit chop $\pi^2$, do I square the true value of $\pi$ and then chop, or do I chop $\pi$ first to 3.14 then square it?

A: If you chop $\pi$ then square then chop, what you are really chopping is $3.14^2$ not $\pi^2$. So you must take $\pi^2$ and then chop it.

A: As a rule of thumb: Always do the chopping / rounding as late as possible.


text:
Q: Dynamic Column Reference I have a table that is like such called "Stocks"
That has a list of tickers across the top row, dates going down Col A and prices in each column for the stocks.

and it goes on for 15 years.
On another sheet call it (Trades) I want a user to enter say "ABC" into a cell and on that table it will pull the price for specific dates that on Trade sheet.
I want to be able to do an index match with a dynamic variable so that a user can enter any symbol and the prices will come up.  I have a match formula which gets me the column the ticker is in but can't get this into a index/match formula
=MATCH(E1,SPY!A1:D1,0)

A: here is a you can use match in both the column reference and the row reference; that said lets say you have the dates in column A. and the date they are looking up in c1 you can do =Index(STOCKS,MATCH($C$1,Stocks[[Date]:[Date]],0),match($E$1,STocks[#Headers],0)) and that should do what you are looking for.


text:
Q: Is it possible to use Portable Class Libraries(PCL) with Visual Studio Online hosted build server? I'm trying to use the Hosted Builder server from Visual Studio Online.
I'm using Visual Studio 2015.
Everything works fine until I'm including a Portable Class Library (PCL).
I get errors related to the AssemblyInfo.cs file:
Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (9, 12)
        The type or namespace name 'AssemblyTitle' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (10, 12)
    The type or namespace name 'AssemblyDescription' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (11, 12)
    The type or namespace name 'AssemblyConfiguration' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (12, 12)
    The type or namespace name 'AssemblyCompany' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (13, 12)
    The type or namespace name 'AssemblyProduct' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (14, 12)
    The type or namespace name 'AssemblyCopyright' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (15, 12)
    The type or namespace name 'AssemblyTrademark' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (16, 12)
    The type or namespace name 'AssemblyCulture' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (17, 12)
    The type or namespace name 'NeutralResourcesLanguage' could not be found (are you missing a using directive or an assembly reference?)
    Source\TestprojectSolution\TestprojectPCL\Properties\AssemblyInfo.cs (29, 12)
    The type or namespace name 'AssemblyVersion' could not be found (are you missing a using directive or an assembly reference?)

Is it possible to use a PCL togehter with the hosted build server? If so, how can I do that?

A: I just answered this question here: https://stackoverflow.com/a/33571729/1123431
The reason this is happening is because the version of NuGet on the Build Agent is not sufficient enough to generate a project.lock.json file from a project.json file.  Until Microsoft updates the version of NuGet on their default servers, we'll just have to check-in the project.lock.json file with our projects.

A: I found my solution of the problem, not sure it is the same for everybody though.
My projects were created with VS2013 and I enabled automatic nuget restore. In VS2013 you get a .nuget solutionfolder and some xml code in your projectfiles.
This is a "old way" restoring nuget packages during msbuild.
The xml code is near the bottom of your cproj files, it should look something like this:
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

Removing this solution folder and the xml code from the projectfiles (you have to unload the projects first) fixed my problem.
See more information:
https://docs.nuget.org/consume/package-restore#automatic-package-restore-in-visual-studio
(They cleary say at the  top, don't mix the old and new styles ;-))
I hope this helps!


text:
Q: How to get information about identified point and exclude it in next plot in R i've got problem with identify().
I have something like this
library (UsingR)
df=data.frame(emissions)
plot (df)
getPoint=identify(df)

And I have to exclude the point  that is too far away from correct observation group.
How can I take this uncorrect point save it, exclude it, and get the correct frame in next plotting without saved point?

A: First off I tried using identify on a data frame plot- it doesn't seem to work so instead I did one comparison- GDP vs perCapita:
plot(df$GDP,df$perCapita)
getPoint=identify(df$GDP,df$perCapita)

I then picked a few points on the plot and then pressed 'ESC'
getPoint returns the number of the row of the points that I picked. I can then omit or select these points:
df[getPoint,] #select picked data points
df[-getPoint,] #exclude picked data points


text:
Q: How to get a Unicode-supporting font for Windows 7 command-line? I've pointed the command-line to the right codepage (chcp 65001), but there's a lot of Unicode
characters that Consolas and Lucida Console can't show. Specifically, I want the printable IPA characters to show up. It's not important to fix multi-codepoint glyphs, although it would be nice.
How can I get such a font and install it for the command-line?
Below is an example of some characters that can't be rendered.

A: I do not know much about that font, but read these two links to see if you can make them work.
http://www.hanselman.com/blog/UsingConsolasAsTheWindowsConsoleFont.aspx
http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815


text:
Q: Calculating current for a parallel array of in-series LEDs I am getting an odd reading from an array of LEDs, which I could do with a little help understanding. I have a very specific project, but to abstract this question from that, let's assume the following:
I have 24 LEDs in 4 sets, each of 6 LEDs with a 68ohm resistor.  They are 1.8v LEDs using 20mA and I have a 12v supply.

simulate this circuit – Schematic created using CircuitLab
I understand how to calculate the required resistor and current for single LEDs but I used the rather excellent http://led.linear1.org/led.wiz to do the math for me on this.  It concludes my array will use 80mA.
However, when I use my meter, it tells me the array is only using 8mA?!
I am planning to run this from my Arduino Micro, which can easily deliver 8mA from a pin but certainly not 80mA, so the difference is crucial to me.
Initially I thought I was reading the meter wrong (it's new) and I was out by a factor of 10 but the only other thing of a known(ish) current I could benchmark my meter with at 12v was the Arduino itself, which is drawing 37mA, which to me sounds about right (and 370mA would seem too high for a Micro), meaning my meter is probably correct?
I know you can get variations in LEDs or whatever, but I have 3 of these arrays and they are all reading the same ~8mA.  What am I missing or should this array be pulling only 8mA?  How should a parallel array of in-series LEDs be calculated?
Thanks for any help.

A: How much current flows through each branch of the circuit?
All branches are in parallel with the 12V source, so there is 12V across each branch.
$$12V = 6*V_{LED} + I_{BRANCH}*68\Omega$$
\$V_{LED}\$ is about 1.8V, so
$$1.2V = I_{BRANCH}*68 \Omega$$
$$\frac{1.2V}{68\Omega}=I_{BRANCH}\approx18mA$$
You have four identical branches each conducting the same magnitude of current, so the total current is about 4*18mA = 72mA. The tool you used gives a reasonable estimate.
If you accidentally used \$680\Omega\$ (Blue Grey Brown) resistors instead of \$68\Omega\$ (Blue Grey Black) resistors, the current will be 10% of the calculation above, giving around 8mA.

A: I think you are ignoring the tolerance on these LEDs for Vf.
I have never seen any 20 mA LEDs rated for 1.8V max, only typical.
If in fact they were Vf=2.1 @ 20mA then this would explain why you are only getting 8mA.
What you could do is measure the Vf on a single LED and then measure Vss=12.?V to confirm this is true. Then 8mA*68R=0.5V (approx) so 11.5V/6 = 1.92V @ 8mA which makes sense.
Solution.
Reduce string to 5 LEDs and recompute R for actual Vf . My estimate is  2.1V @ 20mA based on your accurate results.  Then (12V-(5LEDs*2.1V))/20mA= 1.5V/20mA = 75 ohms  ( so 68 will be slightly more than 20 mA)
Or change it from 6S4P to 5S5P  using 25 LEDs
Conclusion.
Pay more attention to tolerances.
All diode Vf variation is due to ESR variation and not the threshold at 100uA or even 1mA.
So if you want more accurate LED current in your designs, specify sources with tighter tolerances on Vf or select on batches , measure vf and choose Rs to meet your tolerance on current.  Each batch of 200 LEDs or so ought to be within 1% if they are not mixed up or unsorted or worse untested by cheap and dirty distributors.


text:
Q: XPath for extracting Data from Similar named Nodes I have an XML something like this:
<root>
   <A>
    <B>
      <Parameter_Name label="type_A">Text</Parameter_Name>
      <Parameter>ABC</Parameter>
    </B>

    <B>
      <Parameter_Name label="type_B">Number</Parameter_Name>
      <Parameter>123</Parameter>
    </B>

    <B>
      <Parameter_Name label="type_C">Date</Parameter_Name>
      <Parameter>YYYYMMDD</Parameter>
    </B>
   </A>
</root>

Notice the <B> </B> element repeats itself. How does the XPath look like if I have to access the value of <Parameter> for the Parameter_Name label "type_B" (which will be 123). I am not looking for the hard coded approach of using .../B[2]/Parameter, I am trying to find out the generic XPath for that.
Hope the question was clear. Thanks in Advance!

A: Use a predicate:
/root/A/B[Parameter_Name/@label='type_B']/Parameter


text:
Q: Core Data: how to avoid saving to persistent store until all data has been processed? I am new to Core Data and am struggling with a problem. In my game I occasionally have to work on and then save a large amount of data before moving on to the next level (all on the main thread). The flow is something like this:
workOutResults()
processUpdates()
saveContext
moveToNextLevel()

Because processUpdates() needs to fetch data that was updated in workOutResults(), I have to saveContext after workOutResults() otherwise I get an 'unrecognized selector' error.
So the flow is now:
workOutResults()
saveContext
processUpdates()
saveContext
moveToNextLevel()

This works well, but it takes about 5 seconds (which I am fine with). My issue is what happens if the app is killed while in the middle of this process (battery fail for example, or the user may exit the app for some reason)? Say this happens:
workOutResults()
saveContext
[app is killed here]

When the app relaunches, it will attempt to run workOutResults() again and I will get duplicate data because it has saved it.
So my question is how can I ONLY save the data to the persistent store at the end of the process? How do I avoid having to save between workOutResults() and processUpdates() in order to work on the same data?


text:
Q: 3rd party gaming mouse works before login but stops working afterwards I replaced my broken gaming mouse with a new one and it doesn't work. The weird thing is that the mouse works when I reboot but only until I login, then the LEDs turn off and the mouse doesn't do anything (as if it is completely disconnected).
My setup is a MacBook Pro (Retina 15-inch late 2013) macOS Sierra.

A: The first thing I would do is try booting into Safe Mode.
Boot into Safe Mode
Follow these steps to boot your Mac into Safe Mode:

*

*Fully shut down your Mac

*Restart your Mac

*Immediately press the Shift key and keep it down

*Let go of the Shift key when you see the login window (NOTE: If you have FileVault enabled you may need to log in twice).

*Take a note of what happens (i.e. does the mouse work properly, etc)

*Exit Safe Mode by restarting your Mac as normal

*Test again when booted normally

Let me know how these steps went and we'll go from there.


text:
Q: Cross product in 2D by rending k component 0 I was wondering why the cross product does not work in 2D. For example, would it work if I made the changed the k component to 0 and thus have the cross product take place result in a vector that would only lie on the x and y-axis ?
i.e.
If $\\v_1=[a,b,c] $ and $\\v_2=[d,e,f] $
But since the vectors take place in only the $\\x,y-plane $
Let $c=f=0 $
Thus
$\\V_2\times V_1=({{[b(0)-e(0)],[a(0)-d(0)],[a(e)-b(d)]}}) $
Which effectively equates to
$\\V_2\times V_1=[0,0,(ae-bd)] $
Am I breaking anything by effectively doing this? Because since surely 2D vectors are just a subset of the 3D vectors, rending the k component a 0, doesn't change anything?
All thoughts are appreciated on my line of reasoning.

A: $v_2\times v_1$ is perpendicular to the plane containing $v_1$ and $v_2$. If you choose $v_1,v_2$ to lie in the $xy$-plane, the only vectors perpendicular to this plane are of the form $(0,0,p)$, which explains why $v_2\times v_1$ is of this form.

A: Strictly speaking, the cross product is undefined in $\mathbb R^2$. You can embed the plane into $\mathbb R^3$ the way you're proposing, and yes, the geometric meanings of the cross product still apply. However, you can perform the same computation entirely in $\mathbb R^2$ with a determinant: If $v_1=[a,b]^T$ and $v_2=[c,d]^T$, then $\det[v_1,v_2]=ad-bc$ is exactly the same as the $z$-component of the cross product $[a,b,0]\times[c,d,0]$. This, too, gives you the (signed) area of the paralellogram defined by $v_1$ and $v_2$ and, unlike the cross product, generalizes to higher dimensions. That is, in $\mathbb R^n$, the absolute value of $\det[v_1,\dots,v_n]$ is the volume of the paralellotope defined by these vectors and the sign indicates their relative orientation. If it vanishes, the vectors aren't linearly independent and the paralellotope "collapses."

A: There is an equivalent of the cross product in 2D, which does the useful things like measuring area, but it produces a scalar quantity (not surprisingly in the case of area, which should be directed in 3D but is a scalar quantity in 2D, like the volume is in 3D). If we define the cross product to be the bilinear map that satisfies $\mathbf{e}_i \times \mathbf{e}_j = \epsilon_{ijk} \mathbf{e}_k$ for the usual basis of $\mathbb{R}^3$, using the Levi-Civita symbol, so it satisfies
$$ \mathbf{a} \times \mathbf{b} = (a_i \mathbf{e}_i) \times (b_j \mathbf{e}_j) = \epsilon_{ijk} a_i b_j \mathbf{e}_k  $$
The Levi-Civita symbol in $n$ dimensions has $n$ indices, and is antisymmetric in the indices. In particular, the two-dimensional version has
$$\epsilon_{12} = - \epsilon_{21} = 1 \\
\epsilon_{11} = \epsilon_{22} = 0 , $$
so we can define a bilinear antisymmetric map by
$$ [\mathbf{e}_i,\mathbf{e}_j] = \epsilon_{ij} , $$
so
$$ [\mathbf{a},\mathbf{b}] = [a_i \mathbf{e}_i , b_j \mathbf{e}_j] = \epsilon_{ij} a_i b_j = a_1 b_2 - a_2 b_1 , $$
although this is more like a two-dimensional version of the scalar triple product, since it is a map that gives a scalar, that measures the area of the parallelogram generated by $\mathbf{a}$ and $\mathbf{b}$.
Alternatively, we could take a linear map of one vector that gives a "perpendicular",
$$ \mathbf{e}_i^{\perp} = \epsilon_{ij} \mathbf{e}_j , $$
which is a more direct analogy, giving a vector that is a fixed perpendicular to the argument (in this case, a rotation by $\pi/2$). Then
$$ \mathbf{a}^{\perp} = a_i \mathbf{e}_i^\perp = a_i \epsilon_{ij} \mathbf{e}_{j} = -a_2 \mathbf{e}_1 + a_1 \mathbf{e}_2 . $$
Both of these constructions also extend to $n$ dimensions, so that the perpendicular map always acts on $n-1$ vectors and gives another,
$$ (\mathbf{e}_{i_1},\mathbf{e}_{i_2}, \dotsc, \mathbf{e}_{i_{n-1}} )^{\perp} = \epsilon_{i_1 i_2 \dotsm i_{n-1} i_n} \mathbf{e}_{i_n}, $$
where the Levi-Civita symbol is given by the sign of the permutation taking $1,2,\dotsc,n$ to $i_1, i_2 \dotsc i_n $, and the scalar $n$-product/volume map,
$$ [\mathbf{e}_{i_1},\mathbf{e}_{i_2}, \dotsc, \mathbf{e}_{i_n} ] = \epsilon_{i_1 i_2 \dotsm i_n} , $$
so
$$ [\mathbf{a}^{(1)},\mathbf{a}^{(2)},\dotsc,\mathbf{a}^{(n)}] = \epsilon_{i_1 i_2 \dotsm i_n} a^{(1)}_{i_1} \dotsm a^{(2)}_{i_n} , $$
which you may recognise as the determinant of the matrix with entries $a^{(i)}_{j}$.


text:
Q: Struts2 form with two buttons -- action not being processed correctly I've tried searching the forums for the answer to this, and I've been unsuccessful.  I have a Struts2 form with two buttons, and I want the action class to perform a different action depending on which button was pressed.  That's not happening.  Can anyone help me with this?  Here is my form, followed by the action class.
    <s:form action="ApproveBulletin" method="post">

                From: <s:property value="name" />

                Subject: <s:property value="subject" />

                Date: <s:property value="date" />

                <s:property value="note" />
                    <s:hidden name="id" value="%{id}" />

                <s:submit type="button" name="approve" value="approve" label="Approve" />
                <s:submit type="button" name="deny" value="deny" label="Deny" />

    </s:form>

public String execute() {
    BulletinDAO bulletinDAOInstance = new BulletinDAO();

    if ("Approve".equals(buttonName)) {
        if (bulletinDAOInstance.approveBulletin(id) == true) {
            return "redirect";
        }
    }

    if ("Deny".equals(buttonName)) {
        if (bulletinDAOInstance.denyBulletin(id) == true) {
            return "redirect";
        }
    }

    return "failure";
}

A: I think you should have 2 different actions in the "struts.xml" file for the 2 buttons.
In jsp, you can set the form action for the corresponding button through javascript.
On Jsp:
For "Approve Button" set action as "ApproveAction", for "Deny Button" set action as "DenyAction" through javascript
Sample Struts.xml
....
<action name="ApproveAction" class="com.package.YourActionClass" method="approve">
<result>/pages/Approve.jsp</result>
</action>

<action name="DenyAction" class="com.package.YourActionClass" method="deny">
<result>/pages/Deny.jsp</result>
</action>
...

In "YourActionClass", you can then write your code in two different method i.e "approve" and "deny".

A: Here is the action code of the solution I came up with.
    BulletinDAO bulletinDAOInstance = new BulletinDAO();

    if (approve != null) {
        if (bulletinDAOInstance.approveBulletin(id) == true) {
            HttpSession session = (HttpSession) request.getSession();
            session.setAttribute("confirmation",
                    "Your bulletin has been approved.");
            return "success";
        }
    }

    if (deny != null) {
        if (bulletinDAOInstance.denyBulletin(id) == true) {
            HttpSession session = (HttpSession) request.getSession();
            session.setAttribute("confirmation",
                    "Your bulletin has been denied.");
            return "success";
        }
    }

    return "failure";


text:
Q: Is casting from char * to other compatibly-aligned pointer types defined behavior in C89? Are explicit casts from char * to other pointer types fully defined behavior according to ANSI C89 if the pointer is guaranteed to meet the alignment requirements of the type you're casting to? Here's an example of what I mean:
/* process.c */
void *process(size_t elem_size, size_t cap) {
    void *arr;
    assert(cap > 5);
    arr = malloc(elem_size * cap);
    /* set id of element 5 to 0xffffff */
    *(long *)((char *)arr + elem_size*5) = 0xffffff;
    /* rest of the code omitted */
    return arr;
}

/* main.c */
struct some_struct  { long id; /* other members omitted */ };
struct other_struct { long id; /* other members omitted */ };
int main(int argc, char **argv) {
    struct some_struct *s = process(sizeof(struct some_struct), 40);
    printf("%lx\n", s[5].id);
    return 0;
}

This code compiles without warnings and works as expected on my machine but I'm not fully sure if these kinds of casts are defined behavior.
C89 draft, section 4.10.3 (Memory management functions):

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated (until the space is explicitly freed or reallocated).

C89 draft, section 3.3.4 (Cast operators):

A pointer to an object or incomplete type may be converted to a pointer to a different object type or a different incomplete type. The resulting pointer might not be valid if it is improperly aligned for the type pointed to. It is guaranteed, however, that a pointer to an object of a given alignment may be converted to a pointer to an object of the same alignment or a less strict alignment and back again; the result shall compare equal to the original pointer.

This clearly specifies what happens if you cast from struct some_struct * to char * and back to struct some_struct * but in my case the code responsible for allocation doesn't have access to the full struct definition so it can't initially specify the pointer type to be struct some_struct * so I'm not sure if the rule still applies.
If the code I posted is technically UB, is there another standards-compliant way to modify array elements without knowing their full type? Are there real-world impementations where you would expect it to do something else than ((struct some_struct *)arr)[5].id = 0xffffff;?

A:
This code compiles without warnings and works as expected on my machine but I'm not fully sure if these kinds of casts are defined behavior.

In general, the casts have defined behavior, but that behavior can be that the result is not a valid pointer.  Thus dereferencing the result of the cast may produce UB.
Considering only function process(), then, it is possible that the result of its evaluation of (long *)((char *)arr + elem_size*5) is an invalid pointer.  If and only if it is invalid, the attempt to use it to assign a value to the object it hypothetically points to produces UB.
However, main()s particular usage of that function is fine:

*

*In process(), the pointer returned by malloc and stored in arr is suitably aligned for a struct some_struct (and for any other type).

*The compiler must choose a size and layout for struct some_struct such that every element and every member of every element of an array of such structures is properly aligned.

*Arrays are composed of contiguous objects of the array's element type, without gaps (though the element types themselves may contain padding if they are structures or unions).

*Therefore, (char *)arr + n * sizeof(struct some_struct) must be suitably aligned for a struct some_struct, for any integer n such that the result points within or just past the end of the allocated region.  This computation is closely related to the computations involved in accessing an array of struct some_struct via the indexing operator.

*struct some_struct has a long as its first member, and that member must appear at offset 0 from the beginning of the struct.  Therefore, every pointer that is suitably aligned for a struct some_struct must also be suitably aligned for a long.

A: Determining whether an operation upholds or violates "type aliasing" constraints requires being able to answer two questions:

*

*For purposes of the aliasing rules, when does a region of storage hold an "object" of a particular type.

*For purposes of the aliasing rules, is a particular access performed "by" an lvalue expression of a particular type.
For your question, the second issue above is the most the relevant: if a pointer or lvalue of type T1 is used to derive a value of type T2* which is dereferenced to access storage, the access may sometimes need to be regarded for purposes of aliasing as though performed by an lvalue of type T1, and sometimes as though performed by one of type T2, but the Standard fails to offer any guidance as to which interpretation should apply when.  Constructs like yours would be processed predictably by implementation that didn't abuse the Standard as an excuse to behave nonsensically, but could be processed nonsensically by conforming but obtuse implementations that do abuse the Standard in such fashion.
The authors of C89 didn't expect anyone to care about the precise boundaries between constructs whose behavior was defined by the Standard, versus those which all implementations were expected to process identically but which the Standard didn't actually define, and thus saw no need to define the terms "object" and "by" with sufficient precision to unambiguously answer the above questions in ways that would yield defined program behavior in all sensible cases.


text:
Q: Another centering issue with a div that can change size I am trying to center align 2 items inside divs. The first input box works fine since I can hard code the width. The second, being a drop down, will change its width based on the content so I can't hard code a width. Text-align will center the label also, display:inline breaks the centering and I prefer not to have to do changes with JS, but I do realize that's an option.
http://jsfiddle.net/56cgcudb/2/

        Search
        <input type="text" name="Search" id="Search" placeholder="Search" style="width: 125px" />

        Drop Down

            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="">
                option 1

            </button>

                    Option 1 asdasdasd

                    Option 2

                    Option 3

                    Option 4

A: Here's what I do for horizontally centering content. Create a CSS class:
// Classes
.center-block {
  margin-left: auto;
  margin-right: auto;
  width: 100%; // IMPORTANT: width has to be set to something or centering will not work. You can use ems, but percentages gives you responsive sizing
}

So what about text-align? I prefer this method over a simple text-align, because this construct will center all objects in the div, not just text.
And in your code example

Or, wherever you need to center stuff in a

Updated: Center aligned content and left-aligned text
 // Classes
    .center-block-left-text {
      margin-left: auto;
      margin-right: auto;
      width: 100%;
      text-align: left !important;
    }

Here's a good official CCS reference about centering of all sorts.


text:
Q: How to add TableRow dynamically to the TableLayout I need to add TableRow which consists of several different Views dynamically to the TableLayout but have this TableRow's inflated from my layout.xml. Please advice how to do this.

A: Calling addView() on the TableLayout, passing it the TableRow and a TableLayout.LayoutParams, should work.


text:
Q: How to define schema for an ActiveRecord model? I can find how to define columns only when doing migrations.
However i do not need to migrate my model.
I want to work with it "virtually".
Does AR read columns data only from db?
Any way to define columns like in DataMapper?
class Post
  include DataMapper::Resource

  property :id,        Serial
  property :title,     String
  property :published, Boolean
end

Now i can play with my model without migrations/connections.

A: In Rails, you need not define properties on your models.  They will reflect from the database.  Just make sure that you create models for the tables that you want to use.  You will, however, need to tell ActiveRecord how to create the relations between models.  For information on creating relationships, check this out: http://guides.rubyonrails.org/association_basics.html.
If you don't use the Rails convention of id for primary keys, you can set the primary key via set_primary_key :your_key (although this is being deprecated).  If you do not follow Rails' convention for naming tables, i.e. lowercased, snake-cased, pluralized table names, you can change that via set_table_name 'your_table'.


text:
Q: Mount Unknown Type External HDD (was NTFS) I'm new to Ubuntu and came here as my i can't read my external HDD in Windows. So i've booted up my Ubuntu 15.04 install to check if it pops up within the program Disks. The strange part in this picture is it says 1.0TB Unknown as it was an NTFS formatted HDD.

So I've dug a bit deeper and opened up the terminal and executed: sudo fdisk -l
These are the results:
baklap4@baklap4:~$ sudo fdisk -l

Disk /dev/sda: 465,8 GiB, 500107862016 bytes, 976773168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 2A56DAB5-1CA5-4803-910F-483F4646AB46

Device         Start       End   Sectors   Size Type
/dev/sda1       2048    616447    614400   300M Windows recovery environment
/dev/sda2     616448    821247    204800   100M EFI System
/dev/sda3     821248   1083391    262144   128M Microsoft reserved
/dev/sda4    1083392 736312496 735229105 350,6G Microsoft basic data
/dev/sda5  736313344 737282047    968704   473M Windows recovery environment
/dev/sda6  737282048 753283071  16001024   7,6G Linux swap
/dev/sda7  753283072 792344575  39061504  18,6G Linux filesystem
/dev/sda8  792344576 976771071 184426496    88G Linux filesystem

Disk /dev/sdb: 931,5 GiB, 1000170586112 bytes, 1953458176 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xe3304215

Device     Boot      Start        End    Sectors   Size Id Type
/dev/sdb1               63 1953343349 1953343287 931,4G a2 unknown
/dev/sdb2       1953343350 1953439739      96390  47,1M a2 unknown

As you can see on /dev/sdb both the partitions are type Unknown again.
I've tried to mount sdb1 with the following command sudo mount -t ntfs /dev/sdb1 /media returning in the following error:
baklap4@baklap4:~$ sudo mount -t ntfs /dev/sdb1 /media
NTFS signature is missing.
Failed to mount '/dev/sdb1': Invalid argument
The device '/dev/sdb1' doesn't seem to have a valid NTFS.
Maybe the wrong device is used? Or the whole disk instead of a
partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?

I have some important data on this disk which i'd like to retrieve but i don't know how. Anyone who can help me?

A: Unfortunately the disk appears to be severely corrupt, you won't be able to mount it. There are possibly other methods to retrieve the data, a good start would be to use DD to make a clone of it.


text:
Q: How to apply styles to an element inside div ? i have some content inside , i want to move that to left I have below content in my HTML, i want to move it to left 100px, could someone please help me to do that.

This is some test data for which styles should be applied..

A: In the CSS, there is a classes and id's.
Classes are needed for combining some elements:

Lorem Ipsum

And in CSS:
h1.test {
margin-right:100px;
}

ID's you can assign only one element:

Lorem Ipsum

And in CSS:
h1#test {
margin-right:100px;
}

A: html:

This is some test data for which styles should be applied

CSS:
.test{
    position: absolute;
    left: -100px;
}

This will move the div off screen to the left by 100px, or to the left of the next parent element that has position: relative.


text:
Q: Как сделать чтобы карточки были в середине и было расстояние между ими Дело в том, что я нашел карточки товара в инете, ну мне их нужно повторить 5 раз и разместить в ряд, пробовал, изменял css - не помогает. Вот код с инета:

* {
  padding: 0;
  margin: 0;
}

section {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  max-width: 250px;
  margin: auto;
  text-align: center;
  font-family: sans-serif;
}

img {
  width: 100%;
}

#opis1 {
  color: #DCDCDC;
}

.price {
  color: #00FFFF;
  font-size: 20px;
}

.card button {
  border: none;
  outline: 0;
  padding: 10px;
  color: #fff;
  background-color: #FF0000;
  text-align: center;
  cursor: pointer;
  width: 100%;
  font-size: 25px;
}

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

Ну соответственно я начал изменять "класс" section. Менял по разному тег position и тд. Ну и пришел я как разместить карточки товара в ряд, только они слева, а хотелось бы чтобы между ними было растояние 30px и были они в середине. Как это починить? Если у вас есть способ (т.к. у меня возможно коряво все работает), то пишите сюда.
Ну вот и мое решение:
section {
  float: left;
  margin-right: 30px;
  top: 40%;
  right: 50%;
  transform: translate(-50%, -50%);
}

Если вам нужен скрин, могу прислать. Буду благодарен если сделаете чтобы они были в середине.

A: Простой способ использовать Grid Layout

body {background-color: #ccc;}

* {
  padding: 0;
  margin: 0;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  max-width: 250px;
  margin: auto;
  text-align: center;
  font-family: sans-serif;
}

img {
  width: 100%;
}

#opis1 {
  color: #DCDCDC;
  /* Нужный код */
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
  width: 100%;
  justify-content: center;
}

@media (max-width: 600px) {
  #opis1 {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* Нужный код */

.price {
  color: #00FFFF;
  font-size: 20px;
}

.card button {
  border: none;
  outline: 0;
  padding: 10px;
  color: #fff;
  background-color: #FF0000;
  text-align: center;
  cursor: pointer;
  width: 100%;
  font-size: 25px;
}

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

Для избежания проблем с выравниванием придётся перейти на Flexbox

body {background-color: #ccc;}

* {
  padding: 0;
  margin: 0;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  text-align: center;
  font-family: sans-serif;
}

img {
  width: 100%;
}

#opis1 {
  color: #DCDCDC;
  /* Нужный код */
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: flex-start;
  width: calc(100% + 20px);
  margin-right: -20px;
  margin-bottom: -20px;
}

#opis1 .card {
  display: block;
  width: calc((100% - 60px) / 3);
  max-width: 250px;
  margin-right: 20px;
  margin-bottom: 20px;
}

@media (max-width: 600px) {
  #opis1 .card {
    width: calc((100% - 40px) / 2);
  }
}

/* Нужный код */

.price {
  color: #00FFFF;
  font-size: 20px;
}

.card button {
  border: none;
  outline: 0;
  padding: 10px;
  color: #fff;
  background-color: #FF0000;
  text-align: center;
  cursor: pointer;
  width: 100%;
  font-size: 25px;
}

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>

        <!— Фотография -->

        <!— Название -->

Ускорение Виндовс 10

        <!— Цена -->

50 P

        <!— Описание -->

Расскажем как ускорить виндовс 10, буквально в 3 раза, за 5 минут!

        <!— Корзина -->

        <form action="mein.html" target="_blank">
          <button>Магазин</button>
        </form>


text:
Q: Contents of Div Are Displaying Wrong in Internet Explorer I'm working on designing a v3 platform for a website. We're almost done, and now were just doing the finishing touches with cross-browser texting. Everything works fine, except for IE.
I'm testing in IE 9, and when the page loads, there is supposed to be a slider at the top of the page. The slider is set up as one long block of images/desrciption text, which jQuery slides on and off the page.
The slider divs work fine, but the content of the divs is oddly block displayed on the side. So basically the content of my divs are not showing up inside my divs.
So is there any dort of bug/quirk with IE that causes this.
Example code:

  <div

CSS:
.cont {
position: relative;
display: block;
overflow: hidden;
}

.cont div{
display: block;
position: absolute;
left: 0px;
top: 0px;
width: 980px;
opacity: 1;
z-index: 5;
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}

A: So it turns out that this, among many of the problems I recently asked about, were simply caused by Internet Explorer's inability to compute more than 31 stylesheets.
So if you have more than 31 stylesheets, beware.


text:
Q: Check if Coupon exists and if it is the first order In my e-commerce I have implemented coupons, and it is working, but now I introduce "Coupons first order", but don't know if I'm doing the best way to check it, because it is not working, my query is ignoring this consult.
How I can check if coupon_tp i'ts first, and If is true, how check if user is first order?
public function verificaCupom($coupon){
    $this->db->select("customer_id, id, value, percent, code, discount_tp, coupon_tp");

//check if is first order (not working)
    $this->db->select("IF(ga845_cupons.coupon_tp = 'first', (SELECT customer_id FROM ga845_pedidos_view WHERE NOT EXISTS 'ga845_pedidos_view.customer_id = ga845_cupons.customer_id'))  as primeira");

//check if coupon exist
    $this->db->where('code', $coupon);
//check valid
    $this->db->where('CURDATE() <= valid');
//check if coupon it's enable
    $this->db->where('status', 0);
    $this->db->limit("1");

    $query = $this->db->get('ga845_cupons');

    return $query->result();
}

A: Try setting the second parameter to false in select() function.

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names. This is useful if you need a compound select statement where automatic escaping of fields may break them.

$this->db->select("IF(ga845_cupons.coupon_tp = 'first', (SELECT customer_id FROM ga845_pedidos_view WHERE NOT EXISTS 'ga845_pedidos_view.customer_id = ga845_cupons.customer_id'))  as primeira", false);

A: I have adjusted my code to this bellow, and work as I want.
$this->db->select("IF(ga845_cupons.coupon_tp = 'first', (SELECT COUNT(`customers_id`) FROM `ga845_pedidos_view` WHERE `ga845_pedidos_view`.`customers_id` = `ga845_cupons`.`customers_id` ), coupon_tp) as first");
$this->db->having('first <= ' , 0);


text:
Q: Что значит путь "\\\\.\\NTICE"? Объясните, что означает этот путь:
 "\\\\.\\NTICE"

Полностью подпрограмма для открытия файла:

A: Это проверка на наличие запущенного отладчика SoftICE. Тут делается попытка открыть файл (устройство) "\\.\NTICE" через CreateFile. Если возвращается что-нибудь, отличное от -1 (INVALID_HANDLE_VALUE), то SoftICE запущен. Если отладчик запущен, то работа вашей программы завершается.

A: Путь записан в C-нотации, если убрать экранирующие слэши, останется \\.\NTICE и обозначает путь к устройству NTICE (см. английскую документацию, раздел Win32 Device Namespaces).
Скорее всего, это устройство, которое создаётся определённым отладчиком ядра (типа SoftICE), и код проверяет наличие такого отладчика по наличию этого пути.


text:
Q: How to pass a function as an argument for a class member that the Class will use in a method to repeatedly evaluate that member? I have instances of that class calling a function defined elsewhere in the program as its member, and am trying to figure out the notation to initialize the class with a member function that can be called later.  Currently, initializing the object initializes the member to the evaluation of that function at the time of that objects instantiation.  How do I pass the function to init() in a way that the function itself is the object member, rather than the return value of the function?
Example:
class MyClass:
    def __init__(MyFunc):
        function = MyFunc()

MyFuncDef():
    #Do Something

def main():

    MyObj = MyClass(MyFuncDef())
    MyObj.function()

if __name__ == 'main':
    main()

A: The short answer is yes, you can do it by removing the () when you're passing the function.
When you write the () you're calling a function obtaining its return value, whereas, without it, you pass the function itself.
reminder_1 = MultiToast(title="Stopwatch",
                        msg=get_message,
                        icon_path=clock,
                        interval=show_interval_1,
                        count=-1,
                        runonstart=True,
                        duration=show_duration)


text:
Q: Some questions about struct namespace in C I'm trying to understand this answer - typedef struct vs struct definitions [duplicate]:

(Line 3): ["] In the first line you are defining the identifier S within the struct name space (not in the C++ sense). [."]

*

*It seems like for struct X {...};, the {...} is like an adjective for X, and X {...} is thrown into something called struct-namespace, how many struct-namespace are there in a program? Is there only one specified by struct?

*It seems like in C/C++ struct and class are almost the same? So in C++ struct and class are both in class-namespace?

A: From the C99 standard draft
6.2.3

6.2.3  Name spaces of identifiers
If  more  than  one  declaration  of  a  particular  identifier  is  visible  at  any point  in  a translation  unit,  the  syntactic  context  disambiguates  uses  that  refer  to  different  entities. Thus, there are separate namespaces
  for various categories of identifiers, as follows:
—label names
  (disambiguated by the syntax of the label declaration and use);
—the
  tags
  of  structures,  unions,  and  enumerations  (disambiguated  by  following  any
  of the keywords
  struct
  ,
  union
  ,or
  enum
  );
—the
  members
  of  structures  or  unions;  each  structure  or  union  has  a  separate  name
  space for its members (disambiguated by the type of the expression used to access the
  member via the
  .
  or
  ->
  operator);
—all other identifiers, called
  ordinary identifiers
  (declared in ordinary declarators or as
  enumeration constants).

In other words, if you have struct S, then S is in the struct namespace, whereas if you have int S as well, then it's in the namespace of ordinary identifiers.
This is not the case for C++

A: 1 (for C): there is one namespace for all structure tags. You can have as many different tags as you want, even if the same name is used in other namespaces.
Each structure on its own is its own namespace (there are "infinite" struct namespaces).
// You can have
struct foo { int var; }
struct bar { double var; }
struct baz { int var; }
struct qux { int var; }
// with no conflict between all the `var`


text:
Q: Recuperar Milissegundos de uma data gravada em um BD MSSQL Server 2019 com VB.Net + ADO.Net Gostaria de saber como recuperar uma data como dado dos Milissegundos gravados em um Banco de Dados MS SQL Server 2019 usando o VB.Net + ADO.Net.
Sempre que tento resgatar a data, vem no fomrmato "dd/MM/yyyy HH:mm:ss" eu gostaria de também ter os ".fff", mas não consigo recuperar esta informação no BD.

*** código do MODEL:
Private _DataAlteracao As DateTime

Public Property DataAlteracao() As DateTime
    Get
        Return _DataAlteracao
    End Get
    Set(ByVal value As DateTime)
        _DataAlteracao = value
    End Set
End Property

*** Código do INSERT:
Public Overloads Function InserirHistorico(entidade As ClsHistoricoDomain) As Object
    Dim objConfirma As Object

    MyBase.LimparStrComando()

    MyBase.StrComando.AppendLine(" INSERT INTO tblHistorico (")
    MyBase.StrComando.AppendLine(" CNPJ, ")
    MyBase.StrComando.AppendLine(" RazaoSocial, ")
    MyBase.StrComando.AppendLine(" NomeFantasia, ")
    MyBase.StrComando.AppendLine(" CodigoSistema, ")
    MyBase.StrComando.AppendLine(" DataAlteracao) ")
    MyBase.StrComando.AppendLine(" VALUES (")
    MyBase.StrComando.Append(IIf(Not String.IsNullOrEmpty(entidade.CNPJ), String.Format("'{0}',{1}", entidade.CNPJ, Environment.NewLine), "NULL,"))
    MyBase.StrComando.Append(IIf(Not String.IsNullOrEmpty(entidade.RazaoSocial), String.Format("'{0}',{1}", entidade.RazaoSocial, Environment.NewLine), "NULL,"))
    MyBase.StrComando.Append(IIf(Not String.IsNullOrEmpty(entidade.NomeFantasia), String.Format("'{0}',{1}", entidade.NomeFantasia, Environment.NewLine), "NULL,"))
    MyBase.StrComando.Append(IIf(Not String.IsNullOrEmpty(entidade.CodigoSistema), String.Format("'{0}',{1}", entidade.CodigoSistema, Environment.NewLine), "NULL,"))
    MyBase.StrComando.Append(IIf(Not String.IsNullOrEmpty(entidade.DataAlteracao), String.Format("'{0}',{1}", entidade.DataAlteracao, Environment.NewLine), "NULL,"))
    MyBase.StrComando.AppendLine(")")

    objConfirma = SQLHelper.ExecuteScalar(StrComando.Remove(StrComando.ToString.LastIndexOf(","), 1).ToString(), True)

    Return objConfirma
End Function

*** Código do SELECT TODOS:
Public Overrides Function SelecionarTodos() As List(Of ClsHistoricoDomain)
    MyBase.LimparStrComando()

    MyBase.StrComando.AppendLine(" SELECT CNPJ, ")
    MyBase.StrComando.AppendLine(" RazaoSocial, ")
    MyBase.StrComando.AppendLine(" NomeFantasia, ")
    MyBase.StrComando.AppendLine(" CodigoSistema, ")
    MyBase.StrComando.AppendLine(" DataAlteracao ")
    MyBase.StrComando.AppendLine(" FROM tblHistorico ")

    Return MyBase.RetornaLista(StrComando.ToString())
End Function

A: O problema é que montei na 'tblHistorico' uma chave primária composta por dois campos: "CodigoSistema" + "DataAlteracao".
(talvez ajude alguma pessoa)
O melhor que consegui foi fazer o seguinte:
*** Chamada da função para testar
Dim strTeste As String

strTeste = GerenciadorBll.Instance.HistoricoBLL.RetornaCodigoHistorico("1", "18-01-2021 15:14:41.897")
mskDataAlteracao.Text = strTeste

*** BLL
Public Function RetornaCodigoHistorico(Codigo As String, DataHistorico As String) As String
    Return GerenciadorDal.Instance.HistoricoDal.RetornaCodigoHistorico(Codigo, DataHistorico)
End Function

*** DAL
Public Function RetornaCodigoHistorico(ByVal codigoHistorico As String, ByVal dataHistorico As String) As String
    MyBase.LimparStrComando()

    MyBase.StrComando.AppendLine(" SELECT ")
    MyBase.StrComando.AppendLine(" DataAlteracao ")
    MyBase.StrComando.AppendLine(" FROM tblHistorico ")
    MyBase.StrComando.AppendLine(String.Format(" WHERE codigoSistema = '{0}' ", codigoHistorico))
    MyBase.StrComando.AppendFormat(" AND DataAlteracao = '{0}' ", dataHistorico)

    Return MyBase.RetornaDataHistorico(StrComando.ToString())
End Function

*** BASE DAL
Protected Function RetornaDataHistorico(ByVal pCommantText As String) As String
    Dim milliSeconds As Int32
    Dim dt As DateTime
    Dim strTempo As String

    Using dataReader As System.Data.SqlClient.SqlDataReader = SQLHelper.ExecuteReader(pCommantText)

        If dataReader.HasRows Then
            dataReader.Read()

            dt = dataReader.GetValue(dataReader.GetOrdinal("DataAlteracao"))
            milliSeconds = dt.Millisecond

            strTempo = dt.ToString() + "." + milliSeconds.ToString()
        Else
            Return Now()
        End If

        Return strTempo
    End Using

End Function

Agora ficou um erro quando eu quero um SELECT ALL para preencher um grid...
*** UI - User Interface
Private Sub PreencheGrid(Optional ByVal cod1 As String = Nothing, Optional ByVal cod2 As String = Nothing)

    DgvPadrao.DataSource = Nothing
    DgvPadrao.DataSource = GerenciadorBll.Instance.HistoricoBLL.SelecionarTodos

    If DgvPadrao.Rows.Count > 0 Then

...
*** BLL
Public Function SelecionarTodos() As List(Of ClsHistoricoDomain) Implements ICrud(Of ClsHistoricoDomain, String).SelecionarTodos
    Return GerenciadorDal.Instance.HistoricoDal.SelecionarTodos()
End Function

*** DAL
Public Overrides Function SelecionarTodos() As List(Of ClsHistoricoDomain)
    MyBase.LimparStrComando()

    MyBase.StrComando.AppendLine(" SELECT CNPJ, ")
    MyBase.StrComando.AppendLine(" RazaoSocial, ")
    MyBase.StrComando.AppendLine(" NomeFantasia, ")
    MyBase.StrComando.AppendLine(" CodigoSistema, ")
    MyBase.StrComando.AppendLine(" DataAlteracao ")
    MyBase.StrComando.AppendLine(" FROM tblHistorico ")

    Return MyBase.RetornaLista2(StrComando.ToString())
End Function

** BASE DAL
Protected Function RetornaLista2(ByVal commandText As String, Optional ByVal isSql As Boolean = True) As List(Of ClsHistoricoDomain)

    Dim listaRetorno As List(Of ClsHistoricoDomain) = Nothing

    Try

        If isSql Then
            Using dataReader As System.Data.SqlClient.SqlDataReader = SQLHelper.ExecuteReader(commandText)
                If dataReader.HasRows Then
                    listaRetorno = New List(Of ClsHistoricoDomain)()
                    While dataReader.Read()
                        Dim objeto As ClsHistoricoDomain
                        objeto = Activator.CreateInstance(GetType(ClsHistoricoDomain), dataReader)

                        listaRetorno.Add(objeto)
                    End While
                End If
            End Using
        End If

        Return listaRetorno

    Catch ex As Exception
        Return Nothing
    End Try

End Function

O SELECT ALL JÁ RETORNA TODAS AS DATAS SEM MILISEGUNDOS!!!
Como na tabela 'tblHistorico' minha chave primária é composta por 'CodigoSistema' + 'DataAlteracao' então eu me ferro, pois retorna vários registros com a informação da Chave Primária Composta INCOMPLETA...
... acho que terei que mudar TODA a lógica de fazer histórico do sistema.... NÃO pode ser uma chave composta com uma data que depende de milissegundos... terá que ser um autonumber ou algo parecido...
... que péssimo, por causa de um erro no código do VB.Net que NÃO retorna os milissegundos em uma busca eu terei que mudar totalmente a minha ideia.


text:
Q: How to log out Keras custom loss component at the end of an epoch? I have a custom loss function as this format:
def CustomLoss(y_true,y_pred):
    ......
    loss = loss1 + loss2 + loss3
    return loss

How can I return each loss component (loss1, loss2, loss3) at the end of an epoch? By default, I can only observe loss.
Normally, if we have multiple outputs, keras can show it easily. But how to show the value component like what I am mentioned?

A: You need to create a function for each loss separately and pass them them into metrics when compiling the model as shown below
def CustomLoss():
    ......
    return loss1() + loss2() + loss3()

def Loss1():
    ......
    return value1

def Loss2():
    ......
    return value2

def Loss3():
    ......
    return value3

model.compile(optimizer=Adam(),
                       loss=CustomLoss,
                       metrics=[Loss1, Loss2, Loss3])


text:
Q: For which class $H$ of functions is $H\ni x\mapsto\int_0^Tf(t,x(t))\:{\rm d}t$ differentiable? Let $T>0$, $X,Y$ be Banach spaces, $f:[0,T]\times X\to Y$ be Fréchet differentiable in the second argument and such that ${\rm D}_2f$ is (jointly) continuous, $H$ be a subspace of all Borel measurable functions $[0,T]\to X$ and $$g(x):=\int_0^Tf(t,x(t))\:{\rm d}t\;\;\;\text{for }x\in H.$$

I would like to know for which choice of $H$ the function $g$ is well-defined and Fréchet differentiable.

I'm mostly interested in the choice $H=C([0,T],X)$, $H=C^1([0,T],X)$ and $H=\mathcal L^p([0,T],X)$, $p\ge1$.
But I really to struggle to check the desired claim. If it exists, the Fréchet derivative of $g$ at $x\in H$ should be given by $$Ah:=\int_0^T{\rm D}_2f(t,x(t))h(t)\;{\rm d}t\;\;\;\text{for }h\in H.$$
(Maybe we need to impose a linear growth assumption on $f$ to ensure that the integrals are well-defined.)


text:
Q: Foursquare SDK for .net may i know is there any foursquare sdk for .NET C#.
I am doing based on the developer reference but i failed to do it during request for token, i keep on getting the error.
I am using VS 2008 and under development server. I search before this error because of url rewriting, but i'm not hosted in IIS and i also have check the web.config, no luck also. Please help, thanks.
This is my error:
The HTTP verb POST used to access path '/login' is not allowed.
This is my implementation:
        HttpWebRequest request = null;

        HttpWebResponse response = null;

        StreamReader responseStream = null;

        ASCIIEncoding ascii = null;
        string key = ConfigurationManager.AppSettings["key"];
        string secret = ConfigurationManager.AppSettings["secret"];
        string callback = ConfigurationManager.AppSettings["callback"];

        string obtainTokenUrl = ConfigurationManager.AppSettings["obtainTokenUrl"];

        try
        {
            string postData = "client_id=" + key + "&response_type=code&redirect_uri=" + callback;

            ascii = new ASCIIEncoding();
            byte[] postBytes = ascii.GetBytes(postData);

            try
            {
                request = WebRequest.Create(obtainTokenUrl) as HttpWebRequest;
            }
            catch (UriFormatException)
            {
                request = null;
            }

            if (request == null)
            {
                throw new ApplicationException("Invalid URL: " + obtainTokenUrl);
            }

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;

            //add post data to request
            Stream postStream = request.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            response = (HttpWebResponse)request.GetResponse();
            Encoding encode = Encoding.GetEncoding("utf-8");
            responseStream = new StreamReader(response.GetResponseStream(), encode);

            Response.Write(responseStream.ReadToEnd());

A: Well, this may be a roundabout sort of answer. But maybe you could check out the open source 4square app for windows phone 7:
http://4square.codeplex.com/
Since you can look at the source code, you can see how they are interfacing with the 4sq API :-)

A: SharpSquare - FourSquare SDK for .NET http://www.igloolab.com/sharpsquare/


text:
Q: angular-phonecat tutorial - web-server.js giving 404 errors with node.js Hi there I'm running through the angular phonecat tutorial but I'm stuck already on step-0 with the node.js http server returning 404's for /app/index.html
I do have other http servers installed on this box (Win7 Pro), but they aren't even running and I don't think I installed any of these as services either.
Where should I start looking to debug?
Here's the output so far:
C:\Users\S>node C:\Users\S\angular-phonecat\scripts\web-server.js
Http Server running at http://localhost:8000/
GET /app/index.html Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1636.2 Safari/537.36
404 Not Found: /app/index.html
GET /favicon.ico Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1636.2 Safari/537.36
404 Not Found: /favicon.ico
GET /app/index.html Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1636.2 Safari/537.36
404 Not Found: /app/index.html

A: Open the command prompt and execute the node scripts/web-server.js with administrator access.

A: The answer was fairly simple.  If you take a look at the instructions (windows users) at the end of the first page it says to only run executables from the windows command prompt, so on the next page where it says
"In a separate terminal tab or window, run node scripts\web-server.js to start the web server."
what they're really referring to is another Git Bash window that I'm guessing you'll need to leave running in the background for testing.
This is what your output should look like when you've successfully started the server:
user@windows-pc-name ~/angular-phonecat ((step-0))
$ node scripts/web-server.js
Http Server running at http://localhost:8000/
GET /app/ Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1636.2 Safari/537.36

A: After starting web sever with scripts\web-server.js command, open new browser window and give full path for "app/index.html" in that.
For example, If I have located angular-phonecat-master app in my Desktop directory then in browser window I will have to give following path:
localhost:8000/Desktop/angular-phonecat-master/angular-phonecat-master/app/index.html


text:
Q: How do I fix my VNC setup? I am using Real VNC Viewer on Mac OSX 10.6 and Tight VNC Server on Windows XP.
This setup was working.  I have not changed any settings to cause it not to work.  But now I am not receiving screen updates to the VNC viewer.  If I am controlling my Server from my Viewer in the same room.  I can see that I am moving the mouse and sending mouse-clicks.  But I am not receiving screen updates to the Viewer.
I have a VNC viewer on my iPhone.  If I use it to connect to my Server, it works fine.  So I figure the problem is with my VNC Viewer.  I have tried uninstalling it and reinstalling it but to no avail.  I do not know if there are any preferences that are being saved even with the uninstall?
Any ideas or points in the right direction.

A: Why not test with the VNC viewer that is build into the Mac OS X?
Try --> Connect to Server --> vnc://IP ADDRESS
Now, I don't use it to connect to VNC, but to other Macintoshes, but I suspect that it will work with normal VNC servers...


text:
Q: What are the possible solutions of $x+y+ {1\over x}+{1\over y}+4=2 (\sqrt {2x+1}+\sqrt {2y+1})$? I encountered a question in an exam in which we had:

Find all possible solutions of the equation $$x+y+ {1\over x}+{1\over y}+4=2 (\sqrt {2x+1}+\sqrt {2y+1}) $$ where $x $ and $y$ are real numbers.

I tried squaring both sides to eliminate the square roots but the number of terms became too many, making the problem very difficult to handle. I am not really able to understand how to find an easier approach or handle the terms efficiently. Would someone please help me to solve this question?

A: It's $$\sum_{cyc}\left(x+\frac{1}{x}+2-2\sqrt{2x+1}\right)=0$$ or
$$\sum_{cyc}\frac{x^2-2x\sqrt{2x+1}+2x+1}{x}=0$$ or
$$\sum_{cyc}\frac{(x-\sqrt{2x+1})^2}{x}=0,$$
which for $xy<0$ gives infinitely many solutions.
But, for $xy>0$ we obtain:
$$x=\sqrt{2x+1}$$ and $$y=\sqrt{2y+1},$$ which gives
$$x=y=1+\sqrt2.$$

A: This solution works only for positive $x,y$. However they can not be both negative since then LHS is at most $0$. So $$x+y+ {1\over x}+{1\over y}+4 = x+y+{2x+1\over x}+{2y+1\over y} $$
By Am-Gm we have $$ x+{2x+1\over x}\geq 2\sqrt{x{2x+1\over x}} = 2\sqrt{2x+1}$$ and the same for $y$, so we have
$$x+y+ {1\over x}+{1\over y}+4  \geq 2\sqrt{{2x+1}}+2\sqrt{{2y+1}}$$
Since we have equality is achieved when $x={2x+1\over x}$ (and the same for $y$) we have $x=y=1+\sqrt{2}$


text:
Q: Unexpected C++ behaviour in the following program I came across some dodgy code recently. But the behavior left me a bit dumbfounded. The following is a simplification of the problem (basically the virtual keyword is missing, making it non-polymorphic). Why/how is it printing "C::foo called, i: 5"?
How is the object in memory even able to have 'i' in it? I tried C++03 and C++11.
#include <iostream>
using namespace std;

class P
{
public:
    void foo()
    {
        cout << "P::foo called" << endl;
    }
};

class C : public P
{
public:
    void foo()
    {
        i = 5;
        cout << "C::foo called, i: " << i << endl;
    }

    int i;
};

int main()
{
    C* c = static_cast<C*>(new P());
    c->foo();
}

A: "Why/how is it printing "C::foo called, i: 5"?"
In static_casting the P pointer to a C pointer you're saying to the complier interpret this bit of memory as if it contained an object of class C
So when you call foo on that it looks up Cs version of foo.
(That explains the C:foo called... but not how i is 5)
"How is the object in memory even able to have 'i' in it"
In a way it doesn't. Having been told that this memory contains a C, the complier then "knows" that i lives at a certain memory offset from the objects this pointer. That memory hasn't been allocated especially to contain an i member for an object of type C (no objects of C have been created) but having been told (wrongly) that the memory does contain a C, it'll use that address as i, and, because you set it in foo before you output it, that misappropriated address will end up containing 5.
If you don't set i in foo, but you initialise it when its declared instead, you'd see that a real C object outputs the value you set it to, but that a P* cast as a C* outputs whatever happens to be at that address.

A: That's exactly the expected behaviour, nothing strange with it.
"Notes
static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type"
http://en.cppreference.com/w/cpp/language/static_cast

I'm not able yo verify right now, but in an instance of a child object you should be able to specify which of the two "foo" you want to call by specifying the namespace. Not sure about that when a static cast occurs though.
void C::foo()
{
  if (/*something*/)
     // do something
  else
     D::foo();
}

A: After much research the conclusion: "undefined behaviour"
Here is the rule for downcasting using static_cast, found in section 5.2.9 ([expr.static.cast]) of the C++ standard (C++0x wording):

A prvalue of type "pointer to cv1 B", where B is a class type, can be converted to a prvalue of type "pointer to cv2 D", where D is a class derived from B, if a valid standard conversion from "pointer to D" to "pointer to B" exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B
  is neither a virtual base class of D nor a base class of a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type "pointer to cv1 B" points
  to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object
  of type D. Otherwise, the result of the cast is undefined.

ref:- Downcasting using the 'static_cast' in C++


text:
Q: App keeps coming into foreground even after closing from task manager, how to close manually? Hello I am adding sound playing functionality into my app and I've decided to use react-native-track-player I have successfully installed it and I am following the examples. Whenever I play a sound clip, I see the "play" icon at the very top of the status bar and a compact notification appears. The clip plays fine and I can place the app in the background. The issue is whenever I try to close the app via the task manager (square button). Ill see the play icon disappear for a couple of seconds but then my app restarts and comes into the foreground again.
I am not really familiar with the Android APIs therefore I am unable to dive into the native code. So what I would like to do is listen for when the app is close (closed from the task manager, not suspended) and then stop and destroy the player manually to close the app.
Here are the relevant packages
"react-native-track-player": "github:react-native-kit/react-native-track-player#dev",
"react-native": "0.51.0",
"react-native-navigation": "^1.1.334",

A: Alright my issue stemed from the fact that the background service my app was starting was not stopping when the app stopped. How I solved this was to modify the AndroidManifest.xml of the third party service. I added the android:stopWithTask="true attribute to the service tag. Now its declaration look like this.
<!-- The service for the headless tasks in which events can be received by the JS side -->
    <service android:name=".logic.services.PlayerTask" android:stopWithTask="true" android:enabled="true" />
Hope to be someones beacon of light in the future. Thanks


text:
Q: Select with fields to include in detail table with EF Core How can I select whitch fields should be included for detail table in EF Core.
I tried with this query:
    var result= this.context.MainTable
        .Include(t => t.DetailTable)
        .Select(t => new {
            id = t.Id,
            values = t.DetailTable.Select(t2 => t2.SomeField)
        })
        .ToArray();

I would expect this result to single query, but it does not. It automatically execute query one by one for every row in MainTable and select SomeField.


text:
Q: Find $q$ and $r$ with $0\leq r\leq |b|$, such that $a=qb+r$
Find $q$ and $r$, with $0\leq r\leq |b|$, such that $a=qb+r$ for

*

*$a=115,\ b=26$

*$a=400,\ b=-17$

*$a=-312,\ b=-64$

Sadly I missed the class where the prof went over this, so I have no idea what to do. Can somebody point me in the direction of the name of a process or theorem or something so that I can find out how to do it?
Thanks..

A: You should have dealt with the case when $a \ge 0$ and $b > 0$ in school.
When $a < 0$ and $b > 0$ divide first $-a$ by $b$
$$
-a = b q + r, \qquad 0 \le r < b,
$$
then consider
$$
a = b (-q) -r
$$
If $r = 0$, then you're done. If $0 < r < b$, then
$$
a = b (-q -1) + b - r, \qquad 0 < b - r < b.
$$
Finally, if $b < 0$, divide $a$ by $-b$
$$
a = (-b) q + r = b (-q) + r, \qquad 0 \le r < -b = \vert b \rvert,
$$
done.

A: Hint:
If $(q_0,r_0)$ is the solution to $a=qb+r$ then $(q_0-k,r_0)$ is the solution to $a-kb = qb+r$. In fact $q = \frac{a-r}{b}$ and because $0\leq r < |b|$ we have $0\leq\left|\frac{a}{b}-q\right|<1$.
Good luck ;-)


text:
Q: Writing code to update a large matrix? How can I write a code to update a matrix based on certain rules? I plan on constructing a large matrix, and I cannot submit entries one by one.
The rules for the matrix are as followed:
$$
 P(i,j)=
\begin{cases}
p,  & \text{if $j$ = $2i$}\land m \\
q, & \text{if $j$ = $(2i-m)$ }\lor 0
\end{cases}
$$
P is square. I was thinking of just defining it to be a 0 matrix first, then updating the values with whatever code. However, I can't seem to think of how that would be done. I've never heard of updating a matrix. For a given $m$, how would one generate such matrix in Mathematica? Could someone list an example?

A: m = 5;
sa = SparseArray[{{i_, j_} /; j == Min[2 i, m] :>
    p, {i_, j_} /; j == 2 i - m :> q}, {m, m}]

mat = Partition[Range[m^2], m];
sa2 = SparseArray[{{i_, j_} /; j == Min[2 i, m] :> p,
    {i_, j_} /; j == 2 i - m, 0] :> q,
    {i_, j_} :> mat[[i, j]]}, {m, m}];
Row[MatrixForm /@ {mat, sa2}]

A: There's no need to update values; you can use Table and create it in one pass.
m = 4;
Table[
    Which[
        j == 2 i && j == m, p,
        j == 2 i - m || j == 0, q,
        True, 0
    ], {i, 10}, {j, 10}] // MatrixForm

A: Updating an existing matrix
randomP = RandomInteger[{0, 9}, {5, 5}];

m = 2

ReplacePart[randomP, {{i_, j_} /; And[j == 2 i, j == m] -> p,
                      {i_, j_} /; Or[j == 2 i - m, j == 0] -> q}]


text:
Q: singleton, static or interface as constants fields? I need final fields as my app config constants.
I know 3 different ways but I don't know which one is the best and and what is JVM behavior in this cases (in the perspective of memory managment and memory issues)
1. using static fields
public class Constants {
    public static final String URL = "https://www.google.com";
}
//usage
Constants.URL

2. using Interfaces
public interface Constants {
    String URL = "https://www.google.com";
}
//usage
Constants.URL

3. using singleton design pattern ( non-static )
public class Constants {
    public final String URL = "https://www.google.com";
}
//usage
public static Constants instance = new Constants();
Constants.instance.URL;

A: None of them, use and enum type. Keep in mind the second option is really undesirable, because the most important point of interfaces is that you are defining a new type.
By the way, enums are singletons (and you can use them like that) and indeed thread-safe by default.
For example:
public enum ApplicationStatus {
    LIVE("live"),
    MOCKS("mocks");

    private final String status;

    ApplicationStatus(final String status) {
        this.status = status;
    }

    public String value() { return status; }
}

And that should apply to really really global messages/constants/etc for the whole application.


text:
Q: Use inline SVG as favicon <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/svg+xml" sizes="21x21" href="favicon16.svg">
    <title>Document</title>
</head>
<body>
    <svg width="100" height="100">
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   </svg>
</body>
</html>

Am only having a single page HTML with, javascript is inline, I want to create a favicon and use it inside the HTML. any help, please.

A: It can be dataURL, and doesn't need to use base64. You only need to exchange "#" with "%23", place all in one line, and be carefull with quotes, of course. My search-engines page favicon:
<link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='.8 .8 14.4 14.4'><path d='M10 8.99a1 1 0 00-.695 1.717l4.004 4a1 1 0 101.414-1.414l-4.004-4A1 1 0 0010 8.99z' fill='%2380b0ff' stroke='%235D7FDDaa' stroke-width='.3'/><path d='M6.508 1C3.48 1 1.002 3.474 1.002 6.5S3.48 12 6.508 12s5.504-2.474 5.504-5.5S9.536 1 6.508 1zm0 2a3.486 3.486 0 013.504 3.5c0 1.944-1.556 3.5-3.504 3.5a3.488 3.488 0 01-3.506-3.5C3.002 4.556 4.56 3 6.508 3z' fill='%2380b0ff' stroke='%235D7FDDaa' stroke-width='.3'/></svg>">

But the proper way it should be:
<link rel="shortcut icon" href="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='.8%20.8%2014.4%2014.4'%3e%3cpath%20d='M10%208.99a1%201%200%2000-.695%201.717l4.004%204a1%201%200%20101.414-1.414l-4.004-4A1%201%200%200010%208.99z'%20fill='%2380b0ff'%20stroke='%235D7FDDaa'%20stroke-width='.3'/%3e%3cpath%20d='M6.508%201C3.48%201%201.002%203.474%201.002%206.5S3.48%2012%206.508%2012s5.504-2.474%205.504-5.5S9.536%201%206.508%201zm0%202a3.486%203.486%200%20013.504%203.5c0%201.944-1.556%203.5-3.504%203.5a3.488%203.488%200%2001-3.506-3.5C3.002%204.556%204.56%203%206.508%203z'%20fill='%2380b0ff'%20stroke='%235D7FDDaa'%20stroke-width='.3'/%3e%3c/svg%3e">

...so the link from Jeremie can be useful.

A: *

*You can encode your SVG with this tool
https://yoksel.github.io/url-encoder/

*Add the encoded SVG in this markup

<link rel="icon" href="data:image/svg+xml,[YOUR ENCODED SVG HERE]" type="image/svg+xml" />

A: Favicon need to be an external file, or an [DataURL][1], you can use SVG, but it needs to be saved as a standalone file, and pointed into the href like "favicon16.svg". Or converted to base64 and inserted as DataURL Read more
But if you are trying to create custom favicon on-the-fly using SVG, I recommend you use this approach: SVG to Base64, using base64 as favicon and how to change favicon dynamically


text:
Q: RegularExpression RegExp.test I want to match a string with following regular expression -
^\d{4}-\d{5}$|^\d{4}-\d{6}$

which is regex for a zip code with 4 digits-then 5 OR 6 digits after dash.
I am hoping my regex is correct as I have tested it on some online RegEx tester.
and for matching my string with above regex in jquery, I am using:
var regExpTest = new RegExp("^\d{4}-\d{5}$|^\d{4}-\d{6}$");
alert(regExpTest.test("1234-123456"));

But I am always getting false, can anyone please guide what is going wrong here?
Thank you!

A: Because the regular expression constructor takes a string as its argument, you need to escape the backslash \ wherever you use it.  In your example, anywhere you have a \d needs to be \\d.  You can see what happens if you don't by testing your code in Firebug or Chrome's developer tools:
new RegExp("^\d{4}-\d{5}$|^\d{4}-\d{6}$");
//-> /^d{4}-d{5}$|^d{4}-d{6}$/

Notice the slashes are gone?  Now watch what happens when we escape each backslash:
new RegExp("^\\d{4}-\\d{5}$|^\\d{4}-\\d{6}$");
//-> /^\d{4}-\d{5}$|^\d{4}-\d{6}$/

So that should fix your problem.  However, it's much easier to use the literal grammar for regular expressions when you're not using a variable to create them:
var regExpTest = /^\d{4}-\d{5}$|^\d{4}-\d{6}$/;
alert(regExpTest.test("1234-123456"));
//-> "true"

This way, you can write the expression without having to worry about double-escaping.