dimanche 28 juin 2015

Is there a perfect way to use iOS Framework template instead of static library now?

Since iOS8 and Xcode6 has release for a year, I have still cannot find a canonical tutorial for using Framwork template (iOS Universal Framework Mk 8) to develope a static library.

enter image description here

Even though the most popular Repo I think, kstenerud/iOS-Universal-Framework, has shut down when iOS8 Framework release.

enter image description here


However, when I try to develope a Static Framework I got ton of issues to resolve:

  1. I still have to do lipo for x86_64, i386, arm64, amrv7;
  2. remove Code signature from Framework;
  3. Build a resource bundle and import it to app project independent;
  4. Framework Info.plist and modules seem useless;
  5. Still a little worried if Apple will refuse my app since use a Static Framework.

Is there a good tutorial for building and using Static Framework? Any help will be appreciated! Thx.

I get error when I add a UITableView

I have a static UITableView, and in one of the cells, I have a dynamic UITableView. Here is the code I used:

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

    if (self.tableView == tableView) {
        cell = [tableView cellForRowAtIndexPath:indexPath];
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.textLabel setText:self.tagsArray [indexPath.row]];
    }
    return cell;
}

When I run the app, it crashes with the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106efbc65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106b94bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000106efbaca +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x00000001067a998f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   UIKit                               0x000000010762fa83 -[UITableView _configureCellForDisplay:forIndexPath:] + 128
    5   UIKit                               0x0000000107637a41 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 533
    6   UIKit                               0x0000000107616248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    7   UIKit                               0x000000010762c8a9 -[UITableView layoutSubviews] + 210
    8   UIKit                               0x00000001075b6a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    9   QuartzCore                          0x0000000106588ec2 -[CALayer layoutSublayers] + 146
    10  QuartzCore                          0x000000010657d6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    11  QuartzCore                          0x000000010657d546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    12  QuartzCore                          0x00000001064e9886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    13  QuartzCore                          0x00000001064eaa3a _ZN2CA11Transaction6commitEv + 462
    14  QuartzCore                          0x00000001064eb0eb _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    15  CoreFoundation                      0x0000000106e2eca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    16  CoreFoundation                      0x0000000106e2ec00 __CFRunLoopDoObservers + 368
    17  CoreFoundation                      0x0000000106e24a33 __CFRunLoopRun + 1123
    18  CoreFoundation                      0x0000000106e24366 CFRunLoopRunSpecific + 470
    19  GraphicsServices                    0x000000010ad61a3e GSEventRunModal + 161
    20  UIKit                               0x0000000107536900 UIApplicationMain + 1282
    21  myBudget                            0x000000010611fe5f main + 111
    22  libdyld.dylib                       0x0000000108952145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why do I get this error, and what can I do to fix it?

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

samedi 27 juin 2015

Changing the status bar color on UISearchController

I'm trying to change iOS 8 search bar status bar color but I tried the UIStatusBarStyleLightContent with no luck anyone knows a better way? Example of how it looks right now

Get the number of lines in UILabel iOS8

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a UILabel based of its set text?

I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

What is the point of a nil AutoreleasingUnsafeMutablePointer in a Swift closure?

I was reading the different ways to parse REST API calls in Swift and came across the following:

var url : String = "http://ift.tt/1tENtnZ"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

The one line that makes no sense to me is var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil. We already captured our NSError parameter and stored it in a variable called error, and now we're overwriting that and making it nil in our first line in the closure? Or if somehow Swift then performs a downcast of the error from type NSError! to AutoreleasingUnsafeMutablePointer<NSError?>, then can someone explain how that happens?

Thanks!

UITextInputCurrentInputModeDidChangeNotification return nill in ios 8.3

I want to detect current input mode of keyboard, and change text direction with respect to it (rtl if arabic, and ltr if english) in viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(changeInputMode:)
                                             name:UITextInputCurrentInputModeDidChangeNotification object:nil];

} and in changeInputMode:

-(void)changeInputMode:(NSNotification *)notification
{
    UITextInputMode *thisInputMode = [notification object];

    NSLog(@"inputMethod=%@",thisInputMode);
}

but thisInputMode is nill! if I use this code instead:

    NSString *inputMethod = [[UITextInputMode currentInputMode] primaryLanguage];
    NSLog(@"inputMethod=%@",inputMethod);

it works fine and detects current password, but currentInputMode is deprecated. why [notification object] returns nill?

Add lines on ImageView IOS (objective c)

enter image description here

I need some help to get this thing working..

Basically on button click, I have to add a line of fixed width with circle end points on the ImageView. User can add upto 5 lines. If I click on any circle (red dot) end point of line, it should allow to resize the line. Point can be dragged to any position on screen and line has to be straight. At the end, i should be able to calculate the length of each line. I just spent a lot of time on this and referring other similar answers. But so far, no luck.. Any reference code or links is greatly appreciated. Thanks!

IOS resize or reposition line on touching end points (Objective c)

I am trying to resize the line, by touching the red circle points. Let's say, I want to move this line above lips in the image below, How can i achieve this. The line is not moving from the position. I have just started up with this thing and can't find much relevant resources to accomplish this. Trying the best...Please guide me in the right direction. Below is my code and reference image.

Objective c code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];

    //Add second circle
    [path moveToPoint:CGPointMake(100.0, 100.0)];
    [path addLineToPoint:CGPointMake(200, 200)];
    [path moveToPoint:CGPointMake(200, 200)];

    [path addArcWithCenter:CGPointMake(200, 200) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];


    [path closePath];
    [[UIColor redColor] setStroke];
    [[UIColor redColor] setFill];
    [path stroke];
    [path fill];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 2.0;
    shapeLayer.fillColor = [[UIColor redColor] CGColor];

    [self.view.layer addSublayer:shapeLayer];

}

enter image description here

I will add multiple lines like this and my ultimate aim is to move individual line at any position in the image and get measurement of that area using line size.

EDIT: The scenario is, at any given time there will be some flexible lines available on the screen. Lets's say by clicking button, one more new line will be added to screen. The user can just drag any end point to resize the line in any direction. I can't get this thing working correctly.. no luck.

Here is my gist file link, http://ift.tt/1dp9Hm0 It basically adds a UIView to create a line on image. The code in gist allows me to resize the line height by moving touch points up and down but doesn't allow me to rotate the angle of line and adding text in the centre. THANKS

Thanks!

How to get all the classes of an application specified with identifier in iOS?

I want to get all the classes of a specified application (maybe any other apps, not only the app itself), I can get the NSBundle of that application with it's identifier, but how can I get the classes with the NSBundle, or can I get the classes directly with the application's identifier? We assume it could be a jailbroken environment.I tryied objc_copyClassNamesForImage but failed, does any one have ideas? Any help will be appreciated!

NSBundle * bundle = [NSBundle bundleWithIdentifier:appIdentifier];
NSString * bundlePath = [bundle bundlePath];
NSLog(@"%@", bundlePath);

unsigned int count;
const char **classes;

classes = objc_copyClassNamesForImage([bundlePath UTF8String], &count);

for (int i = 0; i< sizeof(classes)/sizeof(classes[0]); i++){
    NSLog(@"class name: %s", classes[i]);
}

Parse Relation [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I have a jobs app that enables users to view jobs. Jobs is a class in my Parse backend. I want to create a Favorites tab where user can mark certain jobs.

I've created a Relations Column in my User Class referring it to my Jobs class.

However, I have ran into this when the user taps to make the job a favorite: [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I feel like my PFRelation coding is spot on. I've researched this error but cannot seem to find any subject that relates to my problem. I must be making a mistake somewhere but

@interface JobDetailViewController ()

@end

@implementation JobDetailViewController

@synthesize jobPhoto;
@synthesize RotationLabel;
@synthesize QualificationsTextView;
@synthesize Job_DescriptionTextView;
@synthesize TypeLabel;
@synthesize LocationLabel;
@synthesize ClearanceLabel;
@synthesize PositionLabel;
@synthesize job;
@synthesize POC;
@synthesize Email;
@synthesize Phone;
@synthesize Apply;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_Scroller setScrollEnabled:YES];
    [_Scroller setContentSize:CGSizeMake(320, 2200)];

    [self dismissKeyboard];
    self.PositionLabel.text = job.position;
    self.RotationLabel.text = job.rotation;
    self.LocationLabel.text = job.location;
    self.TypeLabel.text = job.type;
    self.ClearanceLabel.text = job.clearance;
    jobPhoto.file = (PFFile *)job.imageFile;
    [jobPhoto loadInBackground];

    NSMutableString *pocText = [NSMutableString string];
    for (NSString* poc in job.poc) {
        [pocText appendFormat:@"%@\n", poc];
    }
    self.POC.text = pocText;

    NSMutableString *emailText = [NSMutableString string];
    for (NSString* email in job.email) {
        [emailText appendFormat:@"%@\n", email];
    }
    self.Email.text = emailText;


    NSMutableString *phoneText = [NSMutableString string];
    for (NSString* phone in job.phone) {
        [phoneText appendFormat:@"%@\n", phone];
    }
    self.Phone.text = phoneText;

    NSMutableString *applyText = [NSMutableString string];
    for (NSString* apply in job.apply) {
        [applyText appendFormat:@"%@\n", apply];
    }
    self.Apply.text = applyText;

    NSMutableString *qualificationsText = [NSMutableString string];
    for (NSString* qualifications in job.qualifications) {
        [qualificationsText appendFormat:@"%@\n", qualifications];
    }
        self.QualificationsTextView.text = qualificationsText;

    NSMutableString *job_descriptionText = [NSMutableString string];
    for (NSString* job_description in job.job_description) {
        [job_descriptionText appendFormat:@"%@\n", job_description];
    }
    self.Job_DescriptionTextView.text = job_descriptionText;
}



- (IBAction)favoriteButtonAction:(id)sender {
    PFObject *jobs = [PFObject objectWithClassName:@"Jobs"];
    PFUser *user = [PFUser currentUser];
    PFRelation *relation = [user relationForKey:@"Favorites"];
    [relation addObject:jobs];

    [user saveInBackground];



}


- (void)viewDidUnload
{
    [self setJobPhoto:nil];
    [self setPositionLabel:nil];
    [self setRotationLabel:nil];
    [self setLocationLabel:nil];
    [self setTypeLabel:nil];
    [self setQualificationsTextView:nil];
    [self setJob_DescriptionTextView:nil];
    [self setPOC: nil];
    [self setPhone:nil];
    [self setEmail:nil];
    [self setApply:nil];
    [self dismissKeyboard];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(void) dismissKeyboard {
    [Email resignFirstResponder];
    [POC resignFirstResponder];
    [Phone resignFirstResponder];
    [Job_DescriptionTextView resignFirstResponder];
    [QualificationsTextView resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) favoriteSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Added job to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}


- (void) favoriteFailed {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ooooops!" message:@"Error occurred while adding to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}



@end

JobListViewController that populates the jobs prior to the JobDetailViewController:

#import "JobDetailViewController.h"
#import "JobListViewController.h"
#import "Job.h"
#import "SearchedResultCell.h"
#import <Parse/Parse.h>



@interface JobListViewController () <UISearchDisplayDelegate, UISearchBarDelegate> {

}

@property (nonatomic, weak) IBOutlet UISearchBar *searchedBar;
@property (nonatomic, strong) NSString *mainTitle;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, assign) BOOL canSearch;

@end

    @interface JobListViewController ()

    @end

    @implementation JobListViewController
    {}
    @synthesize searchedBar;
    @synthesize mainTitle;
    @synthesize subTitle;
    @synthesize canSearch;


    - (id)initWithCoder:(NSCoder *)aCoder
    {
        self = [super initWithCoder:aCoder];
        if (self) {
            // Custom the table

            // The className to query on
            self.parseClassName = @"Jobs";

            // The key of the PFObject to display in the label of the default cell style
            self.textKey = @"Position";

            // Whether the built-in pull-to-refresh is enabled
            self.pullToRefreshEnabled = YES;

            // Whether the built-in pagination is enabled
            self.paginationEnabled = YES;

            // The number of objects to show per page
            self.objectsPerPage = 20;
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];



    }

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];

        self.canSearch = 0;

    }

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }

    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }

    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }

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

    - (void)objectsWillLoad {
        [super objectsWillLoad];

        // This method is called before a PFQuery is fired to get more objects
    }


    - (PFQuery *)queryForTable
    {
        PFQuery *query1 = [PFQuery queryWithClassName:@"Jobs"];
        NSString *searchThis = [searchedBar.text capitalizedString];
        [query1 whereKey:@"Position" containsString:searchThis];
        PFQuery *query2 = [PFQuery queryWithClassName:@"Jobs"];
        [query2 whereKey:@"Type" containsString:searchThis];
        PFQuery *query = [PFQuery orQueryWithSubqueries:@[query1,query2]];
            [query orderByDescending:@"createdAt"];

        if (self.pullToRefreshEnabled) {
            query.cachePolicy = kPFCachePolicyNetworkOnly;
        }

        // If no objects are loaded in memory, we look to the cache first to fill the table
        // and then subsequently do a query against the network.

        return query;
    }







    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
    {
        static NSString *simpleTableIdentifier = @"JobCell";
            static NSString *pimpleTableIdentifier = @"JobCell";

        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

        SearchedResultCell *bell = [self.tableView dequeueReusableCellWithIdentifier:pimpleTableIdentifier];

        if (bell == nil) {
            bell = [[SearchedResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pimpleTableIdentifier];

            }

            [self configureSearchResult:bell atIndexPath:indexPath object:object];


        }

        // Configure the cell
        PFFile *thumbnail = [object objectForKey:@"imageFile"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"AppIcon.png"];
        thumbnailImageView.file = thumbnail;
        [thumbnailImageView loadInBackground];

        UILabel *positionLabel = (UILabel*) [cell viewWithTag:101];
        positionLabel.text = [object objectForKey:@"Position"];
        UILabel *rotationLabel = (UILabel*) [cell viewWithTag:102];
        rotationLabel.text = [object objectForKey:@"Rotation"];
        UILabel *locationLabel = (UILabel*) [cell viewWithTag:103];
        locationLabel.text = [object objectForKey:@"Location"];
        UILabel *typeLabel = (UILabel*) [cell viewWithTag:104];
        typeLabel.text = [object objectForKey:@"Type"];


    return cell;
    }


    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"showJobDetail"]) {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

            Job *job = [[Job alloc] init];

            JobDetailViewController *destViewController = segue.destinationViewController;

            PFObject *object = [self.objects objectAtIndex:indexPath.row];
            job.position = [object objectForKey:@"Position"];
            job.poc = [object objectForKey:@"POC"];
            job.email = [object objectForKey:@"Email"];
            job.phone = [object objectForKey:@"Phone"];
            job.apply = [object objectForKey:@"Apply"];
            job.imageFile = [object objectForKey:@"imageFile"];
            job.rotation = [object objectForKey:@"Rotation"];
            job.location = [object objectForKey:@"Location"];
              job.type = [object objectForKey:@"Type"];
            job.clearance = [object objectForKey:@"Clearance"];
            job.job_description = [object objectForKey:@"Job_Description"];
            job.qualifications = [object objectForKey:@"Qualifications"];
            destViewController.job = job;

        }

    }

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {

        [self clear];

        self.canSearch = 1;

        [self.searchedBar resignFirstResponder];

        [self queryForTable];
        [self loadObjects];

    }



    - (void)configureSearchResult:(SearchedResultCell *)cell atIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
    {
        mainTitle = [object objectForKey:@"Position"];
        cell.mainTitle.text = mainTitle;

        subTitle = [object objectForKey:@"Type"];
        cell.detail.text = subTitle;

         // Implement this if you want to Show image
         cell.showImage.image = [UIImage imageNamed:@"AppIcon.png"];

         PFFile *imageFile = [object objectForKey:@"imageFile"];

         if (imageFile) {
         cell.showImage.file = imageFile;
         [cell.showImage loadInBackground];
         }
    }


    #pragma mark - UITableViewDelegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {



        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        [searchedBar resignFirstResponder];

        if ([self.objects count] == indexPath.row) {
            [self loadNextPage];
        } else {
            PFObject *photo = [self.objects objectAtIndex:indexPath.row];
            NSLog(@"%@", photo);

            // Do something you want after selected the cell
        }
    }



    #pragma mark - UIScrollViewDelegate


    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        [self.searchedBar resignFirstResponder];
    }

    - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        [self.searchedBar resignFirstResponder];
        [self queryForTable];
        [self loadObjects];

    }







    @end

Update image of UIImageView in NSmutableArray?

I have:

Class Piece inherit UIImageView;

- (void)setJumpAt:(int)frame {
NSMutableArray *ret = [SkinConstants BallSelected];
NSString *name = [NSString stringWithFormat:@"balls-%d-%d", color - 1, [[ret objectAtIndex:frame] intValue]];
UIImage *a = [UIImage imageNamed:name];
NSLog(@"%d setJumpAt: %@", self.tag ,name);
[self performSelectorOnMainThread:@selector(setImage:) withObject:a waitUntilDone:NO];
[self  setNeedsDisplay];
[self setNeedsLayout];}

Class Player contain NSMutableArray of Piece;

Class JumpThread contain NSTimer use to set image of Piece;

- (void) timer_Tick{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
        [piece setJumpAt:frame++];
        [piece setNeedsDisplay];
        if (frame == len)
            frame = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
    });
});}

I run code normal, but image of Piece not change in mainview, Sorry, I'm not so good at English.

Create a Url shortcut in Xcode using Objective c

In my app users can upload images to my website and they can share the link. What I need to do is to create a link shortcut.

For example I have this link: (http://ift.tt/1dpVk0W)

i need to change the link to (for example): wedv.ghfi

is it possible to do it?

Thanks

Can cocos-2dx play a song from the phone's library?

I'm using an MPMusicPlayerController to access and play music in an objective C file, but I need to play it in my C++ file using SimpleAudioEngine. Is it possible to select an item with MPMusicPlayerController and use its URL(ipod-library://item/item.m4a?id=456458322781804615) to play the music?

Deterministic shuffle in Objective C

This code in Java is the implementation of Knuth's shuffle, but a deterministic one, controllable by the seed to the random number generator.

public String shuffleString(String data, long shuffleSeed) {
    if(shuffleSeed!=0) {
        Random rnd = new Random(shuffleSeed);
        StringBuilder sb = new StringBuilder(data);
        int n = data.length();
        while(n>1) {
            int k = rnd.nextInt(n--);
            char t = sb.charAt(n);
            sb.setCharAt(n, sb.charAt(k));
            sb.setCharAt(k, t);
        }
        return sb.toString();
    }
    else {
        return data;
    }
}

How can I implement a deterministic shuffle in Objective C that outputs the same shuffle order given the same seed? I am using srandom(_shuffleSeed); and random()%(n--) knowing that arc4_random is better but that cannot be seeded.

- (NSString*) shuffleString:(NSString*) data withShuffleSeed:(int) shuffleSeed {
    if(shuffleSeed!=0) {
        srandom(_shuffleSeed);
        NSMutableString *result = [[NSMutableString alloc] initWithString:data];
        unsigned long n = data.length;
        while(n>1) {
            unsigned long k = random()%(n--);
            unichar t = [result characterAtIndex:n];
            NSRange r1 = {n,1};
            [result replaceCharactersInRange:r1 withString:[NSString stringWithFormat:@"%c", [result characterAtIndex:k]]];
            NSRange r2 = {k,1};
            [result replaceCharactersInRange:r2 withString:[NSString stringWithFormat:@"%c", t]];
        }
        return result;
    }
    else {
        return data;
    }
}

Currently, the two shuffle methods do not generate the same result for the same input parameters. I am sure I am missing something!

Stop NSRunloop in NSOperate

I Know is maybe a bad design,but all i want to do is run a nsTimer in NSOperation,so here is what i done:

            #import "CountOperate.h"

            @interface CountOperate ()

            @property(nonatomic, strong) NSTimer *timer;
            @property(nonatomic, unsafe_unretained) NSInteger repeatSecond;

            @end

            @implementation CountOperate

            - (void)main
            {
                self.repeatSecond = 15;

                self.timer = [NSTimer timerWithTimeInterval:self.repeatSecond target:self selector:@selector(update) userInfo:nil repeats:YES]; 
                [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; 
                [[NSRunLoop currentRunLoop] run]; 
            }

            - (void)cancel
            {
                [self.timer invalidate];
                [super cancel];
            }

            - (void)update
            {
                NSUInteger myRandom = arc4random_uniform(100);
                self.dateArray[self.myID] = @(myRandom);     
                [self.tableView performSelectorOnMainThread:@selector(reloadData)
                                                 withObject:nil
                                              waitUntilDone:NO];
                [[NSRunLoop currentRunLoop] performSelector:@selector(update) withObject:nil afterDelay:self.repeatSecond];
            }

The problem here is that I can not stop it immediately, it must wait to be completed after the completion of the interval timer, it's like NSRunLoop must run until the next time the timer fires .

In this example,i had wait 15second,so i can see the NSOperation has finish its job.

NSClassFromString with String coming from Plist

I'm trying to instanciate a class in Swift from a String, ok it can sound weird but the ClassName comes from a Plist.

I'm using NSClassFromString but it doesn't work with the Plist String, I think that I'm close to this question: NSClassFromString works for string literals, returns nil for constructed strings

But I can't use the solution as I can't know the possible classname coming from the Plist

The weird behavior is that if I create the String manually in the code, with the same value then it works as expected... it's like the converted String from the Plist is not the real exact same thing as a new String.

There is the code

let className: String = definition["class"] as! String
let classNameManually: String = "AppName.ServiceTest"
let aClass = NSClassFromString(className) as! NSObject.Type
let instanceObject = aClass()

It works with classNameManually but not with className

Then I put a breakpoint and I have identified a slighly difference

DebugView

Do you have a magic answer ?

Thank you!

save backgroundColor with NSUserDefaults

I tried to save what user choose color from Plain Segmented Control in objective-c with this code but it doesn't working

for saving

   UIColor *saveColor = changeColor.backgroundColor;
   NSUserDefaults *Color = [NSUserDefaults standardUserDefaults];
   [Color setObject:saveColor forKey:@"saveColor"];
   [Color synchronize];

for loading

   NSUserDefaults *color = [NSUserDefaults standardUserDefaults];
   UIColor *loadColor = [color objectForKey:@"saveColor"];
   [changeColor setBackgroundColor:loadColor];

Replace Placeholder Content in PDF iOS

I have looked at the other questions similar to this one, such as how to edit a PDF in objective-c? and iOS - searching and replacing on a PDF; however I have not found an answer that seems to work.

I have a PDF with the placeholder [text1], and I would like to replace this with a string that I receive from user input and then display the updated PDF.

2 Notes:

Apple's PDFkit appears to be only available in OS X, and I have been unable to locate an iOS library that has this functionality.

I don't believe that this PDF would be easy to generate from an HTML template.

Is there a way to do this (in either Swift of ObjC)?

Loop formatting

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSInteger n = 5;
     NSInteger nFactorial = n;
     while (n > 1) {
         nFactorial = nFactorial * --n;
     }
     NSLog(@"The factorial of %ld is %ld", (long)n, (long)nFactorial);
     return YES;
 }

For this code, why does nFactorial have to be initialized to n? Why can't the code just use n in all the places that have nFactorial in it?

Subclassing UITableViewCell & [tableView dequeueReusableCellWithIdentifier:CellIdentifier]

I'm trying understand how [tableView dequeueReusableCellWithIdentifier:CellIdentifier] works. Here is my situation:

I have designed my UITableViewCell subclass in IB and now I'm trying style my sub elements of the cell in my subclass. Unfortunately the method [tableView dequeueReusableCellWithIdentifier:CellIdentifier] seems to not call any method in my cells subclass. With methods I mean initWithCoder,initWithFrame or init.

This is my actual code:

static NSString *BasicCellIdentifier = @"BasicCell";
GSFeedBasicTableViewCell *basicCell = [tableView dequeueReusableCellWithIdentifier:BasicCellIdentifier];

My Cells are showing up but I would to customize the cell further in my subclass to avoid styling code in my TableController. Any hints are really appreciated.

NSDictionary and NSPredicate

I am using a NSDictionary that itself contains dictionaries some keys and its values which are arrays.The format is like so:

{
    0 =     {
        0 =         (
                     3,
                     0,
                     3
                     );
        1 =         (
                     2,
                     0,
                     2
                     );
    };
    1 =     {
        0 =         (
                     1,
                     1,
                     1
                     );
        1 =         (
                     1,
                     1,
                     2
                     );
    };
};

I'm using NSPredicate to searach a dictionary within the dictionary to get the array that contains value 3 at index 0. like so:

inside = [VDictionary objectForKey:[NSNumber numberWithInt:0];
NSPredicate *p = [NSPredicate predicateWithFormat:@"%@[SELF][0] == '3'", inside];

It works but the problem is that the above only searches the dictionary with key 0, I want to search all the dictionaries not just one at a time.

How do I use NSPredicate to search all the dictionaries within a dictionary and get the array that contains the value 3 at index 0?

iOS app single table view cell not functioning

I am using the storyboard feature in Xcode, and I wanted to add a switch for if the order was a credit card. I have seen in other apps a switch is usually in a single table view cell. I tried to implement it on the storyboard, (the second scene of the app) and whenever I go to that scene in the simulation, it crashes with this message:(I cannot post a picture, if you would like one email me at zacharymanno@gmail.com) 2015-06-27 20:07:33.233 ToDoList[9048:436904] * Assertion failure in -[UITableViewCell _setHostsLayoutEngine:], /SourceCache/UIKit_Sim/UIKit-3347.44/NSLayoutConstraint_UIKitAdditions.m:2761 2015-06-27 20:07:33.268 ToDoList[9048:436904] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Must translate autoresizing mask into constraints to have _setHostsLayoutEngine:YES.'

Check for local notifications settings from extension

Is it possible to check for the current Local Notifications settings inside a Cocoa Touch Framework used by an extension?

Usually I’d use

    var currentStatus:UIUserNotificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings()

… but access to UIApplication.sharedApplication() is not available as extension safe API.

Any alternative?

Get multiple selected rows info of an uitableview

I have so far a tableView that works with multiple selection rows. Everything is working fine except when I'm trying to get an array of the rows that I've selected.

var currentStat = Stat()
var selectedMarks = [StatEvents]()

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.font = UIFont.systemFontOfSize(8.0)
    cell.textLabel?.text = "\(currentStat.statEvents[indexPath.row].name)  \(currentStat.statEvents[indexPath.row].dateRanges) horas=\(currentStat.statEvents[indexPath.row].hours)"

    if currentStat.statEvents[indexPath.row].isSelected{
        cell.accessoryType = .Checkmark

    } else {
        cell.accessoryType = .None
    }
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: false)
    currentStat.statEvents[indexPath.row].isSelected = !currentStat.statEvents[indexPath.row].isSelected

    if (selectedMarks.contains(currentStat.statEvents[indexPath.row])){
        selectedMarks.removeAtIndex(indexPath.row)
    } else {
        selectedMarks.append(currentStat.statEvents[indexPath.row])
    }
    tableView.reloadData()
}

The problem is in the "didSelectRowAtIndexPath" method. When I select any row, it appends the object in the "selectedMarks" array (this is working fine), but the problem is when I deselect some of those rows, it should erase back the object in the selectedMarks array. I'm trying to use the "contains" method, but I get a compilation error in that line

could not find an overload for contains that accepts the supplied arguments

Somebody knows how do I solve this? Probably there's another way to get the selected rows array info...

Loading GameCenter Log-in in ViewDidLoad

I researched Apple's documentation for GameCenter, but when I tried to implement their sample code, it did not work. Am I doing something incorrectly?

 - (void)viewDidLoad {
[super viewDidLoad];

 GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];
if (gameCenterController != nil)
{
   gameCenterController.gameCenterDelegate = self;
   [self presentViewController: gameCenterController animated: YES completion:nil];
}
}

I am trying to load the sign in for gamecenter right when the user opens the app. Thank you

Swift / Objective-C integration w.r.t. ARC

I'm having trouble with the integration of Objective-C and Swift. The Objective-C code uses MRC (not ARC). To boil down the issue to a simple example, imagine that I have an objective-C object that owns lots of other objects embedded in its state. It provides methods to return pointers to objects it owns. Since it does not relinquish ownership, all of these objects do not see retain or autorelease messages when they are being returned.

The flow of control takes me through code in this order

A (objective-C) calls B (Closure in Swift) and B calls C (method in Objective-C)

The sequence of calls is supposed to get a value (pointer to object) from the call to C.

Imagine that the big container class has a method (C above)

-(id)getObject:(NSUInteger)identifier

The method has been tagged for swift with:

-(__unsafe_unretained id)getObject:(NSUInteger)identifier

to indicate that the object returned should not be subjected to ARC (at least, that was my hope... It does not seem to be the case).

Now, I write a closure in swift as follows (I simplified to keep the essence) (That's B in the example):

{ k -> container.getObject(k) }

And that closure is passed to Objective-C code (A in the example) and is being called from objective-C. What I was hoping for is: no ARC "interference". But that's not the case! If I rewrite the swift closure to:

{ k -> unowned let rv = container.getObject(k); return rv}

Things are a little better (retain/release calls originating from swift code disappear), but I still get into trouble, because it seems that the compiler creates another Objective-C Block to bridge with Swift closures.

See the fragment below (lifted from lldb backtrace)

#0  0x0000000100159210 in partial apply forwarder for queensNaiveSwift.(closure #1).(closure #4) ()
#1  0x000000010015b627 in reabstraction thunk helper from @callee_owned () -> (@owned ObjectiveC.ORIntVar) to @callee_unowned @objc_block () -> (@autoreleased ObjectiveC.ORIntVar) ()

There is this "Reabstraction thunk helper" which (as I understand it) is a compiler generated objective-C block that wraps the Swift closure. As you see, its 'type' betrays the fact that the return value (type ORIntVar in reality) is @autoreleased. Looking at the assembly confirms that there is a call to autorelease. But the entire thing was written to avoid ARC. Bottom line, the thunk helper is sending my object an autorelease. That puts the object in a global auto-release pool (which defeats the purpose and delays the release). Adding a temporary autoreleasepool is not the solution here. I simply do not wish to receive retain/release/autorelease.

So... How do I tell the Swift compiler to not generate auto-release in its thunks? The value coming back is __unretained_unsafe (and unowned in Swift). Why does the thunk feel compelled to do anything with this pointer? It should be a simple pass-through, no funny business. (Also, I'd rather avoid being forced to pepper the Swift code with unowned let x = ...

Any hint/explanation is much appreciated.

Custom font set in a storyboard won't display on device

I created a label in LaunchScreen.storyboard and used a custom font. It looks all right in xcode but when I run the program on my device or simulators it won't display the custom font. I've already added the font file to the project and the font name to the "Fonts provided by application" array in info.plist. The font file is also added to "Copy Bundle Resources". I've tried all the solutions provided in some other similar questions but none of them worked so I'm not asking a repeated question.

Failed to Import Bridging Header Error

I accidentally messed up my projects' settings while installing and then uninstalling cocoapods. I'm now getting the error "failed to import bridging header". I checked my build settings and the path to the file under build settings > code generation > objective-c bridging header is correct. I messed around with my Framework Search Paths (they are empty now) in build settings while trying to get cocoapods to work. Would really appreciate some help on fixing this bridging header issue.

Instruments memory leaks detecting issue in Xcode 6.2

everyone! I'm using Xcode 6.2 now for developing objective-c, when i try to use "Instruments" to detecting memory issues, it just not work as i were see books or blogs.I use the code blow to test(main function is omitted, using default xcode&instruments settings).

for(int i=0; i<2; i++)
{
    KSTestObj *obj0 = [[KSTestObj alloc] init];
    KSTestObj *obj1 = [[KSTestObj alloc] init];
    obj0.obj = obj1;
    obj1.obj = obj0;
}
sleep(100);

and the KSTestObj class just has a NSObject propety. Here is a strange phenomenon. When I set i<1, the "Instruments" capture nothing, and when i<2(or bigger), it can detect a memory problem by Leaks! BUT the leaked objects number is 2(or 2*times-2)!Thats ODD! Anyone knows what going on? Did i made any mistakes? tks! here is the picture & log: i<2, and "Instruments" detect 2 object leaked.

2015-06-27 14:33:19.108 ObjCPro_Test[50820:603] init success! 0x7ff968700c10
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff968700c20
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff9687003a0
2015-06-27 14:33:19.110 ObjCPro_Test[50820:603] init success! 0x7ff9687003b0
<End of Run>

enter image description here

i<1, "Instruments" shows no leaked objects!

2015-06-27 14:30:17.737 ObjCPro_Test[50789:603] init success! 0x7f7ff1e00830
2015-06-27 14:30:17.738 ObjCPro_Test[50789:603] init success! 0x7f7ff1e004e0
<End of Run>

enter image description here

Is the navigation controller's root view controller the same as that of the window's when set?

Just a question I have that doesn't appear to have been directly answered here before.

I have a simple app using storyboard which has a navigation controller set as the initial view controller in the storyboard, and the first view controller set as the navigation controller's root view controller.

I've read that the window has exactly one root view controller. Is that, then, in this case the navigation controller itself, since it's the initial view controller, or does the window share the navigation controller's root view controller?

Thanks in advance for any help.

Handling scrolling nested UIScrollViews scrolling in the same direction

I am trying to implement something similar to Twitter iOS App (profile page)

This is view hierarchy:

  • UIScrollView

    • Custom View
    • UITableView

    During scroll, once UIScrollView reaches certain y offset, (when UITableView gets to the top of the screen), then UITableView should start scroll. This needs to work in one continuous motion.

By default, this is not in continuous motion.

Disable SWRevealViewController bouncing on addGestureRecognizer

I'm trying to use SWRevealViewController in my app which is sliding menu library, but i needed to edit the library with one option and i will explain as follows. when using addgestureRecognizer and opening the sliding-menu by keep on holding from the left to the most right and then left it,it bounce too much outside to the right then close the menu. i just need to disable this option from the library, just like to open to its normal limit without bouncing.

The link on GitHub is here : http://ift.tt/Jtzjj8

IOS line measurement on picture

I need some help to get started on drawing lines with circle at ends, and measure its length. I am able to draw the line but can't make it moving,having spent hours decided to post on SO.

So please see below image and guide me to get started. Any sample or tutorial using objective c will help.

enter image description here

EDIT: The answer posted by ndmeiri is making use of multi touch. It is really great but unfortunately this has to be achieved without making use of multi touch. The scenario is, at any given time there will be some flexible lines available on screen. User can just drag any end point to resize the line in any direction. I can't get this thing working correctly..

Here is my gist file, code allows me to resize the line with touch points but doesn't allow to change the angle of line and adding text in centre. http://ift.tt/1dp9Hm0

Any help is highly appreciated. Thanks :)

Hit button once to show UIImage. Hit button again to hide UIImage

i researched on this website but couldn't find anything to help me. I'm a beginner in coding so this may seem simple to some of you but hard for me. I have an instruction button in my game that i press to show a speech bubble giving the user instruction, i would like it so when i repress the instruction button, the speech bubble disappear.

.h

IBOutlet UIImageView *instructionsPic;
- (IBAction)instructionAction;

.m

- (IBAction)instructionAction {
instructionsPic.hidden = NO;
startGameButton.hidden = YES;

}

In my viewDidLoad i marked my instruction bubble speech as hidden and when the user hits the instruction button it shows up. So yea, how can i make it disappear again when they click the button again?

Thank you (:

Add calendar to iOS app

I am attempting to create an app of events where I add an event to my online database and it is added to the calendar of my application. So example, If i add "Party on the beach" in my db,set date to 25th June 2015. A user opening the application and navigating to "Events..selecting June" will see this on a calendar.

I am having a little trouble implementing something of the sort as all searches is leading me of how to sync my app with the native calendar app of the device which is not exactly what I want.

Basically I just want a calendar in my app which reads events from online.. Any assistance to point me in the right direction would be appreciated.

Edit I have a hosted database, what I am looking to find is some calendar that can read events from said database.

convert api string to JSON in swift or objective-c

hi i'm getting following string(text/html) not (text/JSON) when make api request.

 let request = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    let res =   NSString(data: data, encoding: NSUTF8StringEncoding)!
        var jsonStr = res

        //here 'res' will be {status: 1, userid: "447", store_code: "930"}

        var data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
        var localError: NSError?
        var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError)

        println("json res \(json)") // 'json' here is nil

        if let dict = json as? [String: AnyObject] {
             let weather = dict["status"] as? [AnyObject]
                println(weather)

        }

    }

//following is the text/html response from api request

{status: 1, userid: "447", store_code: "930"}

So how can i convert this text/html string to JSON.When i try to use NSJSONSerialization it gave fatal error or nil. Can anybody help me how can i solve this issue in swift or objective-c?

randomly change image of buttons and decelerate changing

i have 2 buttons.

they are called _rightButtonPressed and _leftButtonPressed. They have an background image named "blackBackground". When they are clicked, the background image is changed to "whiteBackground".

Ok. Now i want to make a third button, that changes the background image at first _rightButtonPressed to "white", then "black", then _leftButtonPressed to "white", then "black" and so on. This change have to decelerate to the end. At least, it should be randomly stops at a button with "white" background image and click the button. I hope its comprehensible.

I have no idea, how i can do this...

When programatically creating a ViewController, how can I set its view to be of type SKVIew?

I am developing a game in iOS on XCode. I have several SKScenes each associated with a UIViewController class. So in each of the view controller's viewDidLoad, I create

SKView *skView = (SKView *)self.view
SKScene * scene = [whateverSKScene sceneWithSize:skView.bounds.size]
[skView present scene]

I want to avoid the storyboard. However, when I presentViewController from the first view controller to the next, the app crashes at the line "[skView present scene]" because it thinks the new view controller's view is still UIView ('-[UIView presentScene:]: unrecognized selector sent to instance).

How can I fix this? Specifically, when creating the 2nd view controller (programatically), how can I change its view to be of type SKview not UIview? (I should note I want the scenes to be 1:1 with view controllers because almost all of them are popups like a pause-menu pop up over game play or settings pop up etc)

UIAlertView in superclass and subclass

I have a superclass where I sometimes show an UIAlertView and handles the delegation (clickedButtonAtIndex). When I then have a subclass that also handles the "clickedButtonAtIndex" only the subclass delegation is called.

In both cases the UIAlertView is show like this:

[[[UIAlertView alloc] initWithTitle:@"" message:@"message" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:@"Open", nil]show];

Am I doing something wrong or is it bad design to have the same delegation in both the superclass and subclass. I thought the "delegate:self" separated them.

How to convert UPC-A to UPC-E?

We would like to convert the 12 digit UPC-A to 8 digit UPC-E. Can you tell me which is the best way to do this without having to use my own code to convert?

I got many formula for convert the 8 digit UCC-E to 12 digit UPC-A but not reverse.

IOS: keyword search in a list of passages only returns the last match, instead of all matches

i have one passage list and from that i want to find out keyword search from user, passage ID getting over ride in array and because of that only last passage showing the result.

i want search keyword from all passage and show the result .

- (UIViewController*) showContentWithQuery:(NSDictionary*)query
{
ContentViewController * viewController = nil;
if (query)
{

    NSNumber * sectionId = query[@"sectionId"];
    NSNumber * passageId = query[@"passageId"];

    if (sectionId)
    {
        viewController = [[[ContentViewController alloc] initWithSectionId:sectionId] autorelease];

        if (passageId)
        {

            viewController.tempHighlightPassageArray = @[passageId];
        }
    }
}

return viewController;     }

iOS and unicode characters: \u+2605 not solid star in UILabel

I'm trying to make a UILabel that says "★ FEATURED". However, when it renders it, the star isn't solid! Here's the code I'm using:

    _sponsoredLabel = [UILabel new];
    _sponsoredLabel.numberOfLines = 1;
    _sponsoredLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _sponsoredLabel.textColor = [UIColor yellowColor];
    _sponsoredLabel.backgroundColor = [UIColor clearColor];
    _sponsoredLabel.textAlignment = NSTextAlignmentLeft;
    _sponsoredLabel.text = @"✭ FEATURED";
    _sponsoredLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0f];
    _sponsoredLabel.hidden = YES;

In the text itself it looks solid, but here's what it looks like when it renders:

Any advice is much appreciated!

Delay in Corelocation

I've created a helper class for my location needs so i don't violate the DRY principle. The class looks like this:
Location.h

@interface Location : NSObject <CLLocationManagerDelegate>{
CLLocationManager *manager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}

-(float)latitude;
-(float)longitude;
-(NSString *)postalcode;

Location.m

@implementation Location{
    float latitude;
    float longitude;
    NSString *postalcode;
}
-(id)init{
    NSLog(@"Hallo");
    [self setupLocationManager];
    return self;
}

-(float)latitude{

    return latitude;
}

-(float)longitude{

    return longitude;
}

-(NSString *)postalcode{

    return postalcode;
}

-(void)setupLocationManager{
    manager = [[CLLocationManager alloc] init];
    [manager requestWhenInUseAuthorization];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.distanceFilter = 100;
    [manager startUpdatingLocation];
    geocoder = [[CLGeocoder alloc] init];
 }

 #pragma mark - CLLocationManagerDelegate Methods

 - (void)locationManager:(CLLocationManager *)manager didFailWithError:          (NSError *)error
{

     NSLog(@"Error: %@", error);
     NSLog(@"Failed to get location! :(");

}

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

NSLog(@"Location: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {

    latitude = currentLocation.coordinate.latitude;
    longitude = currentLocation.coordinate.longitude;


}

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

    if (error == nil && [placemarks count] > 0) {

        placemark = [placemarks lastObject];
        postalcode = [NSString stringWithFormat:@"%@",placemark.postalCode];
        /*
         self.address.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
         placemark.subThoroughfare, placemark.thoroughfare,
         placemark.postalCode, placemark.locality,
         placemark.administrativeArea,
         placemark.country];
         */
    } else {

        NSLog(@"%@", error.debugDescription);

    }

} ];

}


 @end

When i in my ViewController tries to create an instance of Location and set latitude and longitude labels, in the viewDidLoad method, the labels are sat to 0.00000. Apparently it takes around half a second for Location to get the coordinates. I've tried using

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self setCoordinateLabels];
    });

But that just seems very hacky and can't possibly be the best practise? So is there any way i could do this a better way?

Saving OS X Game Data Using NSData and NSMutableArrays

I am trying to store the hi-score of several levels in a NSMutableArray, which will then be saved in a file in the Documents folder. I know I can use plists, but I don't want the content to be modified by the user. It appears that NSMutableArray *hiscore is not being initialized and I'm not sure how to fix this. For primitives it seems fine, but for objects it's not working.

GameData.h

@interface GameData : NSObject <NSCoding>

@property (assign, nonatomic) int level;
@property (assign, nonatomic) NSMutableArray *hiscore;

+(instancetype)sharedGameData;
-(void)save;
-(void)reset;

@end

GameData.m

#import "GameData.h"

@implementation GameData

static NSString* const GameDataLevelKey = @"level";
static NSString* const GameDataHiscoreKey = @"hiscore";

- (instancetype)initWithCoder:(NSCoder *)decoder {
    self = [self init];
    if (self) {
        _level = [decoder decodeDoubleForKey: GameDataLevelKey];
        _hiscore = [decoder decodeObjectForKey:GameDataHiscoreKey];
    }
    return self;
}

+ (instancetype)sharedGameData {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [self loadInstance];
    });

    return sharedInstance;
}

+(instancetype)loadInstance {
    NSData* decodedData = [NSData dataWithContentsOfFile: [GameData filePath]];
    if (decodedData) {
        GameData* gameData = [NSKeyedUnarchiver unarchiveObjectWithData:decodedData];
        return gameData;
    }

    return [[GameData alloc] init];
}

-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeDouble:self.level forKey: GameDataLevelKey];
    [encoder encodeObject:self.hiscore forKey:GameDataHiscoreKey];
}

+(NSString*)filePath {
    static NSString* filePath = nil;
    if (!filePath) {
        filePath =
        [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
         stringByAppendingPathComponent:@"gamedata"];
    }
    return filePath;
}

-(void)save {
    NSData* encodedData = [NSKeyedArchiver archivedDataWithRootObject: self];
    [encodedData writeToFile:[GameData filePath] atomically:YES];
    /*[_hiscore writeToFile:[GameData filePath] atomically:YES];*/
}

-(void)reset {
    self.level = 0;
}

@end

LevelScene.m

#import "GameData.h"
...
[[[GameData sharedGameData] hiscore] addObject:@1500];
[[GameData sharedGameData] save];

Correct pattern for mutable vs immutable

I'm wondering what the correct pattern for implementing Mutable vs Immutable data structures would be. I understand the concept and how it works, but how should I implement if using an underlying Cocoa data structure? I mean, if I use a NSSet, for instance. Lets say I have the following:

// MyDataStructure.h
@interface MyDataStructure : NSObject
@property (nonatomic, strong, readonly) NSSet * mySet;
@end


// MyDataStructure.m
@interface MyDataStructure ()
@property (nonatomic, strong) NSMutableSet * myMutableSet;
@end

@implementation MyDataStructure

- (NSSet *)mySet
{
    return [_myMutableSet copy];
}

@end

The only reason I'm using a mutable set as the underlying data structure,is so that the mutable version of this class can tamper with it. MyDataStructure per se does not really need a mutable set. Therefore, assuming that I have implemented some initialisers to make this class useful, here's how MyMutableDataStructure looks like:

// MyDataStructure.h (same .h as before)
@interface MyMutableDataStructure : MyDataStructure

- (void)addObject:(id)object;

@end

// MyDataStructure.m (same .m as before)
@implementation MyMutableDataStructure

- (void)addObject:(id)object
{
    [self.myMutableSet addObject:object];
}

@end

By using this pattern the underlying data structure is always mutable, and its immutable version is just an immutable copy (or is it??).

This also begs another question that arises when implementing the NSCopying protocol. Here's a sample implementation:

- (id)copyWithZone:(NSZone *)zone
{
    MyDataStructure * copy = [MyDataStructure allocWithZone:zone];
    copy->_myMutableSet = [_myMutableSet copyWithZone:zone];

    return copy;
}

Doesn't copyWithZone: return an immutable copy if that applies? So I'm basically assigning a NSSet instead to a NSMutableSet property, isn't that right?

Edit: While diving deeper into the issue I found some more issues surrounding this concern.

  1. mySet should be copy instead of strong.
  2. My copyWithZone: implementation isn't right either. I didn't mention it in the first post but that implementation relates to the Immutable version of the data structure (MyDataStructure). As I've read, Immutable data structures don't actually create a copy, they just return themselves. That makes sense.
  3. Because of 2., I needed to override copyWithZone: in the Mutable version (MyMutableDataStructure).

To make things clear:

// MyDataStructure.h
@property (nonatomic, copy, readonly) NSSet * mySet;

And

// MyDataStructure.m
@implementation MyDataStructure

- (id)copyWithZone:(NSZone *)zone
{
    // We don't really need a copy, it's Immutable
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    // I also implement -mutableCopyWithZone:, in which case an actual (mutable) copy is returned
    MyDataStructure * copy = [MyMutableDataStructure allocWithZone:zone];
    copy-> _myMutableSet = [_myMutableSet mutableCopyWithZone:zone];

    return copy;
}

@end

@implementation MyMutableDataStructure

- (id)copyWithZone:(NSZone *)zone
{
    return [self mutableCopyWithZone:zone];
}

@end

It seems tricky at first, but I think I'm getting the hang of it. So the remaining questions are:

  1. Is the pattern correct?
  2. Does the getter for mySet return a mutable or immutable instance?
  3. (not listed before) Do I really need the copy signal when using the copy property attribute?

I appreciate your patience to read this far. Best.

Sharing of Image and text with Deep linking on facebook in ios8

Have anyone worked on deep linking in ios 8? I tried to follow facebook.developer tutorial to implement deep linking but is not so much clear. please suggest me any blog and tutorial or sample code. Any help will be appriceate. Thanks in advance!

How to change duration of ImageView in Objective-C

I am creating a simple camera app for a photobooth. This code below is a sample of the whole project, I am using AVFoundation because I needed my own custom requirements.

When the user presses a button, it takes a photo and instantly shows the preview in the imageView. This is my first major coding project and am new to Objective-C. Is there a way to add a timer or duration to the imageView so that it then removes the image from it, or a way to cycle to a second black image after some time, ready for the next user to take their photo?

Many thanks for any help suggested!

- (IBAction)takephoto:(id)sender {

    AVCaptureConnection *videoConnection = nil;

    for (AVCaptureConnection *connection in StillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts ]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
    }
    [StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer != NULL) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            imageView.image = image;
        }
    }];
}

How to add collection view programmatically in iOS

i want to add UICollectionview when i click on a button.. The default screen has table view already. I am adding grid option button and want to arrange data in grid by collection view when user click on grid button

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

samedi 9 mai 2015

WebsitePanel database restore

I want to be able to use the Database restore option from WebsitePanel.

When I try to restore a database from the hosting space I get "The operation has timed out" exception.

Where can I change the timeout settings (I have dedicated server and have the appropriate permissions)?

The full stack trace is following:

Stack Trace:    System.Net.WebException: The operation has timed out 
at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) 
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) 
at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at WebsitePanel.EnterpriseServer.esDatabaseServers.RestoreSqlDatabase(Int32 itemId, String[] uploadedFiles, String[] packageFiles) 
at WebsitePanel.Portal.SqlRestoreDatabase.RestoreDatabase()

Author and viewer permissions to an article

I am building a Django web application which will contain articles that will only be shared with specific users that the author chooses. It is trivial to give the author the rights to edit the article, however I am trying to find the best way to limit the users that can view the article. I am considering creating a group per article and adding users to that group, however as there will be thousands of articles this will mean making thousands of groups. Also I would have to write code that would programmatically generate the group name and associate it with the specific article.

The alternative approach would be to associate the articles that a user has permission to view with the users profile.

Is there a best practice way to do this? I have researched extensively users and roles but I have been unable to find any articles that discuss this specific situation.

Thank you.

Rails 4: sometimes records are saved and sometimes they are not?

I have a weird thing happening. I have a Model call Recipe that has_many :informations and :directions. When I try to save the @recipe (see my controller) with its many :informations and :directions; sometimes it works and sometimes it does not without me changing anything to the source code.

Also, the :informations are always saved; the problem seems to only be regarding the :directions

Here is my controller:

    def new
        @recipe = current_user.recipes.new
    end

    def create
        @recipe = current_user.recipes.new(recipe_params)

        if @recipe.save
            redirect_to @recipe, notice: "Successfully created new recipe"
        else
            render 'new'
        end
    end     
    private

    def recipe_params
        params.require(:recipe).permit(:category_id, :title, :description, informations_attributes: [:id, :title, :url, :_destroy], directions_attributes: [:id, :title, :url, :step, :_destroy])
    end
end

When I try to save from my form here are the params:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"wfa+wTI+C3hnvscAC1O922EYlssJE3zAbEmmqMbmR+5krb0b17fkWhsXVAW1aFcom8x11uGqGO6drQudGhdcvA==", "recipe"=>{"title"=>"test", "description"=>"test", "category_id"=>"3", "informations_attributes"=>{"1431197959831"=>{"title"=>"test", "url"=>"dede", "_destroy"=>"false"}, "1431197959835"=>{"title"=>"ded", "url"=>"dede", "_destroy"=>"false"}}, "directions_attributes"=>{"1431197963709"=>{"title"=>"dede", "url"=>"dede", "step"=>"de", "_destroy"=>"false"}, "1431197963712"=>{"title"=>"ded", "url"=>"ded", "step"=>"ded", "_destroy"=>"false"}}}, "commit"=>"Create Theme"}

Shema:

  create_table "directions", force: :cascade do |t|
    t.text     "step"
    t.integer  "recipe_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "url"
    t.string   "title"
  end


  create_table "information", force: :cascade do |t|
    t.string   "url"
    t.integer  "recipe_id"
    t.datetime "created_at",                            null: false
    t.datetime "updated_at",                            null: false
    t.integer  "cached_votes_total",      default: 0
    t.integer  "cached_votes_score",      default: 0
    t.integer  "cached_votes_up",         default: 0
    t.integer  "cached_votes_down",       default: 0
    t.integer  "cached_weighted_score",   default: 0
    t.integer  "cached_weighted_total",   default: 0
    t.float    "cached_weighted_average", default: 0.0
    t.string   "title"
  end


  create_table "recipes", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.integer  "user_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
  end

Thanks for your help !

Android SQLite database contains only null values

I am trying to insert the values from an array into SQLite database. The problem is that the function can insert only null values even though the array does not contain such values.

The function for insert :

public void addArrayEntry(String [] response){
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        //System.out.println(response.length);
        for (int i=1; i<response.length; i++){
            values.put(temperature,response[i]);
            db.insert(tableStatistics,null,values);
        }

        db.close();
    }

    catch (Exception e){
        Log.e("Error in insert", e.toString());
    }

}

String createTable = "CREATE TABLE statistics ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "temperature REAL, "+
            "light INTEGER, "+
            "humidity INTEGER)";

Array values :

05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 23.798828125
05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 744
05-08 14:24:21.405 10720-10720/org.security.andreiism.iotsecurity I/System.out﹕ 424

SQL Trigger: Inserting a row in a table after an insert on another table, if a given value doesn't already exist in the first table

As the title says, I'm trying to insert a row in one table, triggered after an insertion on another table, but only if a given value doesn't already exist in the first table.

Example:

I have one table, countries, which stores countries and their id's:

Countries

id   country 
1    England 
2    France  
...  ...    

I have another table, events, which stores information about events as follows:

Events

id  timestamp   city    country
1   13435636    London  England
2   45635742    Paris   France
... ... ... ...

What I want to do: create a trigger so that after an insertion on the events table, insert a new row in the countries table with the country that the event occurred in, but only if that country doesn't already exist in the countries table.

What I have tried:

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    INSERT INTO countries (country) VALUES (New.country)
    WHERE NOT EXISTS (SELECT country FROM countries WHERE country = New.country)

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
    BEGIN
        INSERT INTO countries (country) VALUES (New.country)
    END

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
        INSERT INTO countries (country) VALUES (New.country)

Along with some other variations, and all I get are syntax errors (error #1064).

VB.Net DataGridView Filtering

I have a "DataGridView". And I want to make a filter system with 2 "ComboBox" and 1 "Button".

Column 1 - Column 2
Yes - True
No - Wrong

Let's say this is my table. And My first ComboBox is for "Column 1". When user choose "No" on "ComboBox1" I want to delete others (except no, we want no).

Can not unpin the object until it is saved on parse server using Android-Parse-SDK

I can not unpin my object from local database until it is saved on backend. I save object to local database then call object.saveEventually() like this

object.pinInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if(e == null) {

                                object.saveEventually(new SaveCallback() {
                                    @Override
                                    public void done(ParseException e) {
                                        if(e == null) {
                                            Toast.makeText(AppContext.get(), "Object Saved On Parse", Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(AppContext.get(), "Object Not Saved On Parse", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });

                            }
                        }
                    });

if i want to unpin this object before internet connection back and object is saved on back-end what should i do. I tried this but it's not working:

object.unpinInBackground(new DeleteCallback() {
                            @Override
                            public void done(ParseException e) {
                                if(e == null) {
                                    Toast.makeText(getActivity(), getResources().getString(R.string.object_deleted),
                                            Toast.LENGTH_SHORT).show();
                                    updateObjectsList();
                                } else {
                                    Toast.makeText(getActivity(), getResources().getString(R.string.object_not_deleted),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

How i can cancel object.saveEventually()?

Insert to database without duplicate in php

How can I insert data to database without duplicate of the name for example if the name found in database show message how can do this??

<?php
$username ="root";
$password ="";
$hostname="localhost";
$db="a";
$dbhandle=mysql_connect($hostname ,$username ,$password,$db)or die('not connect to the database because:'.mysql_error());
 mysql_select_db($db,$dbhandle);
 $myusername=$_POST['user'];
$mypassword=$_POST['pass'];
$mypassword_conf=$_POST['Password_conff'];
if($mypassword==$mypassword_conf)
{
$sql="INSERT INTO aa( username, password,pass_con) VALUES 
('$myusername','$mypassword','$mypassword_conf')";
   if(! mysql_query($sql,$dbhandle))
      echo "not insert";
      else
         echo "insert is Done";

          mysql_close();

           }
else
{
    echo "not insert to db found error";
}

?>

Local database choice (Windows Phone 8.1 application)

I am in the process of making a relatively complex Windows Phone 8.1 application and I need a way to store data from server's database into a local database. Data from server is retrieved in JSON format via API. What are my options here? I've tried SQLite database controlled by sqlite-net but it lacks key features such as foreign keys support and 64bit support (?). What other choices do I have? Local database is used in order to give the user ability to work offline and later sync the data from local database with server's database.

Low Level Design for a notification System

We are building a notification system on an existing legacy stack of Codeigniter and MySQL. The case is like this : A notification is send to say 100K users. There are two tables in the DB

1) Messages ( Message ID, Phone ) 2) Status ( Phone, Message ID, Status )

When a message is sent there is single insert happening in messages table which holds phones in comma separated format. And when actually message starts sending ( say via some wrapper on google cloud messaging ) an insert happens in status table. Hence for a single notification to 100K users there can be 1 and 100K inserts respectively. The status table further receives updates from devices to change the status to say READ/ DELIVERED etc.

This doesn't look like a great architecture and would MySQL be able to handle that high volume of inserts ( say batched as well ). Any alternative low level design using the same tech stack or an alternate data store ( cassandra, elastic search ) should be an appropriate fit for this ?

Can't connect to database on notepad++

I can connect to my database just fine when I'm on my website, but when I'm on my notepad++, and I tried to connect to my database, I get the error below. I have XAMPP installed, and apache is working smoothly, but the only thing is that I can't connect to the database while in the notepad++, and yet it works when I'm on my website. All the files are copied from my website, so there is no discrepancy between the files on my website, and the files on my notepad++. I use localhost to get to the index of my page using notepad++, and it works fine. Only when I tried to register information to my database did the error below show up. Please help. Thanks.

Warning: mysql_connect(): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in E:\xampp\htdocs\iscattered\register.php on line 3 Not connect :A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

<?php

$var = mysql_connect('mysql2.000webhost.com','username','password');

if(!$var){

die('Not connect :'  . mysql_error());

}

$database = mysql_select_db("database",$var);
if(!database){

die("Can't connect : " . mysql_error());

}

?>

Regular Expression "a{2}" not working

I have a record with emp_name = "Rajat" and it is not getting returned.

My query is -

select * from employees where emp_name regexp "a{2}"

Please explain why it is not working

create two foreign key from one table sql server

i am creating user table like code PK Table

CREATE TABLE TblUser (UserId int identity primary key ,Name varchar(20))

AND creating one more table FK Table

CREATE TABLE TblAnnouncements (Id int identity primary key ,Announcements 
varchar(20),CreatedBy INT FOREIGN KEY REFERENCES TblUser (USERID)  ON  DELETE  
CASCADE, UpdatedBy INT FOREIGN KEY REFERENCES TblUser (USERID)  ON DELETE  SET NULL)

i am getting this error

Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'FK__TblAnnoun__Updat__60A75C0F' on table 'TblAnnouncements' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

how to maintain createdby and updatedby in an table....

can you give suggest me any other way to do that ?

thank u.

Execute complex SQL queries in VB.NET

I'm having trouble executing a complex SQL query in VB.NET using OledbDataAdapter. This SQl query works fine in the W3school's SQL Tryit Editor. Following is my existing VB.NET code and is there any way to execute that kind of a SQL query directly in VB.NET or can anyone change this query to work with VB.NET with same results?.

    Dim con As New OleDb.OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter
    Dim sql As String

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = C:\database.mdb"
    con.ConnectionString = dbProvider & dbSource
    con.Open()
    sql = "With query1 as (SELECT Val,DateAndTime FROM [FloatTable] where TagIndex='0'),Query2 as (SELECT Val,DateAndTime FROM [FloatTable] where TagIndex='1')select query1.val as 'TT348',Query2.val as 'TT358',Query2.DateAndTime as 'DateAndTime' From query1,Query2 where query1.DateAndTime=Query2.DateAndTime"
    da = New OleDb.OleDbDataAdapter(sql, con)

    da.Fill(ds, "Log")
    con.Close()

    DataGridView1.DataSource = ds

When I run this code snippet it gives an error telling

Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

Greatly appreciate any help and thank you...

Writes to database seem to have no effect

I am working with an ASP.NET web application written in C# deployed to IIS/Windows Server 2008 R2. The application uses NHibernate to interact with an Oracle database running on a networked unix server.

It seems that writes being made by the application to the database have no effect.

If I manually edit the value of a record in the Oracle database, the new value is reflected by the application. However, if I attempt to change a value using the application’s custom “save” functionality, the changes are not reflected in the database. It seems like reads are succeeding, but writes are failing.

Why do writes seem to be failing?

More information:

No obvious error messages are received (ie. the application does not throw an exception and it seems to continue running as if everything is fine).

Another instance of this application is running on IIS/Windows Server 2003. This instance can write to the Oracle database (ie. the changes can immediately be seen in the database by using a database viewer after clicking “save”).

The code is virtually identical between the 2003/2008 applications. However, on the 2008 server, I am using newer versions of Oracle libraries and I changed to target architecture of the visual studio projects from ‘Any CPU’ to ‘x86’ (the 2008 server is 64-bit while the 2003 server is 32-bit).

Disclaimer:

I have very limited experience working with IIS, NHibernate, Oracle databases, Windows Server 2003, and Windows Server 2008 R2. I do, however, have slightly more experience working with C#, ASP.NET web applications, Visual Studio, and MSSQL databases).

Phalcon data migrations separated from schema migrations

Using Phalcon framework and its migrations system, for testing purposes, I need to be able to execute the schema migrations separately from the data migrations.

What I want to do is to have a separate data migrations folder, so on my testing environment I would apply only the schema migrations (for testing purposes, tables should be empty and only populated by fixtures), but on my staging and production environments the data migrations would be applied as soon as the schema migrations are done.

I don't find a way to have two separated sets of migrations in Phalcon. How can I do it?

Choosing the right database index type

I have a very simple Mongo database for a personal nodejs project. It's basically just records of registered users.

My most important field is an alpha-numeric string (let's call it user_id and assume it can't be only numeric) of about differing from about 15 to 20 characters.

Now the most important operation is checking if the user exists at or all not. I do this by querying db.collection.find("user_id": "testuser-123"

if no record returns, I save the user along with some other not so important data like first name, last and signup date.

Now I obviously want to make user_id an index. I read the Indexing Tutorials on the official MongoDB Manual.

First I tried setting a text index because I thought that would fit the alpha-numeric field. I also tried setting language:none. But it turned out that my query returned in ~12ms instead of 6ms without indexing.

Then I tried just setting an ordered index like {user_id: 1}, but I haven't seen any difference.

Can anyone recommend me the best type of index for this case or quickest query to check if the user exists? Or maybe is MongoDB not the best match for this?

Weird 'returned data that does not match expected data length for column' error while the expected length is much bigger - SQL SERVER 2012

In my project I am rebuilding my Access database to an SQL Database. So to do this I am transferring the Access DATA to the SQL Database. I made sure they both have the same structure and the Access fields are modified correctly in the SQL database.

For most of the data this works. Except for 1 table. This table gives me the following weird error message:

OLE DB provider 'Microsoft.ACE.OLEDB.12.0' for linked server 'OPS_JMD_UPDATE' returned data that does not match expected data length for column '[OPS_JMD_UPDATE]...[OrderStatus].Omschrijving'. The (maximum) expected data length is 100, while the returned data length is 21.

So here some more information about both the Access and SQL field/column:

  • Access type: Short text
  • SQL type: nvarchar(MAX)
  • Access column data in it: Normal letters and & - % é + . , : being the 'not normal ones'.
  • A few empty Access records (which is allowed)
  • A total of 135314 record in the Access table

Iv'e set the SQL datatype to nvarchar(MAX) so that the field can never be to small, this didn't seem to help though..

*The OPS_JMD_UPDATE is the linked Access database

What causes this problem? Is it because some characters aren't allowed or..?

AngularJS: Display only first row on ng-repeat not first index

I have two dynamic dropdowns that display a list of data from the database, and refreshes the list on every 'branch' change:

<select id="regions" class="form-control" ng-model="formData.location" required ng-options="rg as rg.type for rg in region">
    <option value="">Choose Location</option>
</select>

<select id="branches" class="form-control" ng-model="formData.branches" required ng-options="c as c[formData.location.displayName] for c in formData.location.data | orderBy:'branch'">
    <option value="">Choose Branch</option>
</select>

displaying by ng-repeat:

<div ng-repeat="codes in response">
  <span ng-if="((codes.branch == formData.branches.alias) && (codes.taken == 0))">
  {{codes.code}}
</div>

I am trying to limit the display of each to just one using limitTo:1. The problem is, this filter only displays the first row from the table. Is there a filter that displays the first child of the displayed list, instead of the first index of the entire list from the database?

Note that the list refreshes a new list from the database each time the branch dropdown switch values.

how can i update a value in record when the date/time match the date/time stored in the record itself

I have the following table

my_table

date | time | status

now my first question is: i need to change a status column from zero to one when the date and time match the date and time of the record which is specified by the user when he/she inserted the record.

second question: when user choose date and time he/she will choose it depends on their time zone so how this will effect if the PHPMyAdmin use different time zone ?

When i send data from a form to access database the first item always replace the first line in database

When i send data from a form to access database the first item always replace the first line in database and as a result when i run the form again it replaces the first item and i loose that data. My code:

this.asfalistratableBindingSource.EndEdit();
this.asfalistratableTableAdapter.Update(this.asfalistradbDataSet.asfalistratable);
this.asfalistratableBindingSource.AddNew();

Rails with Stripe Checkout: How can i seed my db with sample charges and use stripe checkout to generate tokens for each charge?

So I have a rails app that takes donations for a fund raising project using stripe checkout. I save the stripetokens to my db, and then go back and process them all at once if the project funding goal is met (sorta like kickstarter). I've figured out how to do this and have tested my code on a small number of charges (say like 10) without any problems. Here's my code

@project = Project.find(set_project)

# Create new stripe customer
    @customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :card => params[:stripeToken]
        )

# Create new charge
    @charge = Charge.new(
        :email => params[:stripeEmail],
        :stripe_token => params[:stripeToken],
        :project_id => @project.id,
        :amount => params[:amount],
        :customer_id => @customer.id
        )
#Save charge to my db
@charge.save

Then in my project model

# Cycle through all charges for project and process using 
# stripe token and stripe customer id
def charge
    self.charges.each do |x|
        begin
            Stripe::Charge.create(
                :amount => x.amount,
                :currency => 'usd',
                :customer => x.customer_id
            )
        rescue Stripe::CardError => e
            x.error = e
        else
            x.processed = true
            x.save
        end
    end
end

Now here's my question. I want to be able to test this code at higher volumes of charges. How can I seed my db with 1,000 or more sample charges and use the stripe checkout script to create a customer and generate tokens for each one?

Exception during connecting to postgresql database using wt c++ library?

I`m trying to connect to postgresql database which name is "galaxydatabase" and I encountered an unhandled exception. Source code:

#include <Wt/Dbo/Dbo>
#include <Wt/Dbo/backend/Postgres>

namespace dbo = Wt::Dbo;

void run()
{
    dbo::backend::Postgres po;
    po.connect("galaxydatabase");
    // or
    //dbo::backend::Postgres po("galaxydatabase"); // the same exception???
}

int main(int argc, char **argv)
{
    run();
}

Password to the database is "dbpass". I don`t know where put this password in the code?

Duplicate entry for key "PRIMARY" in MySQL

Query for creating table :

create table if not exists person ( 
roll_no int(4) AUTO_INCREMENT primary key,
name varchar(25),  
city varchar(25));

Query to set start number for auto-increment primary key :

alter table person auto_increment = 1;

Query to insert data :

insert into person (name,city) values("Maxwell", "Pune");
insert into person (name,city) values("Baldwin", "Bengaluru");
insert into person (name,city) values("Novartis", "Paris");
insert into person (name,city) values("Shaun", "Mumbai");
insert into person (name,city) values("Beckham", "Toronto");
insert into person (name,city) values("Ashish", "Bengaluru");
insert into person (name,city) values("David", "Paris");
insert into person (name,city) values("PK", "London");
insert into person (name,city) values("Chris", "Bengaluru");
insert into person (name,city) values("Aston", "Mumbai");

Query to delete the row :

delete from person where roll_no=5;

Table structure after deleting the row:

roll_no      name       city
1            Maxwell    Pune
2            Baldwin    Bengaluru
3            Novartis   Paris
4            Shaun      Mumbai
6            Ashish     Bengaluru
7            David      Paris
8            PK         London
9            Chris      Bengaluru
10           Aston      Mumbai

Now, while looking to reinstate the deleted row, the compiler is throwing error as " Duplicate entry '5' for key 'PRIMARY' "

Query used to re-instate the deleted row.

update person set roll_no = roll_no + 1 where roll_no >=4 order by roll_no desc;
insert into person (roll_no, name, city) VALUES (5, "Beckham", "Toronto");

What could be the possible reason for this issue ? Any inputs would be highly recommended.

Sqlite Table Create Syntax Error

I am just trying to get text from a JtextField and I want to implement it inside a sql injection to create a table. Here is my code: try { Class.forName("org.sqlite.JDBC"); conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//Admin.sqlite");

                  stmt = conni.createStatement();


                  String sql =  "CREATE TABLE" + projectname.getText() + 
                               "(ID INT PRIMARY KEY     NOT NULL,"  + 
                               " NAME           TEXT    NOT NULL, " +
                               " EstQuantity            INT     NOT NULL, " +
                               " UnitPrice        CHAR(50), " +
                               " TotalPrice         REAL)"; 

                  stmt.executeUpdate(sql);
                  stmt.close();
                  conni.close();
                } catch ( Exception e ) {
                  System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                  System.exit(0);
                }
                JOptionPane.showMessageDialog(null, "Project Created!");

This is the basic structure. When I input my table name it says java.sql.SQLException: near "(my input)CREATE": syntax error Please help!

I'am getting error

NoMethodError in Data#input

Showing /home/adijanuarsyah/Projects/Food/app/views/data/_idfood.html.erb

where line #8 raised:

undefined method `find' for #<TopFood:0x007fdfd558fa90>

When i'am used find method for getting query food = foods.find(rand_number) i'am getting error like above , but when using TopFood.find(rand_number), its working perfectly.

Here is my view

<h2>Suggestion Indonesian top dishes</h2>
<ul id="foodList">

        <% TopFood.where(:country => "ind").find_each do |foods |  %> 
        <% rand_number = rand(52) + 1 %> 
            <% @food = foods.find(rand_number)%>
                <li><%= @food.name  %></li> 
            <% puts @food.inspect %> 
    <% end %>

</ul>
<div id="loadMore">More sugesstions</div>
<div id="showLess">Show less</div>

Any clue as to what is going on here?

Thanks.

Cannot add foreign key constraint 2

im try create a foreign key to Poblacion, on table cp_cliente, but i cant, i take the error "cannot add foreign key", im try change the name, but i cant. If i delete Poblacion foreign key the script work fine.

CREATE TABLE provincias (

Cod_provincia INT(2) PRIMARY KEY,

Provincia VARCHAR(50) NOT NULL );

CREATE TABLE cp_cliente (

CP CHAR(5),

Cod_provincia INT(2),

Poblacion VARCHAR(70),

PRIMARY KEY (CP, Poblacion, Cod_provincia),

FOREIGN KEY (Cod_provincia) REFERENCES provincias(Cod_provincia) ON DELETE CASCADE ON UPDATE CASCADE );

CREATE TABLE cliente (

DNI CHAR(9) PRIMARY KEY,

Nombre VARCHAR(20) NOT NULL,

Apellidos VARCHAR(20) NOT NULL,

Direccion VARCHAR(50) NOT NULL,

CP CHAR(5),

Cod_provincia INT(2),

Poblacion VARCHAR(70),

FOREIGN KEY (CP) REFERENCES cp_cliente(CP) ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Cod_provincia) REFERENCES cp_cliente(Cod_provincia) ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Poblacion) REFERENCES cp_cliente(Poblacion) ON DELETE SET NULL ON UPDATE CASCADE );

What is the problem? I can't see him :(

Sorry my bad english.

How sql with-recursive statement interpreted?

My sources : Hello there.

I would like to ask get some help about understanding how "with recursive" works. More precisely WHY the anchor query (the non-recursive term) isn't replicated into the sub call of the CTE. I tried my best to understand alone but i'm not sure.

First of all let's take the example of PostgreSQL which is the simpliest one i found (make the sum of 1 to 100) :

WITH RECURSIVE t(n) AS (
      VALUES (1)
      UNION ALL
        SELECT n+1 FROM t WHERE n < 100)

    SELECT sum(n) FROM t;

My Code walkthrough ( I used links below) :

" 1. Evaluate the non-recursive term. For UNION [...]. Include all remaining rows in the result of the recursive query, and also place them in a temporary working table.

  1. So long as the working table is not empty, repeat these steps:

    • Evaluate the recursive term, substituting the current contents of the working table for the recursive self-reference. For UNION [...]. Include all remaining rows in the result of the recursive query, and also place them in a temporary intermediate table.

    • Replace the contents of the working table with the contents of the intermediate table, then empty the intermediate table."

LVL 0 :

  1. non-recursive part

    • CTE : (N) 1
    • WORKING TABLE : (N) 1
  2. recursive part

    • CTE : (N) 1
    • WORKING TABLE : (N) 1
    • INTERMEDIATE TABLE (N) 2

(this is the part i mess around i think) - subsitution of WORKING TABLE

so the recursive t will use WORKING TABLE to do SELECT n+1 and put the result in INTERMEDIATE TABLE.

  1. UNION ALL

    • CTE : (N) 1 2
    • WORKING TABLE : (N) 2
    • INTERMEDIATE TABLE : CLEANED

      1. Then we go into the next lvl by the call of t right? (because END condition WHERE n < 100 = FALSE)

LVL 1 :

We know coz postgreSQL says it "So long as the working table is not empty, repeat the recursive steps" So it will repeat the step 2. and 3. (if i'm correct) until END condition then do the SUM.

BUT if I just walkthrough the call of the next lvl of t should we not do VALUES(1) first ?

I'm really confused about how it is possible.

Best regards, Falt4rm