jeudi 30 juin 2016

How Does Allocated Memory Get Freed In C++?

Let's say I have a header file, armorshop.h, containing a class definition, along with a corresponding .cpp for this header file.

My question is:

  1. How does allocated memory get freed in c++?
  2. Will allocatedmemory1, allocatedmemory2, allocatedmemory3, or allocatedmemory4 ever be freed on its own in each of these scenarios?
  3. Will these aformentioned allocatedmemories be redefined and cause an error in each of these scenarios?
  4. Do variables and classes, etc defined inside of a class definition get freed when they are not being used, and redefined when they are used again? Or do they get defined once and use up resources while not being used?

Thanks

//scenario 1
//armorshop.h
#ifndef __SFML__armorshop__
#define __SFML__armorshop__


class armorshop : public entity
{
public:

};

int allocatedmemory1;
sf::FloatRect allocatedmemory2;
class armorshop allocatedmemory3;
std::vector<armorshop> allocatedmemory4;

#endif

(question 3 clarification in relation to scenario 1:) If I #include "armorshop.h" multiple times will this cause an error

//scenario 2
//armorshop.cpp
int allocatedmemory1;
sf::FloatRect allocatedmemory2;
class armorshop allocatedmemory3;
std::vector<armorshop> allocatedmemory4;

Segmentation fault in wildcard pattern matching

I am getting Segmentation fault in wildcard pattern matching in interviewBit and i seeked Help only to get no response by now. I am using DP to solve the task. Please help me figure out the reason of The segFault Link to the problem -- https://www.interviewbit.com/problems/regular-expression-match/

Here is my solution getting segFault in C++ .

int Solution::isMatch(const string &s, const string &p) {

    int n=s.size(),m=p.size();
    bool dp[n+1][m+1];

   for(int i=0;i<=n;i++)for(int j=0;j<=m;j++)dp[i][j]=false;
   dp[0][0]=true;

   for(int j=1;j<=m;j++)
      if(p[j-1]=='*')dp[0][j]=dp[0][j-1];

   for(int i=1;i<=n;i++)
   {
      for(int j=1;j<=m;j++)
      {
         if(s[i-1]==p[j-1] || p[j-1]=='?')dp[i][j]=dp[i-1][j-1];
         else if(p[j-1]=='*')
         {
            int v1=dp[i][j-1],v2=0;// Not Using
            v2=(dp[i-1][j]|dp[i][j-1]);
            dp[i][j]=(v1|v2);
         }
         else dp[i][j]=false;
      }
   } 
   return dp[n][m];
}

What happens to the value of a floating point number when it's assigned it to a double?

Note: I'm currently working in C++11 and using GCC to compile.

I'm dealing with a situation where the result varies between the below two calculations:

value1 = x * 6.0;

double six = 6.0;
value2 = x * six;

value1 != value2

Where all variables above are of type double.

Essentially, I wrote a line of code that gives me an incorrect answer when I use 6.0 in the actual calculation. Whereas, if I assign 6.0 to a variable of type double first then use the double in the calculation I receive the correct result.

I understand the basics of floating point arithmetic, and I guess it's obvious that something is happening to the bits of 6.0 when it is assigned to the double type.

Question: Why are the above two code segments producing (slightly) different results?

Note: I'm not simply comparing the two numbers with == and receiving false. I've just been printing them out using setprecision and checking each digit.

SMS/Message Receiving Client w/ Twilio for iOS/Swift

I am trying to write an iOS application that is able to read in/display messages received to a Twilio number. I have searched around a bit for my question, but am not sure I understand completely what I have found. Does anyone have any suggestions/similar scenarios or resources that they might be able to assist me with, please?

Their might be a better way to do what I am trying to do, so I am also open to suggestions. I have a Python application running in the background on a Raspberry Pi that currently sends me a text (sends it from my Twilio number) whenever it is triggered. With my new application, I would be sending the message from my Twilio number on the Python application, and receiving it on my Twilio number as well (so basically texting myself). I am not sure this is the best way to do what I want, but I couldn't find anything with Google Voice messages either.

My second approach would be to find a database that Python is able to push to and that Swift can pull from. I appreciate any help or suggestions, thanks!

Reasons for using Variable Argument Lists versus vector (c++)

I am trying to understand Variable Argument Lists (varargs). I have previously used pointers and/or std::vector for parameters which can change in the amount of objects that need to be passed.

I would expect that Varargs (1,2) and Vectors (3,4) as part of function parameters both have their own special uses in C++ and are better at different things. However, I am having a difficult time distinguishing when std::vector is not the right choice. Could this please be explained?

Is this the type of scenario where varargs might be preferred?

union S //Using union from http://en.cppreference.com/w/cpp/language/union
{
    std::int32_t n;     // occupies 4 bytes
    std::uint16_t s[2]; // occupies 4 bytes
    std::uint8_t c;     // occupies 1 byte
};                      // the whole union occupies 4 bytes


int myFunction(std::vector<S> v)

TFHpple randomly crashes in iOS

My app is simple. It reads the stock symbol (AAPL) from Yahoo Finance and gets the price. Every half of a second it refreshes the stock price. Sometimes it crashes, can anyone help explain this to me, as to why it crashes. I get the error "unable to parse"

#import "ViewController.h"
#import "TFHpple.h"

@interface ViewController ()

@property UILabel *stockStymbol;
@property UILabel *stockPrice;

@end
//@"http://finance.yahoo.com/q?s=AAPL"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _stockStymbol = [[UILabel alloc]init];
    _stockPrice   = [[UILabel alloc]init];


    [self parseStockSymbol];

    [NSTimer scheduledTimerWithTimeInterval:0.5f
                                     target:self
                                   selector:@selector(parseStockSymbol)
                                   userInfo:nil repeats:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) parseStockSymbol

{

    NSURL* baseURL = [NSURL URLWithString:@"http://finance.yahoo.com/q?s=AAPL"];
    NSData *data = [[NSData alloc]initWithContentsOfURL:baseURL];

    TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:data];

    NSArray *elements  = [xpathParser searchWithXPathQuery:@"//span[@class='time_rtq_ticker']"];
    TFHppleElement *element = [elements objectAtIndex:0];

    _stockStymbol.text = @"AAPL";
    [_stockStymbol sizeToFit];
    _stockPrice.text = [[element firstChild]content];
    [_stockPrice sizeToFit];


    _stockPrice.frame = CGRectMake(100, 30, _stockPrice.bounds.size.width, _stockPrice.bounds.size.height);

      _stockStymbol.frame = CGRectMake(30, 30, _stockStymbol.bounds.size.width, _stockStymbol.bounds.size.height);


    [self.view addSubview:_stockStymbol];
    [self.view addSubview:_stockPrice];

}


@end

Check which ViewController made a segue (from the destination ViewController)

I have a code that gives random segues to my 12 ViewControllers.

In ViewController1 it looks like this;

let segues = ["1-2", "1-3", "1-4", "1-5", "1-6", "1-7", "1-8", "1-9", "1-10", "1-11", "1-12"]
        let index = Int(arc4random_uniform(UInt32(segues.count)))
        let segueName = segues[index]
        self.performSegueWithIdentifier(segueName, sender: self)

And in ViewController 2 it looks the same, but the segue names change to;

let segues = ["2-1", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9", "2-10", "2-11", "2-12"]

(The "1" changes into a "2") - and so forth for all 12 ViewControllers.

.

Now, what I want to do is delete the ViewControllers that has already been shown, so that the next segue won't go back to any of the previous ViewControllers.

Example:

• ViewController1 makes a segue to ViewController2 ("1-2")

• ViewController2 deletes the segue "2-1" from the array segues

• ViewController2 then makes a segue to ViewController3 "1-3"

• ViewController3 deletes the segue "3-1" and "3-2"

and so on...

How to set up an action with UIBarButtonItem made in Storyboard

I know if I were to do so programmatically, I would create the action menu item with:

share = UIBarButtonItem(
                title: "Continue",
                style: .Plain,
                target: self,
                action: "Pun"

I am trying to do so using the storyboard. Is there a simple way of doing this? I am trying to create a share button that will copy a string and prompt the user to share it (via email, printer, etc.). Thanks. Here is my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let btn1 = UIButton(frame: CGRect(x: 0, y: 0, width:100, height: 50))

    @IBOutlet weak var share: UIBarButtonItem!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        btn1.backgroundColor = UIColor.clearColor()
        btn1.layer.cornerRadius = 5
        btn1.layer.borderWidth = 1
        btn1.layer.borderColor = UIColor.redColor().CGColor

        btn1.setTitle("1", forState: .Normal)


        scrollView.addSubview(btn1)
        scrollView.contentSize.height = 900

        /*share = UIBarButtonItem(
            title: "Continue",
            style: .Plain,
            target: self,
            action: "Pun"
        )*/



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Add this
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        var newFrame = btn1.frame
        newFrame.size.width = scrollView.bounds.width
        btn1.frame = newFrame
    }


}

Swift: Getting 'Snapshotting a view that has not been rendered..' error when trying to open a URL in safari from my app

One of the specifications of my app is that on tapping a tableView cell, the user will be redirected to the website associated with the cell. Here is the code:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let url = NSURL(string: appdelegate.studentInfo[indexPath.row].url) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        UIApplication.sharedApplication().openURL(url)
    }
    else {
        let alert = UIAlertController(title: "Invalid URL", message: "Cannot open URL because it is invalid.", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    } 
}

On my first tap, the URL opens like it is supposed to. However, returning to the app from Safari and touching another cell results in the following error, although the app still works like it is supposed to:

Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.

Is there any way to avoid this error? Or is this a bug?

I have experimented with dispatch_async blocks but it did not solve the problem.

iOS Accessing PageViewController children inside ContainerView

I have a ViewController (let's call it MainViewController) that contains a ContainerView. The ContainerView contains only one child - a PageViewController. The PageViewController pages through 4 different ViewControllers (let's call them Red, Blue, Green, and Orange ViewControllers). How would I access the various colored child ViewControllers from the MainViewController (each one contains a UITableView and I'd like to pass the data for those tableviews down from the MainActivity so that I don't have to make separate database calls to get the data from each one of the colored pages)?

Note: I know how to access a ViewController inside a ContainerView using this method: Access Container View Controller from Parent iOS . But that would only get me to the PageViewController - I need to go a level deeper than that. An answer in Swift would be greatly appreciated.

Here's a screenshot to illustrate. enter image description here

And as a follow-on, how would I access the MainViewController from the 4 colored "grand-children" ViewControllers (correct terminology?)?

How to change url of AVAsset on next page and come to the previous page without having memory issues iOS

I am building an app and the scenario is something like this:

I have 3 view controllers VC1,VC2,VC3.

scenario1 I have an AVPlayer on VC2 that uses a "NSURL" saved in userDefaults to play a video.Let us say that the key to this url is "videoURL".Now if I pop VC2 and go back to VC1,dealloc() gets called and everything gets deallocated and the video stops playing.So,if I change the "videoURL" on VC1 and then push VC2 onto the navigation stack,I get a new AVPlayer with the previous one being deallocated.No problems till now.

scenario2 If I change "videoURL" on VC2,I get a new playerItem using "replaceCurrentItemWithPlayerItem" to play a new video.No problems here as well.

scenario3 Now if I push VC3 onto the stack,I don't know how to play a new URL if I pop back to VC3.The video doesn't stop playing when I push VC3,even if I set AVPlayer to nil before pushing VC3.And when I do stop the video and push VC3,I am facing memory issues.

What is the correct way to implement scenario3?

Output to console in xcode intermittently fails

I am having an intermittent problem with print() statements and other console output not showing in the xCode console window. I'm writing an app in Swift under xCode 7.3 (also had problem with xCode 7.2).

I'm been developing the app for about seven months and the first three or four months I had no problem with the console window showing my print() statements. However, now about 70% of the time when I debug running in the simulator I will get no Console output at all. If I stop and restart the app in the debugger several times eventually it will begin working. This is not due to me not knowing how to display the console window, there seems to be an intermittent bug.

Has anyone else seen this problem or know how to solve it?

I have wondered if it might have anything to do with some of the libraries I'm using. Here is a list of my Podfile.

pod 'Alamofire', '~> 3.0'
pod 'SwiftyJSON', '~> 2.3.0'
pod 'PINRemoteImage', '~> 1.2'
pod 'HockeySDK', '~> 3.8.5'
pod 'SwiftCop'
pod 'Braintree'
pod 'KeychainAccess'
pod 'TwilioSDK', '~>1.2.9'

Regards, Keith B

Progress bar crashes when updated from swift file that is not it's viewController

I have a file in Swift that holds all my queries. And when saving a record with saveOperation.perRecordProgressBlock this file call ChatView view controller and updates the progressBarUpdate function.

Co far I can get the print within progressBarUpdate to print the progress just fine. But when I get to update progressBarMessage.setProgress(value!, animated: true) the application just crash with the following error: fatal error: unexpectedly found nil while unwrapping an Optional value

If I try to run progressBarMessage.setProgress(value!, animated: true) through viewDidLoad it updates the progress bar fine, no error. Which means the outlet is working just fine.

So I guess my issue is something I cannot understand when calling progressBarUpdate from my Queries.swift file

@ my Queries.swift file

 saveOperation.perRecordProgressBlock = { (recordID, progress) -> Void in
       print("... perRecordProgressBlock (Float(progress))")
       var chatView = ChatView()
       chatView.progressBarUpdate(Float(progress))
 }

@ ChatView view controller

func progressBarUpdate(value: Float) 
{
    print(".... perRecordProgressBlock - CHAT VIEW(value)")
    if (value as? Float) != nil 
        {
        progressBarMessage.setProgress(value, animated: true)
        }
}

Making a 2d array with constructor and user input

I am stuck. I want to be able to take user input, and make a public 2D array using a constructor, my code goes as follows: `

class myarray
{
    char** grid;
    int dimX,dimY;
public:
    myarray(){grid=0;}
    myarray(int m,int n) {grid = new char* [m]; for(int i=0;i<m;i++) {grid[i]=new char [n];} dimX=m; dimY=n;}
    ~myarray(){for(int i = 0; i < dimX; ++i) {delete[] grid[i];} delete[] grid;}
    char** fetcharray(){return grid;}

int main()
{
    srand(time(NULL));
    bool check(true),arrayinitialized(false);
    while(check)
    {
        char a; //a-firstinp;
        int m,n; //m,n-grid size

        cin>>a;

        myarray c;

        switch(a)
        {
        case 'i':
        case 'I': {cin>>m>>n;
                  c(m,n);
                  arrayinitialized=true;
                  break;}
        case ...:...
        default:{cout<<"Invalid input! Try again: "; break;}

`

As I have said, I get an error on line "c(m,n);", an error says "error: no match for call to ‘(myarray) (int&, int&)’"

Program works just fine if I declare c in one of the cases locally, however I want it to be accessible throughout main()

Thank you in advance!

Alignment in dynamically allocated array of pointers to pointers to ints

I have this function that generates a "3D array" (I know it's not actually a 3D array but it is a nice way to understand it for me):

int*** generate_test_arrays(int test_arrays_length, int array_values_from,
    int array_values_to, int arrays_per_length) {
    /*This function returns a dynamically allocated "3D array" (a pointer to it).*/
    int*** test_arrays = new int**[test_arrays_length];
    for (int i = 0; i < test_arrays_length; i++) {
        /*printf("Group %d:n", i + 1);*/
        test_arrays[i] = new int*[arrays_per_length];
        for (int j = 0; j < arrays_per_length; j++) {
            test_arrays[i][j] = new int[i + 1];
            for (int i2 = 0; i2 < i + 1; i2++) {
                test_arrays[i][j][i2] = (i2 < i) ? rand() % (array_values_to - array_values_from + 1) + array_values_from: array_values_to + 1;
                /*cout << test_arrays[i][j][i2] << " ";*/
            }
            /*cout << endl;*/
        }
        /*cout << endl;*/
    }
    return test_arrays;
}

And I need each array of integers (i. e. each test_arrays[i][j]) to be 16 byte aligned, but I don't know what alignment actually is and neither do I know how to align my arrays. Does anyone know? Thanks in advance.

What should I override in inheritance when it comes to simple derivation?

class MyString :public string {
public:
    using string :: string;
    using string :: operator=;
    bool operator== (MyString&);
    bool operator<  (MyString&);
    bool operator>  (MyString&);
    MyString& operator=  (MyString&);
    MyString& operator=  (string&);
    MyString operator() (int, int);
    friend ostream & operator<<(ostream&, MyString&);
};

MyString MyString::operator() (int a, int b) {
    MyString os;
    os = string::substr(a, b);
    return os;
}

Note: I'm using cstring

It's my learning experiment. I am confused when it comes to very simple derivation like code above.

  1. Suppose I just want to add feature that can get substring by (int, int) operator, but I realize I can't use those functions that take MyString parameters.

  2. I have tried to use using for those operators ==, <, > but that doesn't work. The compiler tells me that string don't have those operator, I wonder it's because those functions in string are not virtual?

  3. Is the code in operator() legal base on my functionality set in public:? The compiler doesn't tell me any thing. But I'm quite skeptical.

iPhone app crashes when user exits UITableView with MBProgressHUD running in separate thread

In my app, I have a UITableViewController which loads calculated data from my Core Data store. This can take quite some time and hangs the main thread, so to give the user visual feedback, I have installed the MBProgressHUD widget which will show a progress indicator (just the spinning wheel) while the calculation method runs in a separate thread.

This is fine, except that the user can still exit the UITableViewController if they think it's taking too long. Of course, this is a good thing, except that when the separate thread concludes its operation, it still tries to call its delegate (the UITableViewController) to hide the MBProgressHUD. This causes a crash because since the user already exited the UITableViewController, it has dealloc'd and release'd itself.

MBProgressHUD has the following code to try to stop this:

if(delegate != nil && [delegate conformsToProtocol:@protocol(MBProgressHUDDelegate)]) {
    if([delegate respondsToSelector:@selector(hudWasHidden)]) {
        [delegate performSelector:@selector(hudWasHidden)];
    }
}

However, my app somehow seems to still be running this inner code ([delegate performSelector:@selector(hudWasHidden)]) even though the UITableViewController is totally gone--causing the app to crash.

Any suggestions? I am not running with NSZombiesEnabled.

Mamaral onboarding library in swift

Helo, I'm having trouble getting my onboarding System to work. I am using this framework: https://github.com/mamaral/Onboard

This demo for the framework only comes in objective-c, I have done my best to create my own version in swift and am almost finished but I am stuck on a way to move to another storyboard after the final screen. This is my code at the moment:

class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


    func setupNormalRootViewController() -> Void {

        self.window?.rootViewController = LoginViewController

    }


    let firstPage = OnboardingContentViewController(title: "Welcome To my App", body: "App Mesage", image: UIImage(named: "heart"), buttonText: "") {}
    let secondPage = OnboardingContentViewController(title: "...", body: "Message", image: UIImage(named: "Mint"), buttonText: "") {}

    let thirdPage = OnboardingContentViewController(title: "title", body: "abcd", image: UIImage(named: "Choco"), buttonText: "End", action: { setupNormalRootViewController() } ) {}

    let onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "blueBackground"), contents: [firstPage, secondPage,thirdPage])




    self.window?.rootViewController = onboardingVC
 }
}

I am calling "setupNormalRootViewController" in the "thirdPage" variable but there seems to be no way to move on past the initial onboarding screen even though I have set a specified method to run when pressing the button on the last screen.

C++ rule of five for class that has dynamic memory

So I'm writing the big five for a class that has dynamic int array

struct intSet {
  int *data;
  int size;
  int capacity;

  intSet();
  ~intSet();
  intSet(const intSet& is);
  intSet(intSet &&is);
  intSet &operator=(const intSet& is);
  intSet &operator=(intSet &&is);
}

What I got so far:

intSet::intSet(const intSet& is){
  this->size=is.size;
  this->capacity=is.capacity;
  this->data=is.data;
}

intSet::intSet(intSet &&is){
  this->size=is.size;
  this->capacity=is.capacity;
  this->data=is.data;
  is.data=nullptr;
}

intSet& intSet::operator=(const intSet& is){
  if(&is!=this){
    size=is.size;
    capacity=is.capacity;
    delete [] data;
    data=is.data;
    data=new int[capacity];
    for(int i=0;i<size;i++){
      data[i]=is.data[i];
    }  
  }
  return *this;
}

intSet& intSet::operator=(intSet &&is){
  if(&is!=this){
    size=is.size;
    capacity=is.size;
    delete [] data;
    data=is.data;
    is.data=nullptr;
  }
  return *this;
}

intSet::~intSet(){
  delete [] this->data;
}

Clearly there's something wrong with it but I am not really familiar with the big five...I searched a lot but still did not find out the answer...

IOS Swift Image rotated when loaded into UIImageView

In my app, I have a button with which I open the Gallery as below:

@IBAction func selectPhoto() {
    let photoPicker = UIImagePickerController()
    photoPicker.delegate = self
    photoPicker.sourceType = .PhotoLibrary
    self.presentViewController(photoPicker, animated: true, completion: nil)
}

I let the user select a photo and save it:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage        
    let fileName:String = "logo.png"        
    let arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString        
    let pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)                UIImagePNGRepresentation(photoImageView.image!)!.writeToFile(pngFileName, atomically:true)        
    imageSave.setObject(fileName, forKey: "pngFileName")        
    self.dismissViewControllerAnimated(false, completion: nil)
}

Then from View controller, the pictures saved is shown everytime the user gets to the scene using below code.

 override func viewDidLoad() {
    super.viewDidLoad()

    if imageSave.stringForKey("pngFileName") != nil
    {
        let path = NSSearchPathForDirectoriesInDomains(
            .DocumentDirectory, .UserDomainMask, true)[0] as NSString
        let fileName = NSUserDefaults.standardUserDefaults()
            .stringForKey("pngFileName")
        let imagePath = path.stringByAppendingPathComponent(fileName!)
        let image = UIImage(contentsOfFile: imagePath )            
        photoImageView.image = image

    }

Problem : When the image loads back onto the UIImageView, the orientation of the picture is sometimes rotated right by 90 degrees, sometimes rotated left by 90 degrees or sometimes shown as it was saved.

Please let me know what I am doing wrong here. Any help would be appreciated. Thanks

Adding a Framework on iOS in runtime

At first, I will describe my use-case on why I need to add the framework at runtime on iOS.

Let's say I have an app on iOS device. The app requires some 3rd party frameworks to add some external features to it. Now, the features are many. So, the required number of frameworks will be many too. An user may not need lots of features. Just a small set of features. Plus, lots of framework will require a lot of space. The application will be huge in size.

For an example, an user needs only 1 feature. The application provides 100. So, all the other frameworks will definitely be unnecessary.

So, the solution would be to download the frameworks and the necessary files on demand from an online repository, link them on runtime and use them. This would mean the application size would be very small and not bulky with unnecessary stuff.

But does iOS provide that? I have to add an external framework and the necessary files that is not on the app use them on runtime.

Is this possible? Can anyone provide me with some resources on how I can do that?

I have seen some resources on SO and some other sites. The results are not so helpful.

How to get the selected index path for UIImageView object present on a UITableVIewCell of UITableView?

I have a tableview with custom tableView cell present in it. I have placed a UIImageview on custom tableViewCell. When i press or touch the imageView, i want to download some images from url, on the basis of selected index, which i am going to pass it(selectedIndex) as a string in the url.

What happens is when i first touch the image view, i am not getting the selected index path. But when i first select the cell and then i press the image view, at that time i get the selected index path. I searched it on the internet, but didn't found any appropriate solution. Here below is my code where i assign a UILongPressRecognizer to the UIImageView, in cellForRowAtIndexPath method.

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


cell.imgvDownload.tag=indexPath.row;
    singleTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected12)];

    [cell.imgvDownload setUserInteractionEnabled:YES];
    [singleTap.delegate self];
    [singleTap setMinimumPressDuration:0.01f];
    [cell.imgvDownload addGestureRecognizer:singleTap];

return cell;
}

The problem is that UIImageview is to able to get the selected index path for the row selected. But if i first select any cell(row) from tableView and then press the UIImage view, i get the index. Can anyone please tell me what wrong am i doing here. Any help is appreciated.

UITableView scroll to the bottom messed up with EstimatedRowHeight

I'm trying to scroll to the bottom of my UITableView (commentsFeed) whenever the user creates a new comment or the user refreshes the UITableView.

The code I use is:

func scrollToBottomOfComments() {

    var lastRowNumber = commentsFeed.numberOfRowsInSection(0) - 1
    var indexPath = NSIndexPath(forRow: lastRowNumber, inSection: 0)
    commentsFeed.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}

The problem is here in viewDidLoad:

commentsFeed.rowHeight = UITableViewAutomaticDimension
commentsFeed.estimatedRowHeight = 150

This basically states that the comments can have dynamic heights because users could post either really long comments or really short comments.

When I use the estimatedRowHeight, my scrollToBottom doesn't properly scroll to the bottom because it basically assumes my table height is commentsFeed.count * commentsFeed.estimatedRowHeight

This isn't correct though.

When I remove the estimatedRowHeight though, it doesn't seem to work either, and I think the reason is because it doesn't have the row height calculated properly because the rows each have dynamic heights.

How do I mitigate this?

Edit: It should be stated that the scroll doesn't end up at the right position, but the moment I use my finger to scroll anywhere, then the data jumps into place where it should have been via the scroll

Making two types of same template compatible

I do not know how to name the problem that I am facing. So I have a template class for matrices to accept different types e.g. int, double and other stuff. My problem is if I want to work on to different instance type of the class, I can not get it to compile. Here is the definition of the add function which supposedly should add a matrix to the current instance.

template <class T>
void Matrix<T>::add(const Matrix &m) {
    for (int i = 0; i < this->rows; ++i) {
        for (int j = 0; j < this->cols; ++j) {
            this->mat[i][j] += m.at(i,j);
        }
    }
}

It works just fine e.g. if I add a Matrix<double> to Matrix<double> instance.

But I can not get it to work, adding a Matrix<int> to a Matrix<double> e.g:

Matrix<double> matA(2,2);
Matrix<int> matB(2,2);
matA.add(matB);

The compiler (g++ 4.8) complains:

error: no matching function for call to ‘Matrix<double>::add(Matrix<int>&)

What can be the workaround?

C++ method declaration including a macro

I'm using QuickFAST library and while checking it I found this class declaration which I don't seem to really get ! I mean what does a macro name before the class name !

class QuickFAST_Export Message : public FieldSet

also I found this declaration

friend void QuickFAST_Export intrusive_ptr_add_ref(const Field * ptr);

and again I don't get the use of this declaration !

for more info here's the QuickFAST_Export.hpp

#ifdef _MSC_VER
# pragma once
#endif
#ifndef QUICKFAST_EXPORT_H
#define QUICKFAST_EXPORT_H

// Compile time controls for library generation.  Define with /D or #define
// To produce or use a static library: #define QUICKFAST_HAS_DLL=0
//   Default is to produce/use a DLL
// While building the QUICKFAST_ library: #define QUICKFAST_BUILD_DLL
//   Default is to export symbols from a pre-built QUICKFAST DLL
//
// Within QUICKFAST use the QuickFAST_Export macro where a __declspec is needed.

#if defined (_WIN32)

#  if !defined (QUICKFAST_HAS_DLL)
#    define QUICKFAST_HAS_DLL 1
#  endif /* ! QUICKFAST_HAS_DLL */

#  if defined (QUICKFAST_HAS_DLL) && (QUICKFAST_HAS_DLL == 1)
#    if defined (QUICKFAST_BUILD_DLL)
#      define QuickFAST_Export __declspec(dllexport)
#    else /* QUICKFAST_BUILD_DLL */
#      define QuickFAST_Export __declspec(dllimport)
#    endif /* QUICKFAST_BUILD_DLL */
#  else /* QUICKFAST_HAS_DLL == 1 */
#    define QuickFAST_Export
#  endif /* QUICKFAST_HAS_DLL == 1 */

#  else /* !_WIN32 */

In an Xcode iOS .pbxproj file, how are the 12 byte ids generated?

If you open up the .pbxproj file in a text editor, you'll see things that look like:

/* Begin PBXBuildFile section */
        25AF71181D2046B400566BC8 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25AF71171D2046B400566BC8 /* AppDelegate.swift */; };
        25AF711A1D2046B400566BC8 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25AF71191D2046B400566BC8 /* ViewController.swift */; };
        25AF711D1D2046B400566BC8 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 25AF711B1D2046B400566BC8 /* Main.storyboard */; };
        25AF711F1D2046B400566BC8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 25AF711E1D2046B400566BC8 /* Assets.xcassets */; };
        25AF71221D2046B400566BC8 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 25AF71201D2046B400566BC8 /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */

This article claims that they are UUID's, but if that was the case, shouldn't they be completely different from each other? If looks like only the 4th byte is changing and the rest stay the same. So is part of it generated and for some reason that byte changes? Why?

25 AF 71 **18** 1D 20 46 B4 00 56 6B C8
25 AF 71 **1A** 1D 20 46 B4 00 56 6B C8
25 AF 71 **1D** 1D 20 46 B4 00 56 6B C8

What does this UUID mean? Is it possible to replace the UUID from one that Xcode generated with your own? (And still work?)

mercredi 29 juin 2016

Exception when calling std::list::push_back

I have a class TextureManager class which has a std::list of pointers to Ressource

    struct Ressource
    {
        sf::Image img;
        std::string path;
    };

I get this error:

std::_List_alloc<std::_List_base_types<ASC::TextureManager::Ressource *,std::allocator<ASC::TextureManager::Ressource *> > >::_Myhead(...) returned 0x4.

methods:

    const sf::Image& TextureManager::load(std::string dPath)
    {
        Ressource * res = new Ressource;
        res->img.loadFromFile(dPath);
        res->path = dPath;

        data.push_front(res);

        return res->img;
    }   

    const sf::Image& TextureManager::get(std::string dPath)
    {
        return load(dPath);
    }

the TextureManager is a member of RessourceHandler which has the following getter method:

const sf::Image& RessourceHandler::getTexture(std::string path)
{
    return tManager.get(path);
}

That method gets called by different objects which have a pointer to an instance of the RessourceHandler. Thats when the exception gets thrown.

it works all fine if i delete the line where i push_back the Ressource into the list at TextureManager::load()

it also works fine when i call TextureManager::load() from the RessourceHandler's Constructor. Even without deleting the push_back.

I can't figure out why that happens. has anyone an idea?

UIActivityViewController issue iOS 7 and iOS 8?

I’m building an article reading app for iPad. I have integrated a social sharing functionality which means user can share articles on Facebook, and google mail. I’m using UIActivityViewController for sharing.

There is a bar button item,when user click on that UIActivityViewController opens.I updated Xcode 6 When I run on simulator it runs fine But I run on real device(iPad) with iOS 7,the app get crash on clicking on bar button item. this is my code:

     - (IBAction)ysshareAction:(id)sender
       {

         NSURL *linkURL = [NSURL URLWithString:_DetailModal1[4]];//article url
         NSMutableAttributedString *stringText = [[NSMutableAttributedString alloc]  initWithString:_DetailModal1[0]];//_DetailModal1[0] contain article title////
        [stringText addAttribute:NSLinkAttributeName value:linkURL range:NSMakeRange(0, stringText.length)];
        NSArray * itemsArray = @[[NSString stringWithFormat:@"%@",_DetailModal1[0]], [NSURL URLWithString:_DetailModal1[4]]];
        NSArray * applicationActivities = nil;
        UIActivityViewController * AVC = [[UIActivityViewController alloc] initWithActivityItems:itemsArray applicationActivities:applicationActivities];
        AVC.popoverPresentationController.sourceView = _webView;
        [self presentViewController:AVC animated:YES completion:nil];
        [AVC setCompletionHandler:^(NSString *act, BOOL done)
        {

        if([act isEqualToString:UIActivityTypeMail]) {
         ServiceMsg = @"Mail sent!";
     } else if([act isEqualToString:UIActivityTypePostToTwitter]) {
         ServiceMsg = @"Article Shared!";
     } else if([act isEqualToString:UIActivityTypePostToFacebook]) {
         ServiceMsg = @"Article Shared!";
     } else if([act isEqualToString:UIActivityTypeMessage]) {
         ServiceMsg = @"SMS sent!";
     } else if([act isEqualToString:UIActivityTypeAddToReadingList]) {
         ServiceMsg = @"Added to Reading List";
     } else if([act isEqualToString:UIActivityTypeCopyToPasteboard]){
         ServiceMsg = @"Copied Link";
     }

     if ( done )
     {
         UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:ServiceMsg message:@"" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
         [Alert show];

          }
       }];

    }

Help is appreciated!

Cannot compile MOC file if Q_OBJECT macro is removed by other macro: The header file doesn't include <QObject>

When compiling a non-Qt version of a Qt/C++ program (-DDISABLE_MYMODULE), I get this compiler error:

src/mymodule.moc.cpp:12:2: error: #error "The header file
'mymodule.hpp' doesn't include <QObject>."
src/mymodule.moc.cpp:19:1: error: ‘QT_BEGIN_MOC_NAMESPACE’ does not name a type
src/mymodule.moc.cpp:40:6: error: ‘MyModule’ has not been declared
...

I'm using GNU make (not qmake). My Makefile compiles two object files per module, one directly from the .cpp source file and the MOC object file from the .moc.cpp source file (this is what doesn't work), both using g++. This .moc.cpp source file is created by MOC, from the .hpp header (this process does not throw an error).

The header file in question looks somewhat like this:

#ifndef DISABLE_MYMODULE //My problem macro
#ifndef MYMODULE_HPP
#define MYMODULE_HPP
//...
class MyModule : //...
{
    Q_OBJECT //Qt problem macro
    //...
};
//...
#endif
#endif

The whole thing will compile (and later link, execute) just fine if don't set my problem macro. If I do set it, but comment out QT's problem macro, it'll compile fine as well (building a non-Qt version).

I don't exactly know, what MOC replaces Q_OBJECT by, but shouldn't it still be inside my DISABLE_MYMODULE and therefore be removed by the preprocessor?

C++11 Recursive Spinlock Implementation

Following [1] I tried to implement a recursive spin lock as follows.

class SpinLock {
public:
  SpinLock() : lock_owner(lock_is_free), lock_count(0) {
  }

  inline bool tryLock() {
    if (lock_owner != std::this_thread::get_id()) {
      bool locked = lock_owner.compare_exchange_strong(lock_is_free,
          std::this_thread::get_id(), std::memory_order_acquire,
          std::memory_order_relaxed);
      if (locked) {
        lock_count++;
      }
      return locked;
    }

    lock_count++;
    return true;
  }

  inline void lock() {
    if (lock_owner != std::this_thread::get_id()) {
      while(!lock_owner.compare_exchange_weak(lock_is_free,
            std::this_thread::get_id(), std::memory_order_acquire,
            std::memory_order_relaxed));
      assert(lock_owner == std::this_thread::get_id());
    } else {
      printf("Recursive lockingn");
    }

    lock_count++;
  }

  inline void unlock() {
    assert(lock_owner == std::this_thread::get_id());
    assert(lock_count != 0);

    --lock_count;
    if (lock_count == 0) {
      lock_owner.store(lock_is_free, std::memory_order_release);
    }
  }

  inline bool isOwner() {
    return lock_owner == std::this_thread::get_id();
  }

  inline bool isSet() {
    return lock_owner != lock_is_free;
  }

private:
  std::thread::id lock_is_free;
  std::atomic<std::thread::id> lock_owner;
  int lock_count;
};

But lock method doesn't seem to ensure mutual exclusion when I tried locking with multiple threads. What am I doing wrong here?

[1] http://codereview.stackexchange.com/questions/95590/c11-recursive-atomic-spinlock

Array of components doesnt compile

I am trying to make array of pannels, like here:

TImage* Board[BoardX][BoardY];
TImage* Tiles[TILES_MAX];

Here are variables that i have declared:

int BoardX = 25;
int TILES_MAX = 7;
int BoardY = 15;

When i try to compile this, i get the following compiler output:

[C++ Error] Game.cpp(14): E2313 Constant expression required
[C++ Error] Game.cpp(14): E2313 Constant expression required
[C++ Error] Game.cpp(15): E2313 Constant expression required
[C++ Error] Game.cpp(17): E2188 Expression syntax
[C++ Error] Game.cpp(24): E2141 Declaration syntax error
[C++ Error] Game.cpp(24): E2190 Unexpected }
[C++ Error] Game.cpp(24): E2190 Unexpected }
[C++ Error] Game.cpp(29): E2378 For statement missing ;

As you see, the tables doesnt want to compile. This is my whole code (currently unfinished):

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Game.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
int BoardX = 25;
int TILES_MAX = 7;
int BoardY = 15;
TImage* Board[BoardX][BoardY];
TImage* Tiles[TILES_MAX];
char** tileNames = {
  {"assets\stone.bmp"},
  {"assets\Ethernite.bmp"},
  {"assets\EtherniteBlock.bmp"},
  {"assets\frozendirt.bmp"},
  {"assets\grassground.bmp"},
  {"assets\coalore.bmp"},
  {"assets\filling.bmp"}
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
  for(int i = 0; i < TILES_MAX; i++){
    Tiles[i]->Picture->LoadFromFile(tileNames[i]);
  }
}
//---------------------------------------------------------------------------

So how to make this work?

C++ stack and scope

I tried this code on Visual C++ 2008 and it shows that A and B don't have the same address.

int main()
{
    {
    	int A;
    	printf("%pn", &A);
    }

    int B;
    printf("%pn", &B);
}

But since A doesn't exist anymore when B gets defined, it seems to me that the same stack location could be reused...

I don't understand why the compiler doesn't seem to do what looks like a very simple optimization (which could matter in the context of larger variables and recursive functions for example). And it doesn't seem like reusing it would be heavier on the CPU nor the memory. Does anyone have an explanation for this?

I guess the answer is along the lines of "because it's much more complex than it looks", but honestly I have no idea.

edit: Some precisions regarding the answers and comments below.

The problem with this code is that each time this function is called, the stack grows "one integer too much". Of course this is no problem in the example, but consider large variables and recursive calls and you have a stack overflow that could be easily avoided.

What I suggest is a memory optimization, but I don't see how it would damage performance.

And by the way, this happens in release builds, will all optimizations on.

What’s your favorite xml parser for parse my XML file in Objective-C [on hold]

What’s your favorite xml parser in Objective-C

I develop an app in Objective C , i need to parse this XML file for get the data of Fuel Price

here an example of my XML file

thanks for you help

<pdv id="1000001" latitude="4620114" longitude="519791" cp="01000" pop="R">
<adresse>ROUTE NATIONALE</adresse>
<ville>SAINT-DENIS-LèS-BOURG</ville>
<ouverture debut="01:00" fin="01:00" saufjour=""/>
<services>
<service>Automate CB</service>
<service>Vente de gaz domestique</service>
<service>Station de gonflage</service>
</services>
<prix nom="Gazole" id="1" maj="2014-01-02 11:08:03" valeur="1304"/>
<prix nom="SP98" id="6" maj="2014-12-31 08:39:46" valeur="1285"/>
<prix nom="Gazole" id="1" maj="2007-02-28 07:48:59.315736" valeur="999"/>
<fermeture/>
<rupture/> 
</pdv> 

I try to make this code below and i need your help for parse the Rows of my Xml file

    NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"my url file"]];XML"]];
    [xmlparser setDelegate:self];
    [xmlparser parse];
    if (marrXMLData.count != 0) {
        [self.tableView reloadData];
    }
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{
    if([elementName isEqualToString:@"pdv_liste"])
        marrXMLData = [[NSMutableArray alloc] init];
    if([elementName isEqualToString:@"pdv"])
        mdictXMLPart = [[NSMutableDictionary alloc] init];
}

Thanks for your help

Visual Studio 2015 Build Time for Small Project

There are many questions on SO about improving the build time in Visual Studio (cf. here, here, etc.), but the vast majority of answers are aimed at projects which are fairly large. Many of these answers (e.g. increasing amount of parallel builds) will only have a marginal effect on small projects, which is what motivates this question.

I am using Visual Studio Express 2015 with one solution, a single C++ project, containing only three files: an 800-line source file, and two .h files. I am running on Windows 7, my processor is Intel Core i5, CPU 2.60GHz, RAM 8GB.

My build time is a staggering 1 minute or more.

Based on suggestions in other SO threads, I have emptied my %temp% and prefetch directories, but this only had a marginal effect. I changed my code to remove as many warnings as possible. I removed all the unnecessary files from the VS directories for my project. My antivirus is disabled.

Here and here it was suggested that an SSD could help. I find it hard to believe, however, that my performance should be this poor with HDD.

I would be glad to hear any suggestions about this issue. Thank you in advance.

WKWebView Cookies

I'm using the below mentioned approach to set cookies in a WKWebview: Can I set the cookies to be used by a WKWebView?

But the cookies that I have set are being duplicated in the AJAX calls. I mean they are being repeated twice.

Here is the code snippet that I used:

NSString *strURL = DASHBOARDURL;    
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];

NSMutableString *script = [[NSMutableString alloc] init];
NSMutableString *cookieString = [[NSMutableString alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
    [script appendString:[NSString stringWithFormat:@"document.cookie='%@';",cookie.getCookieString]];
    [cookieString appendString:[NSString stringWithFormat:@"%@;", cookie.getCookieString]];
}
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];

//cookies for further AJAX calls
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
WKUserScript *cookieInScript = [[WKUserScript alloc] initWithSource:script
                                                      injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                   forMainFrameOnly:YES];
[userContentController addUserScript:cookieInScript];

WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init];
webViewConfig.userContentController = userContentController;

CGRect viewRect = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);

wkWebview = [[WKWebView alloc] initWithFrame:viewRect configuration:webViewConfig];
wkWebview.navigationDelegate = self;
[wkWebview loadRequest:request];
[self.view addSubview:wkWebview];

getCookieString is a method that returns cookie values as an NSString

  1. Will the WKWebView set the cookies back to NSHTTPCookieStorage at runtime(During AJAX calls)
  2. Can i control AJAX calls cookies with any delegate methods?

Setting up Qt for CLion

i am struggling to set up Qt5 for CLion. Somehow, I did this for VS before but failed to do this in CLion. Building and Including Qt headers are fine and CLion find qt symbols and auto-completes them but when i am using an Qt object Clion giving me this error:

C:Usersbinhb.CLion2016.1systemcmakegeneratedLBMTopoOptimization-ae159e87ae159e87DebugLBMTopoOptimization.exe Process finished with exit code -1073741515 (0xC0000135)

My CMake file looks like this:

cmake_minimum_required(VERSION 3.5)
project(LBMTopoOptimization)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# set prefix path for Qt5
set (CMAKE_PREFIX_PATH "C:\QT\5.7\mingw53_32\")

# Find QT Libraries
find_package( Qt5Core REQUIRED )
find_package( Qt5Widgets REQUIRED )
find_package( Qt5Gui REQUIRED )

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++11")

set(SOURCE_FILES main.cpp)
add_executable(LBMTopoOptimization ${SOURCE_FILES})

# Use the modules from Qt 5.
target_link_libraries(LBMTopoOptimization Qt5::Widgets Qt5::Core Qt5::Gui)

The error would already occur by using for example a QString:

#include <QWidget>

int main(int argc, char** argv ){
    QString name = "this is a string";
return 0;
}
  • System specification:
  • Windows 10
  • Clion 1.3
  • Qt 5.7
  • CMake 3.6 rc3
  • mingw-gcc 4.9.3

I looking forward for any hints.

Why deallocating heap memory is much slower than allocating it?

This is an empirical assumption (that allocating is faster then de-allocating).

This is also one of the reason, i guess, why heap based storages (like STL containers or else) choose to not return currently unused memory to the system (that is why shrink-to-fit idiom was born).

And we shouldn't confuse, of course, 'heap' memory with the 'heap'-like data structures.


So why de-allocation is slower?

Is it Windows-specific (i see it on Win 8.1) or OS independent?

Is there some C++ specific memory manager automatically involved on using 'new' / 'delete' or the whole mem. management is completely relies on the OS? (i know C++11 introduced some garbage-collection support, which i never used really, better relying on the old stack and static duration or self managed containers and RAII).

Also, in the code of the FOLLY string i saw using old C heap allocation / deallocation, is it faster then C++ 'new' / 'delete'?


P. S. please note that the question is not about virtual memory mechanics, i understand that user-space programs didn't use real mem. addresation.

Why Png Compression doesn't change destination size (C++)? OpenCV VS2010

I have tested this code with various values from compression_params.push_back(1); to compression_params.push_back(9); but the PNG image always has same size. 1950x1080 (contains screenshot of Google map - not the satellite photo) has 2,36 MB (2 477 230 bytes. Is this normal is takes so much. I thought png images are small size if they do not contain photos.

vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
compression_params.push_back(1);

try {
    imwrite("RGB_1.png", source, compression_params);
}
catch (runtime_error& ex) {
    fprintf(stderr, "Exception converting image to PNG format: %sn", ex.what());
    return 1;
}

Why is it? Also I cannot find out how to create the PNG object in memory (to keep the encode data in buffer). This means, I would like to save more images into one file (e.g database) so I need to convert into buffer and then save add buffer to file. Is it possible to do it usin OpenCV? Your tips welcome.

I think PNG should support some feature where the algorithm auto-selects background color, so if you see some cv::Scallar(200,200,200) takes too many place on the image, the algorithm could set it as background color and it is removed from the image so the image should take small place. So when it takes same size as regular PNG or even more, that doesn't give any sense.

Constructor not working "error: no match for call to '(<class name>) (int&, int&)"

I have written a simple program which has several possible inputs(i,c,l,v..). The first input is "i m n", where m and n are integer values. This command generates a 2D array with m rows and n cols. Here is my code:

class myarray
{
    char** grid;
    int dimX,dimY;
public:
    myarray(){grid=0;}
    myarray(int m,int n) {grid = new char* [m]; for(int i=0;i<m;i++) {grid[i]=new char [n];} dimX=m; dimY=n;}
    ~myarray(){for(int i = 0; i < dimX; ++i) {delete[] grid[i];} delete[] grid;}
    char** fetcharray(){return grid;}

int main()
{
    srand(time(NULL));
    bool check(true),arrayinitialized(false);
    while(check)
    {
        char a; //a-firstinp;
        int m,n; //m,n-grid size

        cin>>a;

        myarray c;

        switch(a)
        {
        case 'i':
        case 'I': {cin>>m>>n;
                  **c(m,n);**
                  arrayinitialized=true;
                  break;}
        case ...:...
        default:{cout<<"Invalid input! Try again: "; break;}

However, I get an error in case 'i': ...; c(m,n); saying "error: no match for call to '(myarray) (int&, int&)'". When I declare the variable myarray c; in case as a local variable (myarray c(m,n)) everything works just fine. However, I want the variable c to be accessible by other cases and therefore need it to be available throughout the main() function, as it is in the code above. Does anyone know what is wrong and how can I fix it? Thank you in advance!

M4 macros in the 3rd-party aclocal directory are not found

I have locally installed a newer version of automake (1.15) on a system which I do not have root access to. The local directory's bin folder is the first directory in my PATH.

I have also locally installed gtk+-2.0, and I now want to build and install an application which requires gtk as a dependency, i.e. the configure.ac script for my desired application contains:

PKG_CHECK_MODULES(GTK, [gtk+-2.0 >= 2.0])

To ensure the m4 macros are found, I copied all of the .m4 files in gtk_install_dir/lib/pkgconfig/ into the location that aclocal --print specifies (automake_install_dir/share/aclocal/).

I also set PKG_CONFIG_PATH=gtk_install_dir/lib/pkgconfig.

However, when I run:

$ libtoolize
$ aclocal
$ autoconf
$ automake
$ ./configure

I get an error message:

./configure: line 13106: syntax error near unexpected token `GTK,'
./configure: line 13106: `PKG_CHECK_MODULES(GTK, gtk+-2.0 >= 2.0)'

Running aclocal --verbose I can clearly see that there is no mention of gtk, so it is clearly not finding the gtk+ macros.

I have not used these build tools before, am I missing something? I seemingly can't get the configure script to recognise that gtk is installed!

Any advice is much appreciated, thanks

Crashed: com.apple.main-thread (NSMutableArray insertObjects)

I receive crash report.
But I have no idea about this.

Crashed: com.apple.main-thread 0 libobjc.A.dylib
0x180a9db90 objc_msgSend + 16 1 CoreFoundation
0x18130ea0c -[NSMutableArray insertObjects:count:atIndex:] + 160 2 CoreFoundation 0x18130e744 -[NSMutableArray insertObjectsFromArray:range:atIndex:] + 320 3 CoreFoundation
0x18130e5d4 -[NSMutableArray addObjectsFromArray:] + 652 4 UIKit
0x18668cc08 -[UIView(AdditionalLayoutSupport) _accumulateViewConstraintsIntoArray:] + 104 5 UIKit 0x18657f3f4 -[UIView(AdditionalLayoutSupport) _switchToLayoutEngine:] + 124 6 UIKit 0x1866cd9d4 -[UIView(AdditionalLayoutSupport) _initializeHostedLayoutEngine] + 640 7 UIKit 0x186695964 -[UIView(UIConstraintBasedLayout) _layoutEngine_windowDidChange] + 192 8 UIKit 0x18657f578 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 196 9 UIKit 0x18657f7ac -[UIView(Internal) _didMoveFromWindow:toWindow:] + 760 10 UIKit 0x18657ed40 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 152 11 UIKit 0x18657eba8 -[UIView(Hierarchy) _postMovedFromSuperview:] + 504 12 UIKit 0x18658c678 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1784 13 UIKit 0x18664eda0 -[UINavigationTransitionView transition:fromView:toView:] + 620 14 UIKit 0x186644d48 -[UINavigationController _startTransition:fromViewController:toViewController:] + 2696 15 UIKit 0x186643ef4 -[UINavigationController _startDeferredTransitionIfNeeded:] + 868 16 UIKit 0x186643b1c -[UINavigationController __viewWillLayoutSubviews] + 60 17 UIKit 0x186643a84 -[UILayoutContainerView layoutSubviews] + 208 18 UIKit 0x1865801e4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 656 19 QuartzCore 0x183f12994 -[CALayer layoutSublayers] + 148 20 QuartzCore
0x183f0d5d0 CA::Layer::layout_if_needed(CA::Transaction*) + 292 21 QuartzCore 0x183f0d490 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32 22 QuartzCore 0x183f0cac0 CA::Context::commit_transaction(CA::Transaction*) + 252 23 QuartzCore 0x183f0c820 CA::Transaction::commit() + 500 24 QuartzCore
0x183f05de4 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) +


Here is my code.

[self.customConstraints addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|[view]|" options:0 metrics:nil views:views]];

Why is sizeof (class with character variable) anomalous in C++? [duplicate]

This question already has an answer here:

Consider the following code:

#include <iostream>
#include <conio.h>> 
using namespace std;

class book 
{ 
    char Title;
    int no_of_pages; 
public: 
    void read(); 
    void show(); 
}; 

int main()
{
    book ob;
    char Title;
    cout << sizeof(book) << " " << sizeof(Title) << endl;

    getch();
    return 0;
}

The output of the code is

8 1

If I change the definition of 'Title' in the class to following:

char Title[5];

and the main() 'Title' to

char Title[5];

the output changes to:

12 5

To see if this is something which is done to all string variables in the program, I used the 'Title' in main(). But, the pattern is apparent for a string declared in a class.

For the sake of completion, the pattern is :

Size of character array is taken to be the least multiple of 4 greater than the actual size of array

Question: Although I understand it is implementation dependent, does anyone know or can suggest a reason for this behaviour of C++ 11?

My compiler is VS 2012, for 64-bit Windows.

PlaySound() function won't play sound

First question, sorry if I don't do something right :S. I'm attempting to loop a background audio track while a game created in the console window is played. This is part of a group project. The game runs fine but I simply can't get the audio track to play using the PlaySound() function. This is a test program I made to try to figure out the problem.

#include <iostream>
#include <windows.h>
#include <mmsystem.h>

using namespace std;

int main()
{

    PlaySound(TEXT("D:\CodeBlocks:\Programming Work:\SoundTest:\castor.wav"), NULL, SND_FILENAME|SND_ASYNC|SND_LOOP);
    if(PlaySound(TEXT("D:\CodeBlocks:\Programming Work:\SoundTest:\castor.wav"), NULL, SND_FILENAME|SND_ASYNC|SND_LOOP))
    {
        cout << "It's Working." << endl;
    }
    else
    {
        cout << "It's not working." << endl;
    }
    cout << "Hello world!" << endl;

    return 0;
}

My test case returns true (or "It's working."), and when I tried it in the school computer lab, it would loop the default windows error tone, which plays when the function can't find the file you specified, even though I've given it the whole file path. I can't figure out why it can't find the file, I've quadruple checked that it is in fact located where I wrote the file path, and it still seems unable to find it. I've tried using both .mp3 and .wav formats for the audio file. Anyone know what's going on? (note: The linker needs to be given the winmm library for this)

Transfer ownership of boost::asio::socket stack variable

I'm writing a simple tcp socket server capable of handling multiple concurrent connections. The idea is that the main listening thread will do a blocking accept and offload socket handles to a worker thread (in a thread pool) to handle the communication asynchronously from there.

void server::run() {
  {
    io_service::work work(io_service);

    for (std::size_t i = 0; i < pool_size; i++)
      thread_pool.push_back(std::thread([&] { io_service.run(); }));

    boost::asio::io_service listener;
    boost::asio::ip::tcp::acceptor acceptor(listener, ip::tcp::endpoint(ip::tcp::v4(), port));

    while (listening) {
      boost::asio::ip::tcp::socket socket(listener);
      acceptor.accept(socket);
      io_service.post([&] {callback(std::move(socket));});
    }
  }

  for (ThreadPool::iterator it = thread_pool.begin(); it != thread_pool.end(); it++)
    it->join();
}

I'm creating socket on the stack because I don't want to have to repeatedly allocate memory inside the while(listening) loop.

The callback function callback has the following prototype:

void callback(boost::asio::socket socket);

It is my understanding that calling callback(std::move(socket)) will transfer ownership of socket to callback. However when I attempt to call socket.receive() from inside callback, I get a Bad file descriptor error, so I assume something is wrong here.

How can I transfer ownership of socket to the callback function, ideally without having to create sockets on the heap?

"Unable to Validate your Application Error" While Uploading a new version of iOS App

I have been trying to upload a new version for my ios App But I always end up receiving this error "UNABLE TO VALIDATE YOUR APPLICATION, "The application you have selected does not exist"

From Xcode Archiver. I followed this question here Xcode 6.4 The Application You Have Selected Does Not Exist

Which suggests to use Application Loader, After doing that I ended up getting bunch of errors such as these

ERROR ITMS-90049: "This bundle is invalid. The bundle identifier contains disallowed characters. [See the section of the Application Programming Guide entitled The Application Bundle.]"
ERROR ITMS-90057: "Missing plist key. The Info.plist file is missing the required key: CFBundleShortVersionString."
ERROR ITMS-90056: "This bundle is invalid. The Info.plist file is missing the required key: CFBundleVersion."
The resulting API analysis file is too large.  We were unable to validate your API usage prior to delivery.  This is just an informational message.

This errors dont make any sense since all the missing keys are already present in my app, along with appropriate bundle ID of my app which has been in the Appstore for an Year now.

Can anybody help me out regarding this,

I seemed to have tried all the solutions I could find, but to no avail, anybody else facing this? Is this another issue from apples server or maintenance side and I just have to wait a couple of hours before they fix it at thier end??

Can you add variables inside "cout" [closed]

I'm new to C++, on the chapter 2 quiz of LearnCpp.com. I'm stuck and have a question. Can you add variables inside a std::cout statement? For example:

The program will not display my answer. The program ends as soon as the user presses enter after inputting the values. Thanks for your help ahead of time.

EDIT: Sorry for not posting the entire code. I'm also new to forums. I added the () like someone suggested. When I ran the program I think I saw it display the answer for a split second and it doesn't show that Press any key to continue. . .

#include "stdafx.h"
#include <iostream>

int main()
{
double first_value;
double second_value;
char user_operator;

std::cout << "Enter a double value: ";
std::cin >> first_value;
std::cout << "Enter a second double value: ";
std::cin >> second_value;
std::cout << "Enter one of the following (+, -, *, /): ";
std::cin >> user_operator;

if (user_operator == 43 || user_operator == 45
    || user_operator == 42 || user_operator == 47)
    switch (user_operator)
    {
        case 43:
            std::cout << "  " << (first_value + second_value) << "n";
            break;
        case 45:
            std::cout << "  " << (first_value - second_value) << "n";
            break;
        case 42:
            std::cout << "  " << (first_value * second_value) << "n";
            break;
        case 47:
            std::cout << "  " << (first_value / second_value) << "n";
            break;
    }
else std::cout << "Please enter a valid operator.";

return 0;

}

OpenCv iOS camera preview single orientation only without stretching

I'm writing a OpenCv Cordova plugin for iOS. I needed the camera preview to be fullscreen and to maintain aspect ratio for all iOS devices (iPhone, iPads).

I was able to achieve Portrait mode (see code) and it works perfectly on iPhone 6/plus but the camera preview is stretched slightly on iPads possibly due to the fact that AVCaptureSessionPresetHigh's supported resolution is 1280x720. Anyone has any ideas on how to achieve single orientation (landscape or portrait only) and maintain aspect ratio?

My current code for starting a camera is

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // Initialize imageView to fullscreen
    imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:imageView];
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    [imageView setClipsToBounds:YES];

    self.videoCamera = [[FixedCvVideoCamera alloc] initWithParentView:imageView];
    self.videoCamera.delegate = self;
    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPresetHigh;
    self.videoCamera.defaultAVCaptureVideoOrientation =  AVCaptureVideoOrientationPortrait;
    self.videoCamera.defaultFPS = 30;
    [self.videoCamera start];
}

Notice I'm using FixedCvVideoCamera instead of the OpenCv CvVideoCamera class. The reason is that I'm subclassing and overriding CvVideoCamera's layoutPreviewLayer function to keep portrait mode.

 - (void)layoutPreviewLayer;
{
    if (self.parentView != nil)
    {
        CALayer* layer = self->customPreviewLayer;
        CGRect bounds = self->customPreviewLayer.bounds;
        int rotation_angle = 0;

        switch (defaultAVCaptureVideoOrientation) {
            case AVCaptureVideoOrientationLandscapeRight:
                rotation_angle = 270;
                break;
            case AVCaptureVideoOrientationPortraitUpsideDown:
                rotation_angle = 180;
                break;
            case AVCaptureVideoOrientationLandscapeLeft:
                rotation_angle = 90;
                break;
            case AVCaptureVideoOrientationPortrait:
            default:
                break;
        }

        layer.position = CGPointMake(self.parentView.frame.size.width/2., self.parentView.frame.size.height/2.);
        layer.affineTransform = CGAffineTransformMakeRotation( DEGREES_RADIANS(rotation_angle) );
        layer.bounds = bounds;
    }
}

Thanks in advance.

Opaque pointer to struct with template members

Suppose I'm building a linked list (the real data structure is completely different, but a linked list suffices for the question) whose nodes look like

template <typename T>
struct node
{
  struct node<T> *next;
  T data;
};

For my data structure, I have a lot of functions with return type struct node *, and I want the user to treat this type as opaque. In the linked list example, such a function could be for example get_next(struct node<T> *n) or insert_after(struct node<T> *x, struct node<T> *y). Only very few functions, namely those that allocate nodes or get/set their data field, need to know anything about T.

Is there a nicer way to "ignore T" and let the user interact only with something like a typedef struct node * opaque_handle for those functions that don't ever have to care about T? My gut reaction, coming from C, is just to cast to and from void*, but that doesn't sound very elegant.

Edit: CygnusX1's comment has convinced me that I'm asking for too many guarantees from the type system at the same time that I'm trying to circumvent too many of those guarantees. I will fall back to letting T be void * at the cost of casting and indirection.

Access Violation Error when creating an std::string from a unique_ptr char buffer

I'm currently trying to read a null-terminated ASCII string from another process. To do so, I created a class which acts as a memory reader with a generic readBytes function which acts as a wrapper for the Windows function ReadProcessMemory with error handling. My readBytes function works just fine, however my readAsciiString function (code below) is throwing Access Violation Errors when creating a new std::string from a unique_ptr char array.

std::string ProcessReader::readAsciiString(DWORD_PTR offset, int maxChars)
{
    auto buffer = std::make_unique<char[]>(maxChars);

    if (readBytes(offset, buffer.get(), maxChars))
    {
        int pos = 0;
        for (; pos < maxChars; pos++)
        {
            if (buffer[pos] == '�')
                break;
        }

        auto returnBuffer = std::make_unique<char[]>(pos);
        memcpy(returnBuffer.get(), buffer.get(), pos);

        // The program breaks here reporting an Access Violation
        // trying to writing to offset 0x00000000FFFFFFFF
        return std::string(returnBuffer.get());
    }

    return std::string("");
}

Here is a screenshot of the code in Visual Studio with a breakpoint on the return line while watching both buffer and returnBuffer. Resuming the program causes it to crash on that very line.

Screenshot in Visual Studio

I'm relatively new to C++ and am struggling to see what I'm doing wrong. Am I approaching this the wrong way?

Trying to create an iOS WKWebView with a size smaller than the screen programmatically

Im starting with a simple app that just shows a web view using WKWebView. Everything builds, and works okay, except that it is always fullscreen. Ideally it would not extend under the iOS status bar at the top. It needs to be lowered by 20px to be below it. I have searched extensively for a solution but nothing changes the size. Nothing is setup in InterfaceBuilder, I'm doing everything programmatically. Using Swift.

This seems like something basic that many apps with a WKWebView would do. It should be simple. I'm probably missing something obvious. Any help is appreciated. Thanks in advance.

This is what I have so far:

import UIKit
import WebKit
class ViewController: UIViewController, UIGestureRecognizerDelegate , UIWebViewDelegate, WKNavigationDelegate  {

    let url = NSURL(string:"http://stackoverflow.com")
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: CGRect( x: 0, y: 20, width: 380, height: 150 ), configuration: WKWebViewConfiguration() )
        self.view = webView
        self.view.frame = webView.frame
        let req = NSURLRequest(URL:url!)
        webView.loadRequest(req)
        self.webView.allowsBackForwardNavigationGestures = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Many thanks Emilio!! The adjusted code works perfectly!

import UIKit
import WebKit
class ViewController: UIViewController, UIGestureRecognizerDelegate , UIWebViewDelegate, WKNavigationDelegate  {

    let url = NSURL(string:"http://stackoverflow.com")
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: CGRect( x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height - 20 ), configuration: WKWebViewConfiguration() )
        self.view.addSubview(webView)
         let req = NSURLRequest(URL:url!)
        webView.loadRequest(req)
        self.webView.allowsBackForwardNavigationGestures = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

GMSMapView does not occupy full bounds

I've designed the following layout on XCode:

enter image description here

The button Layout (Cancel, Sign Up) is pinned to the bottom layout guide. On top of that are 3 equally sized UIViews, each with 1px vertical spacing in between them.

The remaining space is occupied by mapView, which is a UIView. It is pinned to the top, leading and trailing layout guide. It also has 8px spacing between the building number view.

When I run the application on my iPhone 6, I get this:

enter image description here

The map is not drawn in all available space. I don't know why:

When setting up the map, I do pass the bounds of the mapView:

class RegisterAddressViewController: BaseViewController, CLLocationManagerDelegate, GMSMapViewDelegate {

    @IBOutlet var mapView : UIView!

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.setupMapView()
        self.setupLocationManager()
    }

    func setupMapView(){
        let camera = GMSCameraPosition.cameraWithLatitude(-33.86,
                                                          longitude: 151.20, zoom: 6)
        self.gmsMapView = GMSMapView.mapWithFrame(self.mapView.bounds, camera: camera)
        self.gmsMapView!.delegate = self
        self.mapView.addSubview(self.gmsMapView!)
    }

    //...
}

I do not believe it's an AutoLayout issue since no warning appears in the console and the light grey background of the mapView indicates that the layout is set correctly.

Is there some configuration that I'm missing? Thanks.

mardi 28 juin 2016

Different values from C++ and JAVA using same code

I am translating an android image processing app to ndk. I'm facing the following problem: by logging the some value processed with java/android and others from C++/ndk, I got different values!!

I share with you the java and C++ codes:

Java:

double[] img2 = new double[w*h];
        y1 = new double[w];
        y2 = new double[w];
        for (int j = 0; j < h; j++) {
            for (int n = 2; n < w; ++n) {

                y1[n] = k1 * (img1[j*w+n] + exp(-alpha) * (alpha - 1) * img1[n-1+j*w]) ;

            }

            for(int n = w -3; n>=0; n--){

                y2[n] = k1 *(exp(-alpha)*(alpha+1)*img1[n+1+j*w] - exp(-2*alpha)*img1[n+2+j*w]);
            }

            for (int i = 0; i < w; i++) {
                img2[i+j*w] = y1[i] + y2[i];
            }



        }
        System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ java "+ (int)img2[w/2*h+h/2]);

C++:

double *y1 = new double[w];
    double *y2 = new double[w];
    double *img2 = new double[w * h];
    for (int j = 0; j < h; j++) {
                for (int n = 2; n < w; ++n) {

                    y1[n] = k1 * (img1[j*w+n] + exp(-alpha) * (alpha - 1) * img1[n-1+j*w]);

                }

                for(int n = w -3; n>=0; n--){

                    y2[n] = k1 *(exp(-alpha)*(alpha+1)*img1[n+1+j*w] - exp(-2*alpha)*img1[n+2+j*w]);
                }

                for (int i = 0; i < w; i++) {
                    img2[i+j*w] = y1[i] + y2[i];
                }



            }
    LOGI("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ native %d", (int)img2[w/2*h+h/2]);

The output is:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ native -2147483648
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ java 13502399

Knowing that I checked that the inputs on both sides(logs gives same values).

Forward touches to a UIScrollView

I have two view controllers. View controller A has a UIScrollView and presents view controller B. The presentation is interactive and controlled by the scrollView.contentOffset.

I want to integrate an interactive dismiss transition: When panning up, ViewController B should be dismissed interactively. The interactive dismiss transition should also control the ViewController A scrollView.

My first attempt was using a UIPanGestureRecognizer and setting the scrollView.contentOffset according to the panned distance. This works, however when the pan gesture is ended, the scrollView offset has to be animated to the end position. Using -[UIScrollView setContentOffset:animated: is not a good solution since it uses a linear animation, doesn't take the current pan velocity into account and doesn't decelerate nicely.

So I thought it should be possible to feed the touch events from my pan gesture recognizer into the scroll view. This should give us all the nice scroll view animation behavior.

I tried overriding the -touchesBegan/Moved/Ended/Cancelled withEvent: methods in my UIPanGestureRecognizer subclass like this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [scrollView touchesBegan:touches withEvent:event];
    [scrollView.panGestureRecognizer touchesBegan:touches withEvent:event];

    [super touchesBegan:touches withEvent:event];
}

But apparently something is blocking the scroll view from entering tracking mode. (It does go to dragging = YES but that's about it.) I verified the scrollView is userInteractionEnabled, not hidden and added to the view hierarchy.

So how can I forward my touch events to UIScrollView?

Print Quadruple Precision vector in C++ [duplicate]

I'm trying to print a quadruple precision vector using GCC 4.7.1 in CodeBlocks. This is the code:

#include <iostream>
#include <vector>
#include <quadmath.h>

...

int width = 46;
char buf[128];
for (std::vector<__float128>::const_iterator i = sol_r.begin(); i != sol_r.end(); ++i)
{
    int n = quadmath_snprintf (buf, sizeof buf, "%+-#*.20Qe", width, *i);
    if ((size_t) n < sizeof buf)
    {
        std::cout << buf << ' ';
    }
}

I get this error: undefined reference to 'quadmath_snprintf(char*, unsigned int, char const*, ...)'. What am I doing wrong?


Concerning the duplicate claim, the answer indicated as duplicate contains indeed part of the solution, but it is a general question including several different problems.

Users having problems in printing a quadruple precision vectors are most probably inexperienced (as I am) and would benefit more from a more concise answer and/or more precise sources.

The question asked here can be solved by checking out:

https://gcc.gnu.org/ml/gcc-help/2011-06/msg00148.html (add header as extern)

What is an undefined reference/unresolved external symbol error and how do I fix it? (link the relevant library as libquadmath)

Xcode 7.3.1 - Can't properly setup AWS

A year ago I had a project where I was using AWS. I forget exactly how it worked but it involved a BridgingHeader and no use of Frameworks.

I came back to this project today and none of the AWS stuff was working. I deleted all AWS/pod related files, got rid of the BridgingHeader reliance, cleaned the project, and proceeded to follow the pod-based instructions here:

http://docs.aws.amazon.com/mobile/sdkforios/developerguide/setup.html

However, the project still doesn't recognize any of the AWS libraries (getting the error "Use of unresolved identifier AWS...").

I saw a post by someone that suggested simply putting "import Framework" at the top of the files that use that Framework, but this doesn't work (it doesn't recognize AWSS3 when I put "import AWSS3", for example).

Then I saw advice that suggested figuring out the correct "Framework/Header/Library Search Paths" and so I created a brand new project, copied the podfile, and ran pod install. In this new project I am getting the error:

ld: warning: directory not found for option '-F/Users/username/Library/Developer/Xcode/DerivedData/TestProj-gmhzshcpuyuvaffaocakhunyepaw/Build/Products/Debug-iphonesimulator/AWSAutoScaling'

for each of the AWS libraries.

When I go into the target build settings, I see that the Framework Search Paths have strings relating to the AWS libraries, but when I delete them I then get the error "ld: Framework not found AWSAutoScaling".

I tried giving the direct path to the respective folders but I get the same error.

Qt .5.7 issue with QMessangeLogger and QList<int>

I was making a program which will conver text to pixel image and I occured some problems while trying to compile the code.

First problem is with QMessangeLogger:

C:QtQt5.7.05.7mingw53_32includeQtCoreqlogging.h:158: błąd: expected ',' or ';' before 'QMessageLogger'
 #define qDebug QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC).debug 

When I'm double clicking on it, it takes me back to one of Qt's main files.

Second problem is with Qt list:

 F:GraphicalCrypterGraphicalCrypterencryptmy.cpp:46: błąd: cannot convert 'QList<int>' to 'int' for argument '1' to 'constexpr QRgb qRgba(int, int, int, int)'
             value = qRgba(intArray[index-3], intArray[index-2], intArray[index-1],intArray[index]);

Here is my code :

//encryptmy.cpp http://pastebin.com/mnLqNHAy

//encryptmy.hpp http://pastebin.com/qyhYE9v7

//main.cpp

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "encryptmy.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    enCryptMy enryptmy;
    engine.rootContext()->setContextProperty("enCryptMy", &enryptmy);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

The QList error is appearing in line 46 in my file (link to pastebin). And the first one appears in qlogging.hpp in line 158. Just for sure, I have not changed anything in this file.

What is wrong with this code? I've tried several methods to fix those error but none helped.

Thanks in advance!

Trying to connect Facebook login via FirebaseUI Auth but having an issue with authUI.delegate = self

I am attempting to connect Facebook login via FirebaseUI Auth however I cannot get the Facebook connect button to appear in the instanced authViewController. Platform: iOS, Language: Swift 2.0, Latest stable Xcode release

Everything is working as it should as far as pulling up an instanced authViewController. The e-mail/password option is present and actively creates a new user in my Firebase database.

The problem I am having occurs when trying to implement Facebook login functionality;

In my AppDelegate.swift file I have the following:

import Firebase
import FirebaseAuthUI
...
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    FIRApp.configure()
    let authUI = FIRAuthUI.authUI()!
    authUI.delegate = self

    return true
}

The error I'm getting is "Cannot assign value of type 'AppDelegate' to type 'FIRAuthUIDelegate'" - basically I can't get the following line to work; authUI.delegate = self

I have read all documentation and browsed open/closed issues on implementation at the project's gitHub repo here: https://github.com/firebase/FirebaseUI-iOS/tree/master/FirebaseUI

I have looked over a previous StackOverflow question that is similar in nature here; How to use FirebaseUI for Google authentication on iOS in Swift?

I have attempted to copy the code from the above Stack Overflow since he states he did get more options to appear using his code (his question is about an error further down the line regarding authentication) but I still run into the same self delegation error. I have tried assigning FIRAuthUIDelegate to AppDelegate but it does not conform. What am I missing?

QuickSort in C++ will not finish sorting

Could someone please help me and tell me why quick sort algorithm will not sort the final element? When I input: 6 89 2 78 12 19 99 43 7 63 I get an ALMOST sorted: 2 6 7 12 78 19 43 99 63 89

I have tried to figure this out my self, but when I work my way thought the code at some point I get lost doing a desk check.

#include <iostream>
using namespace std;

// function prototypes
void quickSort(int arrayList[], int left, int right);
int choosePivot(int arrayList[], int listSize);
int partition(int array[], int left, int right);
void printArray(int theArray[], int Size);
// void swap(int value1, int value2);

int main()
{
    int myList[] = {6, 89, 2, 78, 12, 19, 99, 43, 7, 63};
    printArray(myList, 10);
    quickSort(myList, 0, 9);
    printArray(myList, 10);

    //int myList2[] = { 7, 4, 9, 10, -9 };
    //printArray(myList2, 5);
    //quickSort(myList2, 0, 5);
    //printArray(myList2, 5);


    cin;
    getchar;
    getchar;

    return 0;
}


void quickSort(int arrayList[], int left, int right)
{
    //if (left < right)
    if(right > left)
    {
        int p = partition(arrayList, left, right);

        printArray(arrayList, 10);
        quickSort(arrayList, left, p-1);
        quickSort(arrayList, p + 1, right);
    }
}

// left (index value) - left most part of the array we are working on
// right (index value) - right most part of the array we are working on
int partition(int array[], int left, int right)
{
    //int pivot = array[left]; // I will have to write a function to find the
    //  optimum pivot point, this is the naive solution
    int pivot = array[(left+right)/2];


    int i = left;
    int j = right;
    int temp;
    while (i < j)
    {
        //cout << "in the loop" ;
        while (array[i] < pivot)
            i++;
        while (array[j] > pivot)
            j--;
        if (i < j)
        {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
        }
    }

    return i;
}

void printArray(int theArray[], int Size)
{
    for (int i = 0; i < Size; i++)
    {
        cout << theArray[i] << " ";
    }
    cout << endl ;
}

UITableView Delegate Method not getting called?

I' m trying to extract the UITableView Delegate method into a base class called BaseTableProvider

//BaseTableProvider.h
@protocol RSTableProviderProtocol <NSObject>

- (void)cellDidPress:(NSIndexPath *) atIndexPath;

@optional
- (void)cellNeedsDelete:(NSIndexPath *) atIndexPath;

@end

@interface RSBaseTableProvider : NSObject <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, weak) id<RSTableProviderProtocol> delegate;

@end
//BaseTableProvider.m
@implementation RSBaseTableProvider
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    return cell;
}
@end

And then I create a subclass of BaseTableProvider, and override two UITableViewDelegate Method in the subclass

//RSFeedListTableProvider.h
@interface RSFeedListTableProvider : RSBaseTableProvider

@end

//RSFeedListTableProvider.m
@implementation RSFeedListTableProvider

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RSFeedCell *cell = (RSFeedCell *)[tableView dequeueReusableCellWithIdentifier:kFeedCell];

    if(cell == nil){
        cell = [[RSFeedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kFeedCell];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    Feed *feed = (Feed *)self.dataSource[indexPath.row];

    if (feed != nil) {
        cell.titleText = feed.title;
        cell.subTitleText = feed.summary;
    }


    return cell;
}

@end

I initialized the ListTablerProvider in a ViewController.

//RSFeedListViewController.m
@implementation RSFeedListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    _feedListView = [[RSFeedListView alloc] init];

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    _provider = [[RSFeedListTableProvider alloc] init];
    _provider.delegate = self;

    return self;
}

#pragma mark -- Life Cycle

- (void)loadView{
    RSFeedListView *aView = [[RSFeedListView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    self.feedListView = aView;
    self.view = aView;

    self.feedListView.tableView.delegate = _provider;
    self.feedListView.tableView.dataSource = _provider;
}

But I can't see the cell built on the screen.I debuged the code found that UITableView Delegate Method in RSFeedListTableProvider was not called.Any one can help me?Thanks!

C++ beginner - trying to write a function but getting a identifier...is undefined

I am a student and am tasked with creating a program that will determine if a person is rich or not. My code is below and I keep getting an error that identifier "isRich" is undefined. Can someone help me figure out where I went wrong?

EDIT assignment instructions removed, since the error is in the syntax, not the logic

#include "stdafx.h"
#include <iostream> //for input and output
#include "Cusick Project 5.h"
using namespace std;


void calcWealth(int age, long cash, int dependants, long debt)
{

cout << "Please enter your age: ";
cin >> age;
cout << "Please enter the amount of cash on hand: ";
cin >> cash;
cout << "Please enter the amount of dependents you have: ";
cin >> dependants;
cout << "Please enter the amount of money you owe";
cin >> debt;

bool isRich(int *age, long *cash, int *dependants, long *debt);
{
    long trueCash;
    bool status = false;

    trueCash = cash - debt;

    if (dependants == 0)
    {
        if (trueCash >= 1000000)
        {
            status = true;
        }
        else
            status = false;
    }

    else if (age < 40)
    {
        trueCash = trueCash - (dependants * 150000);
        if (trueCash >= 1000000)
        {
            status = true;
        }
        else
            status = false;
    }

    else if (age > 39 && age < 51)
    {
        trueCash = trueCash - (dependants * 75000);

        if (trueCash >= 1000000)
        {
            status = true;
        }
        else
            status = false;
    }

    else
    {
        trueCash = trueCash - (dependants * 25000);

        if (trueCash >= 1000000)
        {
            status = true;
        }
        else
            status = false;
    }
  }
}

int main()
{
    int age;
    long cash;
    int dependants;
    long debt;
    bool status; 

    cout << "Welcome to the wealth indicator..." << endl;

    calcWealth(age, cash, dependants, debt);

    if (isRich(status) = true)
    {
        cout << "Congratulations!  We consider you as being "rich."" <<     endl;
    }

    else
    {
        cout << "I am sorry!  You are not yet "rich."" << endl;
    }
}