text:
Q: Data from Core Data won't show up in the Table Cell (using FetchResultsController) I have a subclass of a TableViewController (favTable), a prototype custom cell (favCell) with two text labels designed in storyboard and a core data model (DataModel) with one entity (FavoritesInfo) and two attributes (name, score). I have also created a subclass of NSManagedObject (FavoritesInfo). When I run the app the cells appear with no content at all.
I have been reading several different tutorials and combining different methods. There must be some mess with that. I can't figure out though how to show the cells content. Any help is appreciated.
favTable.h
#import <UIKit/UIKit.h>
#import "favCell.h"

@interface favTable : UITableViewController  <NSFetchedResultsControllerDelegate>
{
    NSFetchedResultsController *fetchedResultsController;
   NSManagedObjectContext *managedObjectContext;

}

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

@end

favTable.m
#import "favTable.h"
#import "ecoAppDelegate.h"
#import "favCell.h"
#import "FavoritesInfo.h"

@interface favTable ()

@end

@implementation favTable

@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;

- (NSFetchedResultsController *)fetchedResultsController {
    if (!_fetchedResultsController) {

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription
                                       entityForName:@"FavoritesInfo" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];

        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];

        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

        [fetchRequest setFetchBatchSize:20];

        NSFetchedResultsController *theFetchedResultsController =
        [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                            managedObjectContext:managedObjectContext sectionNameKeyPath:nil
                                                       cacheName:@"Root"];
        _fetchedResultsController = theFetchedResultsController;
        _fetchedResultsController.delegate = self;
    }

    return _fetchedResultsController;

}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Favorites";

    self.navigationController.navigationBar.translucent = NO;

    self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"FavoritesInfo" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    fetchRequest.resultType = NSDictionaryResultType;

    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"name", nil]];

    NSError *error;
    if (![[self fetchedResultsController] performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }

}

- (void)viewDidUnload
{

    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

    self.fetchedResultsController = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
//    return [favName count];

    id  sectionInfo =
    [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"favCell";

    favCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[favCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...

   [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

- (void)configureCell:(favCell *)cell
          atIndexPath:(NSIndexPath *)indexPath
{

    FavoritesInfo*favoritesInfo = [self.fetchedResultsController objectAtIndexPath:indexPath];

    cell.cellname.text = favoritesInfo.name;
    cell.cellscore.text = favoritesInfo.score;

    }

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [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:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath]
                    atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

@end

A: The problem is that you are using a very old code style and it is confusing you and causing this problem.
First, remove the iVars.
Your .h file should be...
@interface favTable : UITableViewController

@end

Yes, it really should have nothing in it. No other files need to access the properties so don't put them in here.
The .m file should be like this...
//the imports here...

@interface favTable () // the delegate and datasource come for free as a subclass of UITableViewController. Don't add them again.

// no ivars

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;

@end

@implementation favTable

// don't use @synthesize it is done automatically.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Favorites";

    self.navigationController.navigationBar.translucent = NO;

    self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;

    NSError *error;

    // use dot syntax for accessing properties.
    // self.fetchedResultsController
    // not
    // [self fetchedResultsController]

    if (![self.fetchedResultsController performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }
}

- (NSFetchedResultsController *)fetchedResultsController
{
    // user the _propertyName in the getter and setter only **ish**.

    if (_fetchedResultsController) {
        return _fetchedResultsController
    }

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"FavoritesInfo"];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];

    [fetchRequest setSortDescriptors:@[sort]]; // new syntax, use it!

    [fetchRequest setFetchBatchSize:20];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:managedObjectContext sectionNameKeyPath:nil
                                                   cacheName:nil];

    _fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // now there's your problem
    // in here you were using `fetchedResultsController`. This is why you need to
    // drop the old style.
    // Because of your ivars fetchedResultsController != self.fetchedResultsController
    // or _fetchedResultsController

    id  sectionInfo =
    [self.fetchedResultsController sections][section]; // new syntax, use it!
    return [sectionInfo numberOfObjects];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"favCell";

    favCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[favCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
   [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

- (void)configureCell:(favCell *)cell
          atIndexPath:(NSIndexPath *)indexPath
{
    FavoritesInfo*favoritesInfo = [self.fetchedResultsController objectAtIndexPath:indexPath];

    cell.cellname.text = favoritesInfo.name;
    cell.cellscore.text = favoritesInfo.score;
}

// all the FRC stuff here...

@end

There are a lot of updates in this. Most of them just updating syntax to modern Objective-C (which is now over 2 years old).
You REALLY NEED to update your syntax usage. It is the combination of old and new syntax which has caused this problem in the first place.


text:
Q: How do the two sides of the Schrodinger equation match? This is the form of the Schrodinger equation given by Wikipedia.
$$i\hbar\frac{\partial}{\partial{t}}|\Psi(t)\rangle=\hat{H}|\Psi(t)\rangle$$
My question is a simple one, but difficult for me to understand the answer to. To what space does each side of the equation belong? The left hand side is a constant scalar factor times the time derivative of a column vector, so it belongs to the same space as the vector. The right hand side is the Hamiltonian operator applied to a column vector, which yields energy, a scalar. I must be misunderstanding one of these two expressions since, in my interpretation, they belong to different spaces and are completely incomparable.

A: $|\Psi\rangle$ is not a vector in the usual sense. It is a vector if viewed as a solution in the vector space of all solutions, or in physicists' words, a quantum state.
For an anology, we can say all polynomials $\mathbb R[x]$ over $\mathbb R$ is a vector space, with basis $1,x,x^2,\cdots$. Then any polynomial $p(x)$ is a vector in the sense you view it as an element in $\mathbb R[x]$. On the other hand, you can still put it into an equation (assuming $x\in\mathbb{R}$)
$$\frac{dp}{dx}=2x$$
in which case $p(x)$ is just a real variable depending on another real variable $x$.
So in the Schrodinger's equation, instead of thinking of $|\Psi\rangle$ as a vector, you should think of it as a complex variable depending on time and the space coordinates, so both sides are simply complex variables.
p.s. even so the RHS is not the energy.

Reply to the comment (too long to put in the comment):
I am not saying it is not a vector. I am saying it is simultaneously a vector and a complex variable. Let me start from the beginning.
WHAT IS THIS "VECTOR" WE ARE TALKING ABOUT
First, when you mention vector, you need to be sure of what vector space you are referring to. If you have seen some examples of solving Schrodinger's equation, say, the infinite well problem, you'll know by separating the space and time variables $\Psi(x,y,z,t)=\Phi(x,y,z)\psi(t)$one can derive from the time-dependent equation a time-independent one:
$$\hat H\Phi=E\Phi$$
where $E$ is a constant. Usually the equation has a system of time-independent solutions $\Phi_n(r)$ ($r=(x,y,z)$), called the eigenfunctions (also eigenvectors, but I'd like to avoid the word "vector" for now), which satisfy
$$\hat H\Phi_n=E_n\Phi_n$$
where $E_n$ are called the eigenvalues. All other solutions has the form
$$\Psi(r,t)=\sum_n c_ne^{-iE_nt/\hbar}\Phi_n(r)$$
To make a solution normalizable, one must impose the condition
$$\int_{\rm all\ space}\bar\Psi\Psi dV<\infty\iff\sum_n|c_n|<\infty$$
Now comes the crucial part: what is the vector space we keep talking about? It is the vector space of all solutions! In the case above, it is
$$S=\left\{\sum_n c_ne^{-iE_nt/\hbar}\Phi_n(r):\ \sum_n|c_n|<\infty\right\}$$
One can verify that this is a vector space, and has an inner product
$$<f,g>=\int(\bar fg)dV$$
on it, under which $e^{-iE_nt/\hbar}\Phi_n$ is a system of orthogonal basis of $S$.
SUMMARY:
So there's no problem saying that $\Psi$ is a vector, as long as you see it as one. But you have to distinguish between the two explanations below:
(1) $\Psi(r,t)$ as a function, assumes value in a vector space ($\mathbb C^n$ or $\mathbb C^\infty$) over $\mathbb{C}$.
(2) $\Psi(r,t)$ assumes value in $\mathbb C$, and as a function itself (i.e. a mapping, a rule of correspondence), belongs to a set of functions, which constitute a vector space.
I guess you were thinking (1), but I am trying to explain (2) to you.
I'd like to say more but too tired now. I suggest reading some textbooks instead of Wikipedia:
SUGGESTED READING MATERIALS
[1] Sect. 1.2-1.5 Mathematical Concepts of Quantum Mechanics by Stephen J. Gustafson and Israel Michael Sigal
[2] Sect. 8.1-8.2 Quantum Mechanics by Franz Schwabl
p.s. I am not sure whether there's a name for $\hat H\Psi$.

A: If $\Psi$ is an eigenvector of $H$ then $H\Psi = E\Psi$, a vector.
If $\Psi$ is not an eigenvector of $H$ then $H\Psi$ is a vector but not a constant multiple of $\Psi$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ContentResolver query is throwing a nullpointerException I'm writing an MMS/SMS application on a rooted Android 2.3.3 htc incredible S with sense 2.1.
Now, while trying to receive a certain contacts list of SMS/MMS's I get a FC in the query.
here's some code:
Uri uri = Uri.parse("content://mms-sms/conversations/"+String.valueOf(thread_id));
ContentResolver cr = context.getContentResolver();
Cursor c= cr.query(uri,null,null,null,null);    //crashing here

logcat:
05-22 15:24:24.273: E/AndroidRuntime(32087): FATAL EXCEPTION: main
05-22 15:24:24.273: E/AndroidRuntime(32087): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uiu.messaging/com.uiu.messaging.ContactMessageChain}: java.lang.NullPointerException
05-22 15:24:24.273: E/AndroidRuntime(32087): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.ActivityThread.access$1500(ActivityThread.java:132)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.os.Looper.loop(Looper.java:143)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.ActivityThread.main(ActivityThread.java:4196)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at java.lang.reflect.Method.invokeNative(Native Method)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at java.lang.reflect.Method.invoke(Method.java:507)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at dalvik.system.NativeStart.main(Native Method)
05-22 15:24:24.273: E/AndroidRuntime(32087): Caused by: java.lang.NullPointerException
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.os.Parcel.readException(Parcel.java:1328)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:160)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:372)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.content.ContentProviderProxy.query(ContentProviderNative.java:408)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.content.ContentResolver.query(ContentResolver.java:264)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at com.uiu.messaging.Data.getContactChain(Data.java:319)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at com.uiu.messaging.ContactMessageChain.onCreate(ContactMessageChain.java:138)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
05-22 15:24:24.273: E/AndroidRuntime(32087):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)
05-22 15:24:24.273: E/AndroidRuntime(32087):    ... 11 more

All permissions are accounted for.
Any help will be greatly appreciated.
EDIT:
After following Mike's suggestion I receive the following error in the logcat:
05-22 16:31:46.178: E/AndroidRuntime(1892): FATAL EXCEPTION: main
05-22 16:31:46.178: E/AndroidRuntime(1892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uiu.messaging/com.uiu.messaging.ContactMessageChain}: android.database.sqlite.SQLiteException: near "*": syntax error: , while compiling: SELECT * FROM (SELECT DISTINCT date * 1 AS normalized_date, NULL AS * FROM sms WHERE (htc_category= 0 AND thread_id = 25 AND (type != 3 AND type > 0)) UNION SELECT DISTINCT date * 1000 AS normalized_date, NULL AS * FROM pdu LEFT JOIN pending_msgs ON pdu._id = pending_msgs.msg_id WHERE (htc_category= 0 AND thread_id = 25 AND msg_box != 3 AND (msg_box > 0 AND msg_box != 3 AND (m_type = 128 OR m_type = 132 OR m_type = 130))) ORDER BY normalized_date ASC)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread.access$1500(ActivityThread.java:132)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.os.Looper.loop(Looper.java:143)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread.main(ActivityThread.java:4196)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at java.lang.reflect.Method.invokeNative(Native Method)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at java.lang.reflect.Method.invoke(Method.java:507)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at dalvik.system.NativeStart.main(Native Method)
05-22 16:31:46.178: E/AndroidRuntime(1892): Caused by: android.database.sqlite.SQLiteException: near "*": syntax error: , while compiling: SELECT * FROM (SELECT DISTINCT date * 1 AS normalized_date, NULL AS * FROM sms WHERE (htc_category= 0 AND thread_id = 25 AND (type != 3 AND type > 0)) UNION SELECT DISTINCT date * 1000 AS normalized_date, NULL AS * FROM pdu LEFT JOIN pending_msgs ON pdu._id = pending_msgs.msg_id WHERE (htc_category= 0 AND thread_id = 25 AND msg_box != 3 AND (msg_box > 0 AND msg_box != 3 AND (m_type = 128 OR m_type = 132 OR m_type = 130))) ORDER BY normalized_date ASC)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:372)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.content.ContentProviderProxy.query(ContentProviderNative.java:408)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.content.ContentResolver.query(ContentResolver.java:264)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at com.uiu.messaging.Data.getContactChain(Data.java:318)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at com.uiu.messaging.ContactMessageChain.onCreate(ContactMessageChain.java:138)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
05-22 16:31:46.178: E/AndroidRuntime(1892):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)
05-22 16:31:46.178: E/AndroidRuntime(1892):     ... 11 more

I have no idea what's wrong with the SQL statement...

A: OK, fixed it. the trick was to enter actual column names into the projection. Seems like the bug was android's after all.

A: According to this other answer the second parameter shouldn't be null(although the documentation says that is a valid value), try
final String[] projection = new String[]{"*"};
Cursor query = contentResolver.query(uri, projection, null, null, null);

original post


text:
Q: SSL Certificate Installation Issue with Remote Desktop Connection Using Remote Desktop Connection to connect from Win7 to Win2008 Server R2, what is the difference in installing a self-signed certificate (for server authentication only) and installing a regular signed certificate?  I know the difference between the certificates, but how do I install a signed certificate (which is normally used for a website domain) to use for server authentication only (used for connecting through Remote Desktop Connection)?  I know I sound like someone paranoid, but I would like to understand the procedure necessary to replace the self-signed certificate with a signed certificate.  Thanks for all the help and Have a great day!

A: A. Buy your cert. Like you say, it's the same as one you would get for a web site. Just make sure the name of it matches the name the users will go to for RDP.
B. Install the cert by doing this:

*

*Open MMC.

*Highlight Certificates and click Add.

*Select Computer Account and click Next.

*Select Local Computer and click Finish.

*Back in the MMC, highlight Certificates.

*From the View menu, select Options.

*Change the View mode to Certificate Purpose and then click OK.

*Expand the Certificates object.

*Right-click on Server Authentication and select All Tasks/Import.

*When the Certificate Import Wizard launches, click Next.

*On the File To Import, click Browse and then pick the .PFX file you got from your certificate authority and then click Open. Click Next.

*On the Password page, enter the password for the cert if there is one. Select the Mark this key as exportable option. Click Next.

*On the Certificate Store page, accept the default to automatically select the cert store.

*Click Finish.

C. Enforce SSL by doing this:

*

*Launch Terminal Services Configuration.

*In the left pane, highlight Terminal Services Configuration: .

*In the right pane, right-click on RDP-Tcp and select Properties.

*Click on the General tab.

*Next to Certificate:Auto generated, click Select.

*Select the cert you just imported and click OK.

*Change the Security layer from Negotiate to SSL and the Encryption level from Client Compatible to High. Also, select Allow connections only from computers running Remote Desktop with Network Level Authentication. Click OK.

D. If you're making this server accessible from your internal network to the internet, you then need to give it an external IP and have TCP port 3389 opened on the firewall.
E. Create an A record in DNS that matches exactly the name of the cert.
That should do it. Note that you'll want to review the security configuration in step C7 above to your preference - that config will lock it down nice and tight and will work for anyone running Vista or later.

A: I believe you need to:

*

*Obtain the certificate for your server's full DNS name from a trusted root CA

*On the server open mmc.exe

*Add the Certificates snap-in, and choose 'Computer Account'

*Add the certificate into 'Personal Certificates'


text:
Q: Jquery, get elements with element name starts with a giving string How using jquery get all input text elements whith a name starts with 'productElement'

A: You an use attribute starts with selector [name^="value"]:

Selects elements that have the specified attribute with a value
  beginning exactly with a given string.

$('input[name^="productElement"]')


text:
Q: Issues with shell program in C I am creating a Linux type shell program for a school project. So far I have implemented the basic Linux external commands like "ls","ps", etc., using execvp and basic pipes. As part of the project, the user can either run the program in interactive mode or batch mode. In interactive mode the user just enters a command when prompted. For batch mode, the user specifies a file in the command line where there is a list of commands to execute.
The problem I am having is in batch mode. In batch mode, if an invalid command is listed (e.g. "kdfg", for which "kdfg: command not found" while be the output), everything afterward continues, but everything afterward is executed twice. so if I have a "kghd" on one line and the next line is "ls", then the "ls" command will be executed twice. I've literally been looking at my code for hours and have tried a bunch of stuff, but to no avail.
My code is displayed below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include<sys/wait.h>
#include<unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

char* InputString();
char** GetArgs(char* com);
void Free(char** args);
char** GetCommands(char** line);
void PipedCommands(char* line);
int batch = 0; //Acts as bool for if there is a batch file given at command line
FILE* bFile; //This is just to make a quick tweek to the file if necssary to prevent any undefined behavior and keep track of where we are in the fil.
int b_fd;
int stdin_cpy;

int main(int argc, char** argv)
{
    pid_t pid;
    int status;
    int fd;
    int exitCom = 0; //acts as bool to check if an exit command was given.
    char* line;

    if(argc > 1) //check if batch file was given.
    {
        /*
        if(freopen(argv[1], "r", stdin) == NULL) //I added this in case the file isn't found
        {
            printf("\nCould not open \"%s\". Terminated\n\n", argv[1]);
            exit(1);
        }
        */
        //The following is to append a newline at the end of the file (if there isn't one).
        //For some reaosn, there seems to be some undefined behavior if the input file isn't
        //stricitly ended with a newline.
        bFile = fopen(argv[1], "r+"); //open for reading and updating
        if(bFile == NULL)
        {
            printf("\nCould not open \"%s\". Terminated\n\n", argv[1]);
            exit(1);
        }
        fseek(bFile, -1, SEEK_END); //go to last character of file
        if(fgetc(bFile) != '\n') //If last character is not a newline, append a newline to the file.
        {
            fprintf(bFile, "\n");
        }
        fclose(bFile); //close the file.

        bFile = fopen(argv[1], "r"); //open file to keep track of when it ends
        b_fd = open(argv[1], O_RDONLY); //open file again (with file descriptor this time) to duplicate it to stdin
        stdin_cpy = dup(fileno(stdin)); //keep track of stdin file.
        dup2(b_fd, 0); //duplicate to stdin so program takes input from bFile
        close(b_fd);
        batch = 1;
    }

    //int i=0; //this was used for debugging purposes
    while(1)
    {
        printf("\n");
        char** coms = GetCommands(&line);
        for(int i=0; coms[i] != NULL; ++i) //loop goes through each command returned from GetCommands(...)
        {
            //fork and wait.
            pid = fork();
            wait(&status);

            if(pid == 0)
            {
                int pipedCommand = 0;
                //printf("\ncoms[%d]: %s\n", i, coms[i]);
                for(int j=0; j<strlen(coms[i]); ++j)
                {
                    if(coms[i][j] == '|')
                    {
                        pipedCommand = 1;
                        break;
                    }
                }
                if(pipedCommand == 1)
                {
                    PipedCommands(coms[i]);
                    exit(1);
                }
                char** args = GetArgs(coms[i]);
                //printf("\nargs[0]: %s\n", args[0]);
                if(strcmp(args[0],"exit") == 0)
                {
                    exit(5); //if exit command was given, exit status will be 5 (I just used 5 becuse I felt like it).
                }
                //printf("\nNo exit\n");
                printf("\n");
                execvp(args[0],args);
                printf("%s: command not found\n", args[0]);
                exit(1); //Normal exit exits with 1 or 0.
            }
            //Parent continues after child exits
            else if(pid > 0)
            {
                //check exit status of child
                if(WEXITSTATUS(status) == 5)
                    exitCom = 1; //set bool exitCom to 1 (true), indicating that the exit command was given
            }
        }
        if(pid > 0)
        {
            free(line);
            free(coms);
            //Now that all commands in the line were executed, check exitCom and if it is 1 (exit command was given), the shell can now exit.
            if(exitCom == 1)
            {
                printf("\n");
                exit(0);
            }
        }
/*
        if(i >= 5)
        {
            printf("\nFORCED EXIT\n");  //this was used for debugging purposes
            exit(1);
        }
        ++i;
*/
    }

    return 0;
}

char* InputString()
{
    int len = 20;
    char* str = (char*)malloc(sizeof(char)*len);
    char* buff;
    unsigned int i=0;

    if(str != NULL)
    {
        int c = EOF;
        //printf("%c", fgetc(bFile));
        while( ((c = getchar()) != '\n') && (c != EOF) )
        {
            /*
            //printf("%c", fgetc(bFile));
            //fgetc(bFile);
            if(feof(bFile))
            {
                printf("\n\nEnd of the line\n\n");
            }
            */
            str[i++] = (char)c;
            if(i == len)
            {
                len = len*2;
                str = (char*)realloc(str,sizeof(char)*len);
            }
        }
        str[i] = '\0';
        buff = (char*)malloc(i);
    }
    if(batch == 1)
    {
        if(fgets(buff, i, bFile) == NULL) //Once the end of file has been reached
        {
            dup2(stdin_cpy, 0); //revert input back to original stdin file so user can now enter commands interactively (this happens if exit command was not given)
            close(stdin_cpy); //close stdin_copy
            fclose(bFile); //close bFile as we have reached the end of it
            batch = 0;
        }
    }
    printf("\n");
    return str;
}

//User enters a line of commands (1 or more). Commands are separated with a ';' being the delimeter.
char** GetCommands(char** line)
{
    char** coms = (char**)malloc(sizeof(char*));
    char delim[] = ";";

    if(batch == 0)
        printf("prompt> ");
        fflush(stdout);

    *line = InputString();
    if(batch == 1)
        printf("%s\n", *line);

    strcat(*line, ";");

    int i=0;
   coms[i] = strtok(*line, delim);
   while(coms[i] != NULL)
   {
       ++i;
       coms = (char**)realloc(coms, sizeof(char*) * (i+1));
        coms[i] = strtok(NULL, delim);
        //printf("\ni: %d\n", i);
   }

   return coms;
}

//A command obtained from GetCommands(...) is separated into various arguments with a space, ' ', being the delimiter.
char** GetArgs(char* com)
{

    char** args = (char**)malloc(sizeof(char*));
    char delim[] = " ";

    //printf("\nline: %s\n", line);
   int i=0;
   args[i] = strtok(com, delim);
   while(args[i] != NULL)
   {
       ++i;
       args = (char**)realloc(args, sizeof(char*) * (i+1));
        args[i] = strtok(NULL, delim);
   }

   return args;
}

void PipedCommands(char* line)
{
    char** coms = (char**)malloc(sizeof(char*));
    int numComs;
    char delim[] = "|";

    int i=0;
    coms[i] = strtok(line, delim);
   while(coms[i] != NULL)
   {
        ++i;
        coms = (char**)realloc(coms, sizeof(char*) * (i+1));
        coms[i] = strtok(NULL, delim);
   }
   numComs = i;

   int fd[2];
   pid_t pid;
   int status;
   int prev_p = 0;

  // printf("\nnumComs: %d\n", numComs);
    for(int i=0; i<numComs; ++i)
    {
        //printf("\ni: %d\n", i);
        pipe(fd);
        pid = fork();
        wait(&status);
        if(pid == 0)
        {
            //printf("\nChild\n");
            if(i < numComs-1)
            {
                //printf("\ni < numComs-1\n");
                //printf("%s", coms[i]);
                //printf("coms[%d]: %s", i, coms[i]);
                //printf("\nBefore dup2\n");
                char** args = GetArgs(coms[i]);
                //printf("\nexecvp in if\n");
                if(prev_p != 0)
                {
                    dup2(prev_p, 0);
                    close(prev_p);
                }
                dup2(fd[1], 1);
                close(fd[1]);
                execvp(args[0],args);
                printf("%s: command not found\n", args[0]);
                exit(3);
            }
            else
            {
                //printf("\nelse\n");
                //printf("coms[%d]: %s", i, coms[i]);
                //printf("\nBefore dup2 in else\n");
                if(prev_p != 0)
                {
                    dup2(prev_p, 0);
                    close(prev_p);
                }
                //close(fd[0]);
                close(fd[1]);
                char** args = GetArgs(coms[i]);
                printf("\n");
                execvp(args[0],args);
                printf("%s: command not found\n", args[0]);
                exit(3);
            }
        }
        close(prev_p);
        close(fd[1]);
        prev_p = fd[0];
        if(WEXITSTATUS(status) == 3)
        {
            close(fd[0]);
            close(prev_p);
            close(fd[1]);
            return;
        }
    }
    close(fd[0]);
    close(prev_p);
    close(fd[1]);

}

You can probably ignore the PipedCommands(...) function as I do not think the problem lies there.
Below is a simple batch file:
kldfg
whoami

Below is the output using the above batch file
kldfg
kldfg: command not found

whoami
jco0100

whoami
jco0100

The whoami command should only execute once, but it appears to execute twice. After that, the program reverts to interactive mode as it should and everything runs fine from there. Does anyone have any idea why this is happening. This only happens when an unknown command is entered. If all commands in the batch file are valid, nothing is outputted twice. It's only for batch files that have an unknown command that all commands after the unknown one are outputted twice.
Here's another example:
Batch file:
date
kldfg
whoami; ls | wc -l
date | wc -c

Output:
date
Tue Apr 13 19:43:19 CDT 2021

kldfg
kldfg: command not found

whoami; ls | wc -l
jco0100
34

date | wc -c
29

whoami; ls | wc -l
jco0100
34

date | wc -c
29

A: I got it working by disconnecting stdin on the child process before running the command:
...
freopen("/dev/null", "r", stdin); // disconnect
execcvp(args[0], args);
...

From this link: If I fork() and then do an execv(), who owns the console?

A: I had a crack at debugging it. To get you started on that road:
Compile your C program with debugging symbols:
$ gcc --debug your-program.c

Now debug your C program:
$ gdb a.out

This start a gdb interactive shell.
In gdb itself:
(gdb) list
(gdb) set follow-fork-mode parent
(gdb) breakpoint 69

*

*list your code

*tell the debugger to follow the parent when fork()

*set a breakpoint at line 69

Run the program:
(gdb) run batch.txt

It will pause at line 69. Execute next line:
(gdb) next

Print a variable:
(gdb) print *coms

Continue running:
(gdb) continue

I leave the rest for you to explore.
I'm still not sure what's wrong with it. Something strange happens in InputString() after your fork fails with an unknown command. InputString() begins returning duplicates from getchar().
I didn't even know you could do that with stdin. Maybe just read from the file in a normal fashion, rather than clobbering stdin, and see if the problem goes away.

A: Don't write linux code much, I am trying to do more of that.
I took the fork and wait commands out so I could build it in mingw64 (because they arent supported in windows builds) and can't seem to reproduce the issue.
So I think the issue is in the multi-threading setup you have going there.
The "pid" variable is shared between every fork. which means when the fork command is called "pid" is set to whatever the last fork in the loop returned.
It looks like you are using an if statement checking the "pid" variable to see if this thread can execute the command. But wouldn't the main thread keep running right through that?
I don't know what fork() returns but "pid" is uninitialized, don't know if that matters.
Maybe this helps?


text:
Q: Inconsistent overload resolution with rvalue references My understanding of overload resolution is that 'T&&' is generally a better match than 'const T&'. However, I'm seeing some inconsistent behavior among compilers with this trivial example:
#include <iostream>

void Func(const double& a)
{
    (void)a;
    std::cout << "[lvalue]\n";
}

void Func(double&& a)
{
    (void)a;
    std::cout << "[rvalue]\n";
}

template <typename T>
void TFunc(T&& a)
{
    Func(a);
}

int main ()
{
    TFunc(5.5f);

    return 0;
}

Clang 3.2 will print [rvalue]. However, the VS2013 32bit/64bit compilers will print [lvalue]. If I change '5.5f' to '5.5', then both compilers will print [lvalue].
I can understand why the VS compiler chooses the 'const double&' version since I don't have a std::forward call to preserve the '&&' of the parameter. However, I still don't understand what makes clang think that the '&&' overload is the better choice.
Why does adding an implicit float to double conversion affect the behavior in clang? Who is right?

A: When you call with 5.5f, T is float, and the Func call effectively becomes Func(double(a)). The argument is a temporary, and so rvalue overload should be chosen.
When you call with 5.5, T is double, and no temporary is created in a call to Func(a). A named variable cannot bind to an rvalue reference, so lvalue overload is the only choice.
MSVC has a long-standing misfeature that allows temporaries to bind to non-const lvalue references. This is why it incorrectly chooses lvalue overload even in the first case. Try compiling with /Za (disable language extensions) - I believe it would match clang's behavior then.


text:
Q: TLSv1.0 Supported Got a job for a company with no  personalIT experience and was given the task of working on compliance issues. The issue is "TLSv1.0 Supported", the research I have done shows it is a application layer problem in the IP Suite. How would I go about fixing this issue as when I went to the National Vulnerability Database, It does not show this Vulnerability, is it a relatively new Vulnerability? How do I go about fixing this issue?

A: Since we have no idea what OS you have, server software, or anything of the kind I will offer some general information to point you in the right direction.
Note:  It is quite possible that major configuration changes may effect other software running on the system.  It is best to have a full back up of the server before you begin.  It is even better to restore that backup to a virtual machine, and test the changes there before implementing them in production.
If your company doesn't already have a certificate for SSL, you will need to purchase one, for example here:  https://www.digicert.com/  Preferably, EV cert.  For personal use lets encrypt is fine, but you need to pass compliance so it isn't going to be good enough.
On linux servers and/or PC
First you need to make sure you have a supported version of openssl.
In many cases this means updating your libssl and/or libopenssl.
https://www.openssl.org/
The most common are web servers like apache and nginx.

*

*update your SSL library

*update web server

*Change web server configure to only use TLS.

Most linux distributions have built-in package managers.  Consult the documentation for which one your linux supports, but here are some examples.  You probably want to stick with an update for now, as upgrade make sweeping system wide changes.  Even so, this is why we do a full backup incase something bad happens.
apt-get update
apt-get upgrade
apt-get distro

zypper update
zypper dup

What to plan for.  Many version upgrades of apache have configuration changes, and apache may initially fail to start.  You will have to view the log files to know where the errors are located.  Then consult google and apache's web site to update the configuration.  Some times located in /var/log/apache/error_log
For apache at least these options need to be set.  You may choose to alter the list of allowed things, but it works for me.
In ssl-global.conf
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA
SSLHonorCipherOrder on
       #   Point SSLCertificateFile at a PEM encoded certificate.
SSLCertificateFile /etc/apache2/ssl.crt/server.crt
SSLCertificateKeyFile /etc/apache2/ssl.key/server.key

Windows PC
Windows Server 2003 does not support the TLS 1.2 protocol.
https://www.basics.net/2015/10/06/iis-7-5-how-to-enable-tls-1-1-and-tls-1-2/
Most versions of windows have TLS support.
They probably use IIS.
It is possible if they have super old versions of either you may need to upgrade.
Then you need to edit the configuration to disable SSL all versions.


text:
Q: Reading the whole text file into a char array in C I want to read the contents of a text file into a char array in C. Newlines must be kept.
How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.
Edit: I have the following code now:
void *loadfile(char *file, int *size)
{
    FILE *fp;
    long lSize;
    char *buffer;

    fp = fopen ( file , "rb" );
    if( !fp ) perror(file),exit(1);

    fseek( fp , 0L , SEEK_END);
    lSize = ftell( fp );
    rewind( fp );

    /* allocate memory for entire content */
    buffer = calloc( 1, lSize+1 );
    if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);

    /* copy the file into the buffer */
    if( 1!=fread( buffer , lSize, 1 , fp) )
      fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);

    /* do your work here, buffer is a string contains the whole text */
    size = (int *)lSize;
    fclose(fp);
    return buffer;
}

I get one warning:  warning: assignment makes pointer from integer without a cast. This is on the line size = (int)lSize;. If I run the app, it segfaults.
Update: The above code works now. I located the segfault, and I posted another question. Thanks for the help.

A: FILE *fp;
long lSize;
char *buffer;

fp = fopen ( "blah.txt" , "rb" );
if( !fp ) perror("blah.txt"),exit(1);

fseek( fp , 0L , SEEK_END);
lSize = ftell( fp );
rewind( fp );

/* allocate memory for entire content */
buffer = calloc( 1, lSize+1 );
if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);

/* copy the file into the buffer */
if( 1!=fread( buffer , lSize, 1 , fp) )
  fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);

/* do your work here, buffer is a string contains the whole text */

fclose(fp);
free(buffer);

A: fgets() is a C function that can be used to accomplish this.
Edit: You can also consider using fread().

A: Since I used slurp() expecting it to work, a few days later I found out that.... it doesn't.
So for people that are eager to copy/paste a solution to "getting the contents of a FILE into a char*", here's something you can use.
char* load_file(char const* path)
{
    char* buffer = 0;
    long length;
    FILE * f = fopen (path, "rb"); //was "rb"

    if (f)
    {
      fseek (f, 0, SEEK_END);
      length = ftell (f);
      fseek (f, 0, SEEK_SET);
      buffer = (char*)malloc ((length+1)*sizeof(char));
      if (buffer)
      {
        fread (buffer, sizeof(char), length, f);
      }
      fclose (f);
    }
    buffer[length] = '\0';
    // for (int i = 0; i < length; i++) {
    //     printf("buffer[%d] == %c\n", i, buffer[i]);
    // }
    //printf("buffer = %s\n", buffer);

    return buffer;
}

A: A solution in the form of a complete program that answers the question and demonstrates it. It is a bit more explicit than other answers and, therefore, easier to understand for those less experienced in C (IMHO).
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/*
 * 'slurp' reads the file identified by 'path' into a character buffer
 * pointed at by 'buf', optionally adding a terminating NUL if
 * 'add_nul' is true. On success, the size of the file is returned; on
 * failure, -1 is returned and ERRNO is set by the underlying system
 * or library call that failed.
 *
 * WARNING: 'slurp' malloc()s memory to '*buf' which must be freed by
 * the caller.
 */
long slurp(char const* path, char **buf, bool add_nul)
{
    FILE  *fp;
    size_t fsz;
    long   off_end;
    int    rc;

    /* Open the file */
    fp = fopen(path, "rb");
    if( NULL == fp ) {
        return -1L;
    }

    /* Seek to the end of the file */
    rc = fseek(fp, 0L, SEEK_END);
    if( 0 != rc ) {
        return -1L;
    }

    /* Byte offset to the end of the file (size) */
    if( 0 > (off_end = ftell(fp)) ) {
        return -1L;
    }
    fsz = (size_t)off_end;

    /* Allocate a buffer to hold the whole file */
    *buf = malloc( fsz+(int)add_nul );
    if( NULL == *buf ) {
        return -1L;
    }

    /* Rewind file pointer to start of file */
    rewind(fp);

    /* Slurp file into buffer */
    if( fsz != fread(*buf, 1, fsz, fp) ) {
        free(*buf);
        return -1L;
    }

    /* Close the file */
    if( EOF == fclose(fp) ) {
        free(*buf);
        return -1L;
    }

    if( add_nul ) {
        /* Make sure the buffer is NUL-terminated, just in case */
        buf[fsz] = '\0';
    }

    /* Return the file size */
    return (long)fsz;
}

/*
 * Usage message for demo (in main(), below)
 */
void usage(void) {
    fputs("USAGE: ./slurp <filename>\n", stderr);
    exit(1);
}

/*
 * Demonstrates a call to 'slurp'.
 */
int main(int argc, char *argv[]) {
    long  file_size;
    char *buf;

    /* Make sure there is at least one command-line argument */
    if( argc < 2 ) {
        usage();
    }

    /* Try the first command-line argument as a file name */
    file_size = slurp(argv[1], &buf, false);

    /* Bail if we get a negative file size back from slurp() */
    if( file_size < 0L ) {
        perror("File read failed");
        usage();
    }

    /* Write to stdout whatever slurp() read in */
    (void)fwrite(buf, 1, file_size, stdout);

    /* Remember to free() memory allocated by slurp() */
    free( buf );
    return 0;
}

A: I have used following code to read xml file in to a char buffer and I had to add \0 at the end of file
FILE *fptr;
char *msg;
long length;
size_t read_s = 0;
fptr = fopen("example_test.xml", "rb");
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
rewind(fptr);
msg = (char*)malloc((length+1));
read_s = fread(msg, 1, length, fptr);
*(mip_msg+ read_s) = 0;
if (fptr) fclose(fptr);


text:
Q: Proc not found on runtime dlls like MSVCR120.dll & MSVCP120.dll I am using NanoServerApiScan.exe to scan my binaries for the nano server support. It returns Errors like the following,
KERNEL32.dll
  CopyFileA(Proc not found)
    Please use API CopyFileExA as substitution.
  MoveFileExA(Proc not found)
    Please use API MoveFileExW as substitution.
ADVAPI32.dll
  LogonUserW(Proc not found)
    Please use API LogonUserExExW as substitution.

I can follow the suggestions to make my binaries work on nano servers. The scan also return errors in MSVCR120.dll and MSVCP120.dll,
MSVCR120.dll
    __crt_debugger_hook(Proc not found)
    __crtUnhandledException(Proc not found)
    __crtTerminateProcess(Proc not found)
    _onexit(Proc not found)
MSVCP120.dll
    ?_Xbad_alloc@std@@YAXXZ(Proc not found)
    ?_Xout_of_range@std@@YAXPEBD@Z(Proc not found)
    ??0id@locale@std@@QEAA@_K@Z(Proc not found)

How to fix these kind of errors? Can the reverse forwarders package reroute these APIs also? What if my customer doesn't configure his server with reverse forwarders?


text:
Q: Print PDF file without opening print dialog in asp.net I want to print my PDF file without opening Print dialog in ASP.NET Web forms.
My requirement is I have some PDF files on my server and I want to print that file on button click but without opening the Print window.
How can I achieve this?

A: The best you can do is concatenate the PDF files into one file and then print it, showing the printer dialog once at the beginning of the process. .NET PDF libraries that have this functionality.
PdfDocument.Combine("Output.pdf", "doc1.pdf", "doc2.pdf", "doc3.pdf");

Please refer this documentation may help you Print without Dialog


text:
Q: How to know if Sharepoint 2013 List is registered to Remote Event Receiver in Provider Hosted App? I have multiple list in SharePoint 2013 and some of the lists are attached to ListEvent.svc service. I would like to know which specific lists are registered to that particular Remote Event Receiver?
I know we can get it programmatically using "properties.ItemEventProperties.ListTitle" but are there any XML files generated wherein it contains all the lists name attached to a particular service.


text:
Q: Tomcat start failure probably due to Linux network setup: java.net.BindException: Cannot assign requested address I can't start tomcat due to the pasted stack trace, and I don't believe the answer is in Java.
I've tried changing ports and confirmed that another port (8005) also fails with the same error message.
How do I verify that my linux network setup allows Java to use ports?
EDIT2: It appears this box has been the victim of an intrusion.  I believe it makes sense to flag this post for moderator to close since a compromised box can't be expected to behave normally.  Thank you everyone for your time and effort.
EDIT:
there is a possibility that corruption of packages in /bin is responsible.  I had to update the a few with up2date.
EXTRA INFO:
Re: similar questions, I've eliminated the JVM_BIND possibility by checking netstat.
ping localhost simply hangs:

$ ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
-- no responses ---
--- localhost ping statistics ---
9 packets transmitted, 0 received, 100% packet loss, time 8000ms

ping google works:

$ ping google.com
PING google.com (74.125.225.228) 56(84) bytes of data.
-- responses removed ---
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 1.389/1.417/1.443/0.048 ms, pipe 2
the exception:

    SEVERE: StandardServer.await: create[8036]:
java.net.BindException: Cannot assign requested address
        at java.net.PlainSocketImpl.socketBind(Native Method)
        at java.net.PlainSocketImpl.bind(Unknown Source)
        at java.net.ServerSocket.bind(Unknown Source)
        at java.net.ServerSocket.(Unknown Source)
        at org.apache.catalina.core.StandardServer.await(StandardServer.java:373)
        at org.apache.catalina.startup.Catalina.await(Catalina.java:662)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:614)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jun 5, 2013 12:49:05 PM org.apache.coyote.http11.Http11Protocol pause
INFO: Pausing Coyote HTTP/1.1 on http-8035
Jun 5, 2013 12:49:05 PM org.apache.catalina.connector.Connector pause
SEVERE: Protocol handler pause failed
java.net.SocketException: Invalid argument or cannot assign requested address
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(Unknown Source)
        at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.(Unknown Source)
        at java.net.Socket.(Unknown Source)
        at org.apache.jk.common.ChannelSocket.unLockSocket(ChannelSocket.java:492)
        at org.apache.jk.common.ChannelSocket.pause(ChannelSocket.java:289)
        at org.apache.jk.server.JkMain.pause(JkMain.java:725)
        at org.apache.jk.server.JkCoyoteHandler.pause(JkCoyoteHandler.java:153)
        at org.apache.catalina.connector.Connector.pause(Connector.java:1029)
        at org.apache.catalina.core.StandardService.stop(StandardService.java:566)
        at org.apache.catalina.core.StandardServer.stop(StandardServer.java:744)
        at org.apache.catalina.startup.Catalina.stop(Catalina.java:648)
        at org.apache.catalina.startup.Catalina$CatalinaShutdownHook.run(Catalina.java:692)

A: Seems to me that your /etc/host configuration is not correct. Are you able to ping 127.0.0.1? Also make sure you have following line in your host file
/etc/host
127.0.0.1           localhost

.
Please check if your "The Loopback Interface" is setup correctly.

A: "java.net.BindException: Cannot assign requested address" suggests another instance of Tomcat didn't shutdown properly and is still using the port you assigned to tomcat.

A: Answer from user1628502 is correct.Another instance is running and which is using this address, Kill that process and try to run the server again. Are you running as root? then all the port and resources used by the server will be unbinded and released automatically upon server close/shutdown. And in case of user , when you are not shutting down the server properly, the address remains to be binded, that might be your pblm.
Restart system & Try to run as root user

A: If you've already verified that no other process is using the same port as configured for Tomcat, you need to verify your network configuration now.
Check that your /etc/host file does not contain multiple entries for localhost. If it does, verify that the IP addresses listed are actually assigned to your machine. If not, either remove or update those entries with your current IP address.


text:
Q: Moving a slideshow using CSS/HTML I'm pretty new to HTML/CSS and stumbled across a tutorial to help me create an image slideshow for a website I'm making. I figured out how to get the slideshow to work but still haven't figured out how to move it yet.
sorry if the formatting is off I use prettier and not too sure if I like it. Thanks in advance!
Video by Clever Techie

/*image slider*/

.slide-container {
  top: 150%;
  width: 586px;
  height: 330;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  text-align: center;
}

.image-container {
  top: 100%;
  width: 2344px;
  height: 330;
  position: relative;
  transition: left 0.5s;
  -webkit-transition: left 0.5s;
  -moz-transition: left 1s;
}

.slider-image {
  float: left;
  margin: 0px;
  padding: 0px;
}

.button-container {
  top: 120%;
  position: relative;
}

.slider-button {
  top: 120%;
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background-color: #fff;
}

#slider-image-1:target~.image-container {
  left: 0px;
}

#slider-image-2:target~.image-container {
  left: -586px;
}

#slider-image-3:target~.image-container {
  left: -1172px;
}

#slider-image-4:target~.image-container {
  left: -1758px;
}

Photoreal Scenery

A: Welcome to SO.
seems like you are trying pure HTML CSS solution in that case please check this snippet (use full pageview). the tutorial related to this is here

.row {
  background: #fff;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}
* {
  box-sizing: border-box;
}

.slider {
  width: 300px;
  text-align: center;
  overflow: hidden;
}

.slides {
  display: flex;

  overflow-x: auto;
  scroll-snap-type: x mandatory;

  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;

  /*
  scroll-snap-points-x: repeat(300px);
  scroll-snap-type: mandatory;
  */
}
.slides::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
.slides::-webkit-scrollbar-thumb {
  background: black;
  border-radius: 10px;
}
.slides::-webkit-scrollbar-track {
  background: transparent;
}
.slides > div {
  scroll-snap-align: start;
  flex-shrink: 0;
  width: 100%;
  height: 400px;
  margin-right: 50px;
  border-radius: 10px;
  background: #eee;
  transform-origin: center center;
  transform: scale(1);
  transition: transform 0.5s;
  position: relative;

  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 100px;
}
.slides > div:target {
/*   transform: scale(0.8); */
}
.author-info {
  background: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 0.75rem;
  text-align: center;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  margin: 0;
}
.author-info a {
  color: white;
}
img {
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.slider > a {
  display: inline-flex;
  width: 1.5rem;
  height: 1.5rem;
  background: white;
  text-decoration: none;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin: 0 0 0.5rem 0;
  position: relative;
}
.slider > a:active {
  top: 1px;
}
.slider > a:focus {
  background: #000;
}

/* Don't need button navigation */
@supports (scroll-snap-type) {
  .slider > a {
    display: none;
  }
}

html, body {
  height: 100%;
  overflow: hidden;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom, #ddd, #eee);
  font-family: 'Ropa Sans', sans-serif;
}

   1
   2
   3
   4
   5

Also as Squashie01 has suggested you can use bootstrap classes to get this done easily here is a fiddle using the newest bootstrap classes. refer the documentation here.

A: Since you haven't described which type of slideshow you need, I have created slideshow which can either run automatically or can be controlled by the user. After user click or site load, it start automatic slide show in 10s. Automatic slideshow change slides in every 3s. Check out this snippet:

var slideIndex = 0;
var timer1, timer;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");

function showSlides() {//called by automatic slideshow
    clearTimeout(timer1);//clear previously set timer

    //clear styles
    for (var i = 0; i < slides.length; i++)
        slides[i].style.display = "none";
    for (var i = 0; i < dots.length; i++)
        dots[i].className = dots[i].className.replace(" active", "");

    //reset slideIndex
    if (++slideIndex == slides.length)
        slideIndex = 0;

    //reset styles
    slides[slideIndex].style.display = "block";
    dots[slideIndex].className += " active";

    //reset timer
    timer1 = setTimeout(showSlides, 3000);
}

function showSlide(n) {//called when user manually choose particular slide
    //clear previously set timers
    clearTimeout(timer1);
    clearTimeout(timer);

    //clear styles
    for (var i = 0; i < slides.length; i++)
        slides[i].style.display = "none";
    for (var i = 0; i < dots.length; i++)
        dots[i].className = dots[i].className.replace(" active", "");

    //reset slideIndex
    if (n == slides.length)
        slideIndex = 0;
    if (n < 0)
        slideIndex = slides.length;

    //reset styles
    slides[slideIndex].style.display = "block";
    dots[slideIndex].className += " active";

    //reset timer for automatic slideshow
    timer = setTimeout(showSlides, 10000);
}
/* make width, height, min/max properties includes content, padding and border */
* {box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
    width: 50vw;
    height: 50vh;
    position: relative;
    margin: auto;
    clear:both;
    background-color: black;
}

/* Hide the images by default */
.mySlides {
    display: none;
}

/* make images fit to slide width */
.mySlides img {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    text-align: center;
    height: 50vh; object-fit:  fill;
}

/* Next & previous buttons */
.prev, .next {
    cursor: pointer;
    position: absolute;
    top: 50%;
    margin: 0;
    width: auto;
    padding: 16px;
    color: white;
    font-weight: bold;
    font-size: xx-large;
    transition: 0.6s;
    user-select: none;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);

}

/* Position the "next button" to the right */
.next {
    right: 0;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
    background-color: black;
    opacity: 0.7;
}

/* Caption text */
.text {
    color: #f2f2f2;
    font-size: 4em;
    padding-bottom: : 12px;
    position: absolute;
    bottom: 8px;
    width: 100%;
    text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
    color: #f2f2f2;
    font-size: 1.5em;
    padding: 8px 12px;
    position: absolute;
    top: 0;
    z-index: 1;
}

/* Dots container */
.dots-container {
    text-align: center;
}

/* The dots/bullets/indicators */
.dot {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

.active, .dot:hover {
    background-color: #717171;
}

/* Fading animation */
.fade {
    -webkit-animation-name: fade;
    -webkit-animation-duration: 1.5s;
    animation-name: fade;
    animation-duration: 1.5s;
}

@-webkit-keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}

@keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}

/* Small devices specific alterations */
@media only screen and (max-width: 600px) {
    /* Slideshow container */
    .slideshow-container {
        width: 96vw;
    }

    .text {
        font-size: 1.5em;
    }

    .numbertext {
        font-size: 1em;
    }

    /* Next & previous buttons */
    .prev, .next {
        padding: 4px;
        font-weight: bold;
        font-size: large;
    }
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apple</title>

Photoreal Scenery

1 / 4

Caption Text

2 / 4

Caption Two

3 / 4

Caption Three

4 / 4

Caption Three

        ❮
        ❯

Here is the logic:
HTML
We have added <meta name="viewport" content="width=device-width, initial-scale=1.0"> to make page-width follows device width and set initial scaling to 1.0.
These are the classes

*

*slideshow-container - store container

*mySlides - slides

*fade - fade animation

*prev/next - previous, next buttons

*dots-container - store dots

*dot - individual dot

CSS
Important CSS additions are

*

**(all) - make border, padding included in measurements of height width

*slideshow-container - set it to 50% of viewport height and width

*mySlides - hide all slides

*mySlides img - center image and set bounds

*.prev, .next - disable selection, change to pointing cursor add transition

*.numbertext - set z-index to 1

*.dot - change to pointing cursor add transition

*@-webkit-keyframes fade - setup IE specific fading rules

*@keyframes fade - setup fading rules

*@media only screen and (max-width: 600px) - tweaks for small screen devices

JavaScript
There are 2 functions:

*

*showSlides() - used to create automatic slideshow.

*showSlide(n) - used to view slide selected by the user.

A:

           Previous

           Next


text:
Q: How to handle OCR Scan Error in VB6 Im trying to get all the info i can get from a pictured doc. Which includes hand-writings in some part. While scanning this im having my screen freeze like hell and than gives an error that says VB6 stopped working... I cant really findout what causes this so i just wanna get over it if there is an error or OCR faliure. Sadly couldnt succeded yet. Here what i done so far:
Dim Mdoc As MODI.Document
Dim Mlay As MODI.Layout
Dim fso As Scripting.FileSystemObject
Dim logfile As Object

Public Function ScanMan(ByVal Name As String, ByVal Path As String) As String
    Set Mdoc = New MODI.Document
    'Set Mdoc = CreateObject("MODI.Document")
    Set fso = New Scripting.FileSystemObject

    DoEvents
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''''''''''''''''''' Create OCRLog File '''''''''''''''''''
    OCRPath = App.Path & "\OCR Results Log\"
    OCRName = Str(DateTime.Date) & " OCRresults"
    If fso.FolderExists(OCRPath) = False Then
        fso.CreateFolder (OCRPath)
    End If
    If fso.FileExists(OCRPath & OCRName & ".txt") = False Then
        fso.CreateTextFile OCRPath & OCRName & ".txt"
    End If
    Set logfile = fso.OpenTextFile(OCRPath & OCRName & ".txt", ForAppending)
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    On Error GoTo OCRErr
    DoEvents
    Mdoc.Create Path & Name
    Mimg = Mdoc.Images(0).OCR(miLANG_ENGLISH, True, True)
    Set Mlay = Mdoc.Images(0).Layout
    logfile.WriteLine Mlay.Text

    ScanMan = Mlay.Text

    Mdoc.Close False

    Set Mlay = Nothing
    Set Mdoc = Nothing

OCRErr:
    logfile.WriteLine "OCR given (" & Err.Number & ") numbered (" & Err.Description & ") error."
    logfile.Close
End Function

So how can i handle this freeze problem?

A: Try this:
Mdoc.Images(0).OCR
logfile.Write Mdoc.Images(0).Layout.Text

Hope this helps.


text:
Q: gcloud functions call giving an error for background I am testing node js app using mocha and assert.
Get sample code from this link
I deploy helloBackground function in local and also in gcloud succesfullly
then I try to execute mocha test case.
also tried all way to call gcloud functions describe here
Then execute below command in CMD
functions call helloBackground --data '{\"name\": \"John\"}'
This should return "Hello John!" in command prompt.
but I receive an error as

Error: TypeError: Cannot read property 'name' of undefined

Please let me know how to pass proper data in CMD to test.
Thank you in advance.

A: Looking at your error message, it is most likely caused by the trigger argument you used when you deployed the app. The helloBackground function is a Background Function, and instead of --trigger-http, you should use a background function trigger.
For example: $ gcloud functions deploy helloBackground --runtime nodejs6 --trigger-resource you_bucket_name --trigger-event google.storage.object.finalize
You would need to create an empty .txt file in the same directory of your app and upload it to Cloud Storage
$ gsutil cp test.txt gs://[ the name of your cloud storage bucket ]

And you can run the app again.
You will find more explanation on the type of functions here
And you can follow this well documented tutorial on Cloud Storage here


text:
Q: How can i raise activate event in Asp.net?Is there any possibility? We have activate event in windows application like that is there any event in asp.net? How can i raise activate like event in Asp.net?Is there any possibility?

A: Have a look at DOM events and especially the focus event, section "Focusing and blurring the entire window".
You need to write a Javascript handler for the required events which either updates the page via Ajax or raises an ASP.Net event.


text:
Q: OS X Yosemite - TCP/IP issues when using manual IP I seem to be having a weird issue on OS X Yosemite (10.10.5) - When I have my wifi connection set to DHCP, everything works fine. But, when I switch to manual IP (even with the exact same IP config that I get from DHCP), routing to internet sites fails. I can ping local computers, but, pinging other sites results in "No route to host". I would appreciate any ideas on how to fix this. Thanks
Edit:
The routes that I have after setting a manual ip are
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.2.144      UGScI           1        0     en1
127                127.0.0.1          UCS             0        0     lo0
127.0.0.1          127.0.0.1          UH              8     2206     lo0
169.254            link#5             UCS             0        0     en1
192.168.2          link#5             UCS             7        0     en1
192.168.2.1        a0:63:91:2:9e:b0   UHLWI           0       88     en1   1195
192.168.2.3        74:d4:35:94:ef:54  UHLWIi          5      302     en1   1140
192.168.2.9        9c:20:7b:c8:9d:f7  UHLWIi          1        0     en1   1188
192.168.2.14       64:27:37:e7:24:51  UHLWI           0        9     en1   1141
192.168.2.100      28:c6:8e:5f:de:82  UHLWI           0       84     en1   1140
192.168.2.140      0:11:32:b:b9:11    UHLWI           0       14     en1   1140
192.168.2.144/32   link#5             UCS             1        0     en1
192.168.2.144      link#5             UHLWIir         2        0     en1
192.168.2.250/32   link#5             UCS             0        0     en1
192.168.2.255      ff:ff:ff:ff:ff:ff  UHLWbI          0       24     en1

A: Looks like I am affected by the issue posted here. The proposed solution of adding a new default route works. If anybody else, has a better solution, where I don't have to do that everytime - when I switch between DHCP and Manual - I would love to try it. Thanks
Solution posted there is to add a default route to the router IP
sudo route add default 192.168.x.x


text:
Q: Understanding kusto SCAN operator query I am trying to figure out how the scan operator works.
References:
[Scan operator] [Blog by Adi Eldar] [SO question] [Another SO post]
Question 1
The Scan operator matching logic says

Each record from the input is evaluated against all of scan's steps, starting from last to first.

Given n records and m steps : does this mean that

*

*the input records starting from 1 to n are matched with steps m to 1 ?
or

*the input records starting from n to 1 are matched with steps m to 1 ?
Question 2
The matching logic then states that

If the state of the previous step isn't empty and...

So, when evaluating a step (m-1) in a scan having m total steps, which one of the following is the previous step (considering that documentation states that steps are evaluated from last to first)

*

*m-2

*m

Question 3
..and what happens when the previous step is empty ?
Question 4

Looking at the above query on the left, it seems to suggest that

*

*the input records starting from 1 to n are matched with steps 1 to m.

This is not in accordance with what the matching logic says.
Question 5
Run query online
I understand the query on the left and its output.
For each of the step, a match is found and thus each sequence has the number of records equal to the number of steps (three).
Now when I change the condition in step 1, I expect the records to simply shift, but still have 3 matches per sequence as long as enough records are available. But as you can see on the right side of the image, the output is different.
Why do two records match against the last step within the same sequence ?
Question 6
Run the query online


text:
Q: Jasper Reports: How to conditionally set the textbox style? Is it possible in Jasper Reports to conditionally set a textbox style? If yes, how?
Please note that I'm aware of conditional styles, but I do not need a style which varies on a condition, but set the proper style using a different condition for each textbox (of course I could create a conditional style for each textbox, but that would be a real PITA...).
I'm using Jasper Reports 3.7.6 and the Jasper Studio Eclipse plugin.
Thanks
Use case example pseudocode:

bean1 {
    f1
    f2
}

bean2 {
    cond1
    cond2
}

<textbox1 style="(bean2.cond1 ? style1 : style2)">
    bean1.f1
</textbox1>
<textbox2 style="(bean2.cond2 ? style1 : style2)">
    bean1.f2
</textbox2>

A: Unfortunately you can't define a generic style. See page 135 of the iReport Ultimate Guide:
http://community.jaspersoft.com/documentation/ireport-ultimate-guide:

Please note that the conditions cannot be generic,
  for instance, you cannot set a condition like "if the number is positive" or "if the string is
  null
  ." You must be very specific,
  specifying, for example, that a
  particular value (field, parameter, variable or
  any expression involving them) must be positive
  or
  null, and so on.

A: Answering myself: it turns out that it is not possible to set conditional style the way I needed. I ended up with duplicating each text fields (a copy for each style), then setting the visibility upon the condition. Boring and time consuming, but it works.


text:
Q: What does ".swap" in "swap!" source code do? I was curious so I checked source code of swap! function on clojure repository, and it was like this:
(defn swap!
  "Atomically swaps the value of atom to be:
  (apply f current-value-of-atom args). Note that f may be called
  multiple times, and thus should be free of side effects.  Returns
  the value that was swapped in."
  {:added "1.0"
   :static true}
  ([^clojure.lang.Atom atom f] (.swap atom f))
  ([^clojure.lang.Atom atom f x] (.swap atom f x))
  ([^clojure.lang.Atom atom f x y] (.swap atom f x y))
  ([^clojure.lang.Atom atom f x y & args] (.swap atom f x y args)))

And I don't know what the ".swap" function is doing? I tried to search for it but it's not defined in the same file, so can't find definition of it. Or is this another special thing that is actually not a function at all?

A: A lot of things in Clojure are actually implemented in Java, like reference types (atom, ref, var, agent), data structures (map, vector, list, set), namespaces (the actual Namespace class) and other stuff. When reading the source code for Clojure functions in clojure.core it's not rare to find an interop call to a Java method.
It is my understanding that there's a long term objective to implement these things in Clojure itself (search here for Clojure-in-Clojure), but for now these things are implemented in Java, which is really not so bad since the whole language is open source and you can check any implementation detail online in the github repo (already linked in a comment): Clojure (note that there's a jvm and a clj folder indicating in what language the code inside is implemented).

A: In Clojure, an expression (.x object a b c) results in a method call, which in Java would be expressed as object.x(a, b, c). For more details see Java Interop.
In this particular case, the swap! function calls an appropriately overloaded swap method of the clojure.lang.Atom instance passed as the first argument. The swap method contains the actual logic performing the swap.

A: Simply put, an atom is sth. that is under control of transactional memory. (Read about STM, please.) It is inmutable for its observers (dereferencing an atom returns inmutable state as of the instant of deref), but can be mutated transactionally. This is exactly what swap! does. It transactionally swaps the old value for the new value. Please note that it is very different from assignment. Assignment is not safe for concurrency.
In other words, atom works like a cell in a database table. When you query it, you will have a value, not an exception, even if at the same instant another query is updating it.
Cheers -


text:
Q: X-Men: Why didn't Psylocke notice Jubilee's presence in the Australian outback? In Uncanny X-Men (Vol I) #244 Jubilee tailgates through Gateway's teleportation window from LA to the deserted Australian outback town where the X-Men have set up headquarters.
She remains there in hiding until after the remaining X-Men (Psylocke, Colossus, Havok, Dazzler) enter the Siege Perilous in Uncanny issue #251.
In Uncanny #248, evidence is presented that Jubilee has been swiping food from the X-Men's reserves when Colossus notices their food supply is lower than it should be. And then Jubilee is shown raiding the pantry later in the issue.
In #245 Psylocke (Betsy Braddock) is shown on guard duty for their HQ (presumably psi-scanning the area). And in #248 she performs a "Full intensity" psi-scan on the surrounding area while looking for Storm.
So my question:
If Jubilee was in close proximity to the X-Men for days (or weeks) in the deserted Australian outback, and Psylocke was often performing psi-scans of the area, why didn't Psylocke ever notice Jubilee's presence?
The X-Men were generally on high-alert throughout these issues as they feared attack by the Reavers. It seems unlikely that the telepathic Psylocke would either not notice Jubilee's presence or decide to keep this information to herself if she did notice. A failure to disclose this information to the team could put the carefully-guarded secret of their existence and operations in Australia at risk.
Additionally Jubilee was just a teenage kid. As established in earlier issues of Captain Britain involving the Warpies (British children mutated by the remnants of Jasper's Warp), Betsy Braddock had an affinity for kids. If Betsy noticed the presence of Jubilee stranded in the desolate Australian outback, she'd be likely to want to help Jubilee survive.
It seems very unlikely that Psylocke would have noticed Jubilee yet decided to keep the information private.
What gives?

A: According to her Wikipedia entry,

In her early appearances, Jubilee also displayed an apparent immunity to telepathy, but this was soon abandoned by writers. She had on occasion used this ability to hide herself from telepathic scans and probes from Sentinels. Whether or not she knew of this ability remains unaddressed.

This is backed up by these panels from the conclusion of issue #244:

Storm says that they couldn't find Jubilee using psiscans, but she obviously hadn't gone very far, as she's just around the corner there.

A: It was eventually culminated that Besty Braddock had cameras in her eyes thanks to Mojo, perhaps it was somehow related to that. That's my best "comic book" answer.

A: I thought of this question when I first read these issues too, but I hadn't read them until after I'd read the original generation X series. In that series Gateway is shown training Monet in the use of her mental powers, which led me to believe that he had some level of telepathy. That always made me think that it was him who had concealed Jubilee's presence, for his own mysterious purpose..


text:
Q: How to "copy" DataGrid in xaml I have 3 datagrids: grid0, gird1, grid2 binded to observable collection Watches0, Watches1, Watches2 respectively. Here is just small example, in my real project DataGrids had many columns with styles, converters etc. All datagrids are completely same except x:Name, Grid.Column and ItemSource properties. The problem is if I want to change some property or column in xaml I have to do it for all 3 datagrids. I was thinking about using styles or templates but see some problems with it. I'm interested is there a way to "copy" element in xaml?
    <DataGrid x:Name="grid0"
              Grid.Column="0"
              AllowDrop="True"
              AutoGenerateColumns="False"
              SelectionMode="Extended"
              ItemsSource="{Binding Watches0}"
              Drop="watchesGrid_Drop"
              PreviewMouseLeftButtonDown="watchesGrid_PreviewMouseLeftButtonDown">

        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"
                                Binding="{Binding Name}"
                                Width="40" />
            <DataGridTextColumn Header="Value"
                                IsReadOnly="True"
                                Binding="{Binding Value}"
                                Width="60" />
        </DataGrid.Columns>

    </DataGrid>


text:
Q: Newtonsoft get value from hierarchical JSON using single dynamic selector I'm looking for a way to pass a single string selector to get a value from hierarchical JSON. This selector could be id, location.name, or even deeper, it has to be dynamic.
I have this JSON:
{
"generatedAt": "2022-01-01 02:03:25",
"myitems": [
{
    "id": "1795089",
    "location": {
        "name": "Myplace",
        "countryCode": "DE"\
    },
}
,
{
    "id": "1795070",
    "location": {
        "name": "Roseplace",
        "countryCode": "US"
    },
}

],
"count": 2
}

I want to select nested values by a SINGLE selector. E.g. location.name. I want this because I want to store the selector in a single field in my database.
I have tried this:
Dim obj As JObject = JObject.Parse(json)
Dim jsonArray As JArray = DirectCast(obj("myitems"), JArray)

For Each item In jsonArray
    item("id").Value(Of String) 'works
    item("location")("name").Value(Of String) 'works
    item("location.name").Value(Of String) 'does NOT work
Next

I considered storing the selector in my database like location.name and then when executing the selector in my code, first splitting that selector by ., and then build it like item(selectorpart(0))(selectorpart(1)).Value(Of String)
However, I have a lot of fields that I need to select and it would be a lot of extra code if I need to split each selector first. Also because many times my JSON is not as nested as above and I wouldn't need to split the selector at all.
How could I do this?
I checked here, but the described requirement seems different than mine.
I checked here but it doesn't apply to nested structures.
Also, I'm reading JSON feeds from different providers so I can't simply create a single class as was suggested in some other threads, and I don't want to have to map each feed
structure to a class.


text:
Q: What external authentication service can I use to secure my Jenkins Continuous Integration environment? Jenkins CI comes with a number of built-in security options like authentication, SSL...etc (described here).
Because there are always security vulnerabilities that could be discovered with Jenkins CI (like these) and upgrading Jenkins CI immediately is sometimes difficult due to plug-in bugs, is there another way to easily secure Jenkins CI with encrypted login authentication without it being on Jenkins itself? (I'm using Jenkins on a Windows OS).
What I would like to have is a completely separate authentication service for all users of Jenkins CI which they have to authenticated against prior to them actually being able to use Jenkins CI. Do any of you know some possible solutions for this?

A: The standard security setup page describes how to configure different options for authenticating users. For windows it recommends installing the active directory plugin.


text:
Q: PBKDF2 function with 128 Bit Key Length and 1,024 iterations of SHA256 in .Net Framework 4.5 I am trying to work with an api in .Net framework 4.5 that supposed to provide me cryptocurrencies wallet. in a part of it's documentations it says:

Pass Pin Code through the PBKDF2 function with 128 Bit Key Length and
  1,024 iterations of SHA256

i could not find the Specify method in C# to do that. in documentations they have input "be9d3a4f1220495a96c38d36d8558365" as pin code and the out put is "4369cb0560d54f55d0c03564fbd983c4".
it seems that i should use Rfc2898DeriveBytes Method, and i used it like code below but i didnot get the same result.
string output = Convert.ToBase64String((new Rfc2898DeriveBytes("e24546d6643137a310968566cf1cd42b",16, 1024)).GetBytes(32));
output ==> 'x10zclBJY2eeZqjMyPfQm4ljyMFPvWbxF72Om2DCzHE='

A: It's probably best to implement your own version of PBKDF2. PBKDF2 is the actual algorithm implemented by the badly named Rfc2898DeriveBytes class.
As .NET 4.5 doesn't include the functionality to use PBKDF2 with a different hash. .NET version 4.7.2 does include the functionality but it doesn't allow the salt to be zero bytes.
So therefore it is best to implement your own version. The .NET version of Microsoft has specific copyright notices that do not seem compatible. One way to go around this is to implement PBKDF2 from Mono, but the later versions of Mono do not implement this class (it seems) and they do not implement the version where the hash can be chosen.
Fortunately bartonjs has indicated a version that has the permissive MIT license, which can be used, leading to the following solution:
using System;
using System.Security.Cryptography;
using System.Text;

namespace StackOverflow
{
    public class Rfc2898DeriveBytes : DeriveBytes
    {
        private const string DEFAULT_HASH_ALGORITHM = "SHA-1";

        private const int MinimumSaltSize = 0;
        private readonly byte[] _password;
        private byte[] _salt;
        private uint _iterations;
        private HMAC _hmac;
        private int _blockSize;

        private byte[] _buffer;
        private uint _block;
        private int _startIndex;
        private int _endIndex;

        public string HashAlgorithm { get; }

        public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations)
            : this(password, salt, iterations, DEFAULT_HASH_ALGORITHM)
        {
        }

        public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, string hashAlgorithm)
        {
            if (salt == null)
                throw new ArgumentNullException(nameof(salt));
            if (salt.Length < MinimumSaltSize)
                throw new ArgumentException(nameof(salt));
            if (iterations <= 0)
                throw new ArgumentOutOfRangeException(nameof(iterations));
            if (password == null)
                throw new NullReferenceException();  // This "should" be ArgumentNullException but for compat, we throw NullReferenceException.

            _salt = (byte[])salt.Clone();
            _iterations = (uint)iterations;
            _password = (byte[])password.Clone();
            HashAlgorithm = hashAlgorithm;
            _hmac = OpenHmac();
            // _blockSize is in bytes, HashSize is in bits.
            _blockSize = _hmac.HashSize >> 3;

            Initialize();
        }

        public Rfc2898DeriveBytes(string password, byte[] salt)
             : this(password, salt, 1000)
        {
        }

        public Rfc2898DeriveBytes(string password, byte[] salt, int iterations)
            : this(password, salt, iterations, DEFAULT_HASH_ALGORITHM)
        {
        }

        public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, string hashAlgorithm)
            : this(Encoding.UTF8.GetBytes(password), salt, iterations, hashAlgorithm)
        {
        }

        public Rfc2898DeriveBytes(string password, int saltSize)
            : this(password, saltSize, 1000)
        {
        }

        public Rfc2898DeriveBytes(string password, int saltSize, int iterations)
            : this(password, saltSize, iterations, DEFAULT_HASH_ALGORITHM)
        {
        }

        public Rfc2898DeriveBytes(string password, int saltSize, int iterations, string hashAlgorithm)
        {
            if (saltSize < 0)
                throw new ArgumentOutOfRangeException(nameof(saltSize));
            if (saltSize < MinimumSaltSize)
                throw new ArgumentException(nameof(saltSize));
            if (iterations <= 0)
                throw new ArgumentOutOfRangeException(nameof(iterations));

            _salt = new byte[saltSize];
            RandomNumberGenerator.Create().GetBytes(_salt);
            _iterations = (uint)iterations;
            _password = Encoding.UTF8.GetBytes(password);
            HashAlgorithm = hashAlgorithm;
            _hmac = OpenHmac();
            // _blockSize is in bytes, HashSize is in bits.
            _blockSize = _hmac.HashSize >> 3;

            Initialize();
        }

        public int IterationCount
        {
            get
            {
                return (int)_iterations;
            }

            set
            {
                if (value <= 0)
                    throw new ArgumentOutOfRangeException(nameof(value));
                _iterations = (uint)value;
                Initialize();
            }
        }

        public byte[] Salt
        {
            get
            {
                return (byte[])_salt.Clone();
            }

            set
            {
                if (value == null)
                    throw new ArgumentNullException(nameof(value));
                if (value.Length < MinimumSaltSize)
                    throw new ArgumentException("Too few bytes for salt");
                _salt = (byte[])value.Clone();
                Initialize();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_hmac != null)
                {
                    _hmac.Dispose();
                    _hmac = null;
                }

                if (_buffer != null)
                    Array.Clear(_buffer, 0, _buffer.Length);
                if (_password != null)
                    Array.Clear(_password, 0, _password.Length);
                if (_salt != null)
                    Array.Clear(_salt, 0, _salt.Length);
            }
            base.Dispose(disposing);
        }

        public override byte[] GetBytes(int cb)
        {
            if (cb <= 0)
                throw new ArgumentOutOfRangeException(nameof(cb));
            byte[] password = new byte[cb];

            int offset = 0;
            int size = _endIndex - _startIndex;
            if (size > 0)
            {
                if (cb >= size)
                {
                    Buffer.BlockCopy(_buffer, _startIndex, password, 0, size);
                    _startIndex = _endIndex = 0;
                    offset += size;
                }
                else
                {
                    Buffer.BlockCopy(_buffer, _startIndex, password, 0, cb);
                    _startIndex += cb;
                    return password;
                }
            }

            while (offset < cb)
            {
                byte[] T_block = Func();
                int remainder = cb - offset;
                if (remainder > _blockSize)
                {
                    Buffer.BlockCopy(T_block, 0, password, offset, _blockSize);
                    offset += _blockSize;
                }
                else
                {
                    Buffer.BlockCopy(T_block, 0, password, offset, remainder);
                    offset += remainder;
                    Buffer.BlockCopy(T_block, remainder, _buffer, _startIndex, _blockSize - remainder);
                    _endIndex += (_blockSize - remainder);
                    return password;
                }
            }
            return password;
        }

        public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
        {
            // If this were to be implemented here, CAPI would need to be used (not CNG) because of
            // unfortunate differences between the two. Using CNG would break compatibility. Since this
            // assembly currently doesn't use CAPI it would require non-trivial additions.
            // In addition, if implemented here, only Windows would be supported as it is intended as
            // a thin wrapper over the corresponding native API.
            // Note that this method is implemented in PasswordDeriveBytes (in the Csp assembly) using CAPI.
            throw new PlatformNotSupportedException();
        }

        public override void Reset()
        {
            Initialize();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "HMACSHA1 is needed for compat. (https://github.com/dotnet/corefx/issues/9438)")]
        private HMAC OpenHmac()
        {
            String hashAlgorithm = HashAlgorithm;

            if (string.IsNullOrEmpty(hashAlgorithm))
                throw new CryptographicException("HashAlgorithm name not present");

            if (hashAlgorithm.Equals("SHA-1", StringComparison.OrdinalIgnoreCase))
                return new HMACSHA1(_password);
            if (hashAlgorithm.Equals("SHA-256", StringComparison.OrdinalIgnoreCase))
                return new HMACSHA256(_password);
            if (hashAlgorithm.Equals("SHA-384", StringComparison.OrdinalIgnoreCase))
                return new HMACSHA384(_password);
            if (hashAlgorithm.Equals("SHA-512", StringComparison.OrdinalIgnoreCase))
                return new HMACSHA512(_password);

            throw new CryptographicException("MAC algorithm " + hashAlgorithm + " not available");
        }

        private void Initialize()
        {
            if (_buffer != null)
                Array.Clear(_buffer, 0, _buffer.Length);
            _buffer = new byte[_blockSize];
            _block = 1;
            _startIndex = _endIndex = 0;
        }

        // This function is defined as follows:
        // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
        // where i is the block number.
        private byte[] Func()
        {
            byte[] temp = new byte[_salt.Length + sizeof(uint)];
            Buffer.BlockCopy(_salt, 0, temp, 0, _salt.Length);

            WriteInt(_block, temp, _salt.Length);

            temp = _hmac.ComputeHash(temp);

            byte[] ret = temp;
            for (int i = 2; i <= _iterations; i++)
            {
                temp = _hmac.ComputeHash(temp);

                for (int j = 0; j < _blockSize; j++)
                {
                    ret[j] ^= temp[j];
                }
            }

            // increment the block count.
            _block++;
            return ret;
        }

        private void WriteInt(uint i, byte[] buf, int bufOff)
        {
            buf[bufOff++] = (byte)(i >> 24);
            buf[bufOff++] = (byte)(i >> 16);
            buf[bufOff++] = (byte)(i >> 8);
            buf[bufOff] = (byte)i;
        }
    }
}

this is a class where more specific exceptions have been rewritten, some specialized cloning is replaced, and the random salt generation is generalized. The minimum salt size has also been set to 0. Otherwise it is the same code in a different name space.
It is possible to use it like this:
string pw = "be9d3a4f1220495a96c38d36d8558365";
byte[] salt = new byte[0];
int iterations = 1024;

Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(pw, salt, iterations, "SHA-256");
byte[] key = pbkdf2.GetBytes(16);

Note that the PIN is hexadecimals encoded as UTF-8, the default encoding for PBKDF2 (not the default encoding for .NET!). The result is a key that, when represented as hexadecimals equals 4369cb0560d54f55d0c03564fbd983c4.
I've converted to a 4.5 compatible class using a string to indicate the hash function, for the one with an enum HashAlgorithm (4.6 or something similar) take a look at the revision history.