dimanche 31 juillet 2016

Is there a "tag" correspondent?

I'm wondering if there is another thing such as the tag?

I'm already using tags on my images but I have to use multiple tags in order to create my code, which I haven't found a way to do... Therefore I'm wondering if there is another thing that works similar to the tag? Another way to "mark" an image?

(image.tag = 1) ---> example of a tag.

how to parse a date time string that includes fractional time

I have a datetime string as : "20:48:01.469 UTC MAR 31 2016", I would like to convert this string representation of time to a time tm structure using strptime, but my format string apears wrong. What should I use for fractional seconds? %S or %s or aomething else? Please advise. Code snippet is as below:

tm tmbuf;
const char *str = "20:48:01.469 UTC MAR 31 2016"
const char *fmt = "%H:%M:%s %Z %b %d %Y";
strptime(str,fmt,&tmbuf);

Starting Tab - UITabBarController Swift iOS

I've just created a tab UIViewController in Swift, brand new, no code. I wanted to know how I could change which tab the app starts on. For example, it has view 1 and view 2. At the bottom it has two tabs, tab 1 and tab 2. How could I get it to where the tab and page it starts on is tab 2, view 2. Instead of always opening and starting on the first tab. Thank you for the help!

`use_frameworks!` and images - how to use them in the client project's Storyboard?

When including my pods with the use_frameworks! directive, I have to include the images via code the following way:

UIImage *image = [UIImage imageNamed:@"myImage" inBundle:[NSBundle bundleWithIdentifier:@"org.cocoapods.MyPod"] compatibleWithTraitCollection:nil];

That works perfect and as intended; but how can I reference an image in the client project (not! within the pod)? When I only enter the image name in Interface Builder the image is not shown...

What is the significance of x in the address of a variable?

I am trying to print the address of a data member of a class:

#include <iostream>

struct test { int x; };

int main() {
    test t;
    std::cout << &t.x << std::endl;
}

The output is:

0x23fe4c

I don't understand how this points to a memory address. I want to know the meaning of this way of representing addresses.

iOS 10.0 Speech Recognition Error kAFAssistantErrorDomain

I try using speech recognition as below

    let urlpath = Bundle.main().pathForResource("myvoice2", ofType: "m4a")
    let url:URL = URL.init(fileURLWithPath: urlpath!)

    let recognizer = SFSpeechRecognizer()
    let request = SFSpeechURLRecognitionRequest(url: url)
    recognizer?.recognitionTask(with: request, resultHandler: { (result, error) in
        print (result?.bestTranscription.formattedString)

    })

The result is nil, I debug and see the error as below

Error Domain=kAFAssistantErrorDomain Code=1101 "(null)"

Do you have any idea?

How to autofill windows user password

system("runas /user:username myprogram.exe");
//------read user password file-----//

It won't work because when program proceeds to the system command process, it will stop to get to the reading process until user him/herself has finished the password, and that's not what I want.

So is it possible to read user password file and then automatically fill it into where users are expected to fill in themselves?

Thanks!:)

sharing a link opened in safari in ios to my application?

I need help about this problem.

I have a functionality in my application to share links with other users, what I need to do is:

  1. Open any link in safari browser
  2. Directly some action on safari browser to share that link in my application.

Is this possible in iOS to share a link from browser to the app directly.

Need help about this.

Regards.

What is the difference std::transform and std::for_each?

Both can be used to apply a function to a range of elements.

On a high level:

  • std::for_each ignores the return value of the function, and guarantees order of execution.
  • std::transform assigns the return value to the iterator, and does not guarantee the order of execution.

When do you prefer using the one versus the other? Are there any subtle caveats?

How to get Boost libraries binaries that work with Visual Studio?

Here's a question you may have seen around the 'nets in various forms...summed up here for you googling pleasure :-)

I have a project that is built with Microsoft's Visual Studio and uses functionality from boost (http://www.boost.org/). I already have my project working with some of the libraries that are header only (no binary library needed to link with). How or where can I get the windows binaries for the other libraries?

Core Data relationship between existing entities

I have two tables of data. One is table_A(id, x, x, b_id) and table_B(id, x). I would like to add a relationship between b_id from table_A to id of table_B. I already have a JSON data like that, and I tried with Xcode to make so connection, but all I can make is a new relationship between those two.

I'm new to this, so would apreciate any help.

How many constructors are defined for a class?

So I'm preparing for an upcoming C++ exam and came across this question about classes and constructors: "How many constructors does the class Fraction have?"

class Fraction {
//...
public:
   Fraction(int numerator = 0, int denominator = 1);
//...
}

I thought it's only one, but they suggested there are 3:

Fraction();
Fraction(n);
Fraction(n, d);

Or in other words: Is a function with default values an overloaded function?

Could a very long Class function member defined in header file?

I defined a class in header file and implemented its function in same header file. I didn't put inline keyword with function definition because I think compiler will regard it as a inline function by default -- but inline is only a hint to compiler, right? What if compiler doesn't regard it as inline function because of its length? I never get error message 'multiple definitions' in reality.

struct tmp {
    void print() {
       ...(very long)
     }
};

Firebase: How to store Videos in storage and then store video URL in database?

So I am using Firebase for the first time. I have read that you should store videos in Storage and then store that unique URL in their Database. How would I take this approach? For example if a user request a specific video to play how would I grab the URL from the database and then with that url pull the video out of the database?

Thank for the help and excuse my inexperience with Firebase.

What is most optimal way to replace integer '0' with '1' in c++

I have a piece of code where I multiply two numbers but condition is none of those integer numbers should be 0. If it is 0, I need to make it to 1 so that it is not counted.

y=x*z // x>0, z>0. if x==0 then x=1, if z==0, then z=1;

I want to avoid "if" condition check on every variable and replace with 1. Is there a better way of doing it.

Recursive pugixml, can't get values

Well, I got code

pugi::xml_node text = doc.child("text").child("girl");

for (int i = 0; i < situations.size(); i++)
{
    std::cout << situations[i] << std::endl;
    text = text.child(situations[i].c_str()); // problem
}

After that code, I can't get any values from text, but straight using like

doc.child("text").child("girl").child_value("day1")

Is working. Need help. Thanks.

questions about lists on c++

Consider a List of strings that contains the following strings in the order given:

"bob" "ann" "sue" "ned":   [0]   [1]   [2]   [3] respectively

Give the contents of the List after each operation.

a. list.insert(2, "bob");
b. list.insert(5, "ann");
c. list.remove(0);
d. list.remove(3);

I got...bob, ann, bob, sue, ned;
 bob, ann, bob, sue, ned, ann;
ann, bob, sue, ned, ann;
ann, bob, sue, ann

is this correct?

How to draw or make custom route using MKMapView

I am trying to write an app that will show the route of a tram line. I have added the map, but I am having problems trying to find how to add this route to my app.

I have looked at MKOverlayRenderer and I think I have to add an image on top of the map to do this. There are some tutorials but they are outdated.

Can someone help me with this. Thank you

How to prevent size_t from being interpreted as pointer?

how can I change the signature of distanceTo(..) to make the compiler warn or error on a call with std::size_t as parameter?

class Point {
private:
  float value;

public:
  Point(float value) : value(value){};
  float distanceTo(const Point &point) { return point.value - value; }
};

int main() {

  std::size_t index = 1;
  Point start(1);
  Point end(4);
  float dist = start.distanceTo(index); // compiles, but should not!
  std::cout << dist;

  return 0;
}

"a template argument may not reference a non-external entity"?

What does it mean when GCC (4.9.x with --std=c++11) refuses a specific instantiation of a template, telling me:

 /myfile.cpp(28): error: a template argument may not reference a
non-external entity

what is a "non-external entity"?

Note: I'm not asking about a specific piece of code. I'm not asking why I got this message for my code. I just don't understand what this message means.

Why does IL2CPP run with no error and no output

My unity version is 5.3.4f, and I hava C# script as a.cs and compiled a.exe and it runs OK. Then I use IL2CPP to translate a.exe into C++ compiled exe a_il2cpp.exe with command:

il2cpp.exe --outputpath=a_il2cpp.exe --cachedirectory="obj_cache" generatedcppdir="generated_cpp" a.exe

But it shows no error and no output, do I miss something? I have C++ compiler installed.

What does "a template argument may not reference a non-external entity" mean?

What does it mean when GCC (4.9.x with --std=c++11) refuses a specific instantiation of a template, telling me:

/myfile.cpp(28): error: a template argument may not reference a non-external entity

what is a "non-external entity"?

Note: I'm not asking about a specific piece of code. I'm not asking why I got this message for my code. I just don't understand what this message means.

When debugging a visual c+ program, the file specified can't be executed

I made a simple hello world program. I clicked on "Start Debugging" and the window showed "Project is out of date. Would you like to build it?" As I click on "yes", the next window shows "There were build errors. Would you like to continue and run the last successful build?". I choose yes again, and it shows this window: (attached screenshot)enter image description here

C++, RapidXML: function to get total of siblings nodes

for example:

<something>
   <x/>
   <x/>
   <y/>
   <z/>
</something>

It must return 2, I thought about using, for this example:

int Get_total_x(){
   int total=0;
   for(xml_node<> *x=root_node->first_node("x"); x; x=x->next_sibling()){
      total++;
   };
   return total;
};

Does RapidXML has a especific function for that?

samedi 30 juillet 2016

Qt GUI open a file using push button

I need to create qt gui push button with line edit, where I press the button which leads to browsing a folder to find a textfile I want to import. The textfile will be parsed afterwards. I would prefer to use combobox but I have no idea how to browse the folder through gui. Perhaps something like QDir related stuff should work but please help.

Basically, I want to import/open a textfile using push button/combobox.

How to click button and move on next page?

I have UIScrollView with pagingEnabled=YES. I want to scroll in next page on button click but my code doesn’t work. When I press on button once I move to next page but when press again I move in the end page. How to click button and move on next page?

-(IBAction)aMethod:(id)sender
{
int i;
i = i+1;

[scroller setContentOffset:CGPointMake(scroller.frame.size.width*i, 0) animated:YES];
}

Writing to stream using ternary operator ? in C++

I have several points of type double. I want to write them in the stream only when they are not 0. Also I have to say which one it is, like this: x1=" value " y1=" value " and so on.. Is there any way to do it like this: << ( (x1 != 0) ? ( "x1="" << x1 << '"' ) : ' ') ) << ( (y1 != 0) ? ( "y1="" << y1 << '"' ) : ' ') ) or I have to make several if else statements?

after every 24 hours Firebase stopped working and when i update pods it again starts working

I am working on Firebase and i have one query. I have login trough firebase and fired insert, update, delete queries.

Here is my code:

[self.data observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
        NSArray *array = snapshot.value;
        NSLog(@"%@",array);
    }];

This block working perfectly but after every 24 hours it stops calling but if i update pod then again it starts working. please someone help me with this.

Reminder is not working

I want to remind the user based on time,but cannot achieve using this code,please give me any solution.This is my code:

NSDate *pickerDate = [self.StartDate date];

    UIApplication* app = [UIApplication sharedApplication];
    UILocalNotification* notifyAlarm = [[UILocalNotification alloc] init];

    NSDate *date1=[pickerDate dateByAddingTimeInterval:60];
    notifyAlarm.fireDate = date1;
    notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    //notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
    notifyAlarm.repeatInterval =NSCalendarUnitWeekday;
    notifyAlarm.soundName =UILocalNotificationDefaultSoundName;
    notifyAlarm.alertBody =self.EventText.text;
    //notifyAlarm.alertLaunchImage=@"in.png";
    [app scheduleLocalNotification:notifyAlarm];
    [self dismissViewControllerAnimated:YES completion:nil];

Facebook Messenger not showing up with UIActivityViewController

I am using UIActivityViewController in my app to provide options for users to share some text. enter image description here

Apps like facebook, twitter, whatsapp once installed they automatically show up as options with UIActivityViewController, but not Facebook Messenger.

Any special set up I need to do with Messenger? I am using objective c.

iOS AVCaptureSession: Reduce callback rate of audio recording

I have an AVCaptureAudioDataOutputSampleBufferDelegate implemented on my ViewController. My goal is to show the average power my audio recording.

The problem is that the callback

func captureOutput(captureOutput: AVCaptureOutput!, let didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!)

is being called too frequently (roughly 45 times per second, 10 would do).

How can I influence this? Do I have to set something in the AVCaptureSession or the AVCaptureAudioDataOutput?

keep user logged in ios app swift

I make a login and signup app when I run my app and login evrything is going ok but when I stop my app and run it again login page showing again can I make user loged in

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
    if (isLoggedIn != 1) {
        self.performSegueWithIdentifier("goto_login", sender: self)
    } else {
        self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String

    }
}

How to detect Left swipe and Right swipe for Stacklayout in Xamarin.Forms?

I have been trying to detect left swipe and right swipe for stacklayout. Things in which I need help are,

  1. Creating a stacklayout renderer to add swipe Gesture.
  2. How to detect user has swiped left or right.

Please provide a solution which works on cross platforms.

Providing an example for stacklayout renderer will be really helpful to acheive the swipe functionality in xamarin.forms

Objective-C the ^ operator

I'm a newbie in Objective C and trying to figure out what does the ^ operator? While exploring some source code i saw next construction:

dispatch_once(&onceToken, ^{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 13.f), NO, 0.0f);

    [[UIColor blackColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 20, 1)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 5, 20, 1)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 20, 1)] fill];

    [[UIColor whiteColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 1, 20, 2)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 6,  20, 2)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 11, 20, 2)] fill];   

    defaultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

});

And I'd like to know what is the ^?

Visual Studio C++ structure on Github

Currently, my project structure looks like this.

enter image description here

But my Github just have a single folder with all .cpp and .h inside it. How do I maintain the structure?

Can't believe a massive wave of downvotes for something people can just simply share knowledge. I am new to visual studio.

Objective-C highlight UIButton when selected / unselected

I have a UIButton inside a UIView, when the UIButton is selected I would like have a background colour of dark gray...is this possible?

UIView *toolbar = [[UIView alloc]initWithFrame:CGRectMake(10, 50, 40, 160)];
    [toolbar setBackgroundColor:[UIColor colorWithWhite: 0.70 alpha:0.5]];

    toolbar.layer.cornerRadius = 5;

    UIButton *penTool = [UIButton buttonWithType:UIButtonTypeCustom];
    penTool.frame = CGRectMake(5, 0, 30, 30);
    [penTool setImage:[UIImage imageNamed:@"pen-but" inBundle:currentBundle compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
    [penTool addTarget:self action:@selector(drawButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    penTool.autoresizingMask = UIViewAutoresizingNone;
    penTool.exclusiveTouch = YES;
    penTool.tag = 1;

    [toolbar addSubview:penTool];

Find object by tag (in swift)

I have a variable @IBOutlet var ImageViews: [UIImageView]! that holds my 36 UIImages from the storyboard. I have set a tag to one random Image;

ImageViews[5].tag = 5

I want to be able to find this Image through the tag only and change its background color.

(Image in ImageViews with tag 5)

HERE'S THE CODE IN C# maybe you can translate it? I can't.

Weird constructors behavior

#include <iostream>
using namespace std;

class Foo
{
public:
    Foo()
    {
        cout << 0;
    }
    Foo(Foo &f)
    {
        cout << 1;
    }
};

void someFunction(Foo f) {};

int main()
{
    Foo f1;           //displays 0 (as expected)
    Foo f2(f1);       //displays 1 (as expected)
    someFunction(f1); //displays 1 (why?)
    someFunction(f2); //displays 1 (why?)

    return 0;
}

I don't understand why function 'someFunction' calls second constructor. I thought it will just call first constructor, with no parameters, and displays 0.

Maybe I am missing something obvious...

iOS Push Notifications using NodeJS

I have a requirement to implement the server side code for pushing notifications to an iOS app. I have followed the link below.

https://blog.engineyard.com/2013/developing-ios-push-notifications-nodejs

The problem is I always get 'Insufficient credentials' message. I've also tried with another node.js module by name 'apn' but with no help.

Has anyone tried either of these modules successfully? Are there any other alternatives?

Spin bottle with UIGestureRecognizer

I am using this code now to spin bottle on button tap: @IBAction func spinButton(sender: AnyObject) { let rotateView = CABasicAnimation() let randonAngle = arc4random_uniform(360) + 720 rotateView.fromValue = 0 rotateView.toValue = Float(randonAngle) * Float(M_PI) / 180.0 rotateView.duration = 3 rotateView.delegate = self rotateView.repeatCount = 0 rotateView.removedOnCompletion = false rotateView.fillMode = kCAFillModeForwards rotateView.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) bottleImageView.layer.addAnimation(rotateView, forKey: "transform.rotation.z") } But how can I rotate the button using gesture? So the harder/faster I move my finger, the faster the bottle will spin

Add new View Controller to Navigation Table View controller in Interface Builder?

I have an app that has a table view controller embedded in a navigation controller. I would like to create another view controller in the navigation stack so that when a cell is tapped, the app goes to a detail view and maintains a back button in the leftBarButtonItem. What is the best way to create that relationship in interface builder with a storyboard?

I feel like I've done it before but I can't remember how or find a solution.

Override method from inner class that I'm extending

class A : public B {}

class B : public C {}

class C
{
 public :

     class D : public I<T1>
     {
         virtual void method() const;
     }; 

     class E : public I<T2>
     {
         virtual void method() const;
     }; 

     class F : public I<T2>
     {
         virtual void method() const;
     }; 
 public :
     D d;
};

I would like in class A to override 'method' in class D. Is it possible? I always get the message :

error: cannot define member function 'method' within 'A'

C++ Is it possible to encrypt data sent over a named pipe?

I have a named pipe server and a named pipe client that communicate with each other. But I don't want anyone to be able to read the data sent via the named pipe. The code is written in C++.

I have couple of questions:

1) is it possible at all tap into a named pipe?

2) if it is possible to tap into a named pipe, is it possible to encrypt data being sent via the named pipe?

Assertion failure while trying to pop views from the navigation stack

I'm trying to pop to a specific view controller that is in the navigation stack but I am doing something wrong as I am getting this error pop up when I try to execute the code

Assertion failure in -[UINavigationController popToViewController:transition:], /SourceCache/UIKit_Sim/UIKit-1912.3/UINavigationController.m:2229

Here is the code thats causing the issue

FirstViewController *firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController.xib" bundle:nil];

    [self.navigationController popToViewController:firstViewController animated:YES];

launch containing app from iOS8 Custom Keyboard

I want to launch my containing app.

I tried using URL schemes.

The URL scheme launched the app from other places - so the problem is not there.

Looks like this object is nil:

   self.extensionContext

thus i can't run this method:

[self.extensionContext openURL:url completionHandler:nil];

Can I launch my app? Do URL Schemes work in a custom keyboard?

thanks!

Will std::experimental::optional<> support references?

At the moment, boost::optional<> supports references but the std::experimental::optional<> on my system from libstdc++ does not. Is this reflective of what might make it into the standard?

I know that the optional proposal author spun off optional references as a separate proposal so that the main optional proposal would have a better chance of being accepted. Was the proposal for optional references rejected or did work on it stop?

Finding size of perfect quad tree

I need to find the size of a perfect quad tree. This means I have 1 root node that splits into 4 nodes that splits into 4 nodes etc.

so a quad tree of height 1 would be size 1 height 2 = size 5 (1 + 4) height 3 = size 21 (1 + 4 + 16) height 4 = size 85 (1 + 4 + 16 + 64)

etc..

I know that the size of a perfect binary tree can be found with: size = 2^(height+1)-1 So I believe that a similar equation exists for quad tree.

So what is it?

Disable single warning error

Is there a way to disable just a single warning line in a cpp file with visual studio?

For example, if I catch an exception and don't handle it, I get error 4101 (unreferenced local variable). Is there a way to ignore this just in that function, but otherwise report it in the compilation unit? At the moment, I put #pragma warning (disable : 4101) at the top of the file, but that obviously just turns it off for the whole unit.

vendredi 29 juillet 2016

Why does stringstream not move to next set of characters when cout?

string inputLine = "1 2 3";
stringstream stream(inputLine);

// Case One
int x, y, z;
stream >> x;
stream >> y;
stream >> z;
// x, y, z have values 1, 2, 3

// Case Two
cout << stream << endl;
cout << stream << endl;
cout << stream << endl;
// All 3 print out 1

For the above code, why is it when you assign to an int, stringstream moves to the next set of characters, but not with cout?

searchDisplayController deprecated in iOS 8

How do you correct the following so no warnings appear? What am I missing?

When correcting the searchResultsController to searchController it gives me an error "object not found"

if (tableView == self.searchDisplayController.searchResultsTableView) {
        cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [_content objectAtIndex:indexPath.row];
    }

    return cell;
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
  shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                       objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    return YES;
}

CarbonKit Tabbar transperant along with the Navigation bar

we are creating an app ios swift, we need to design screens as attached below. The red Colored are is CarbonKit Tabbar, I would like make those Tabbar and Navigation bar transperant as the back ground image should be shown from that Navigation bar and Carbont Kit Tabbar Attached an image for clear idea

Navigation Bar and Tabbar Transparant

How to Draw The View Controller with the Dyanamic Value

**  **

I have to make a view as image is below. I am confused and not able to darw Screen as Screen will have more Image on Bottom of Image as User will scroll the View and data on the Each time will come up Dynamically and Will on every time View Come up. Thanks any Help Appricated

Get base derived from

Suppose I have a class like so:

template<class T>
class Base{ };

Suppose I have another class like so:

template<class T, class Other>
class Derived :
  public virtual Base<T>, 
  public virtual OtherRandomClass<Other> 
{ };

Is there some way to create a template class to determine which version of Base (if any) a random class like Derived is derived from?

Downgrading C/C++ compiler on Fedora 23 to a MATLAB R2016a-compatible compiler

I would like to build MEX functions from C/C++ source code to enable MATLAB script access, but my current version of Fedora has a newer and incompatible GCC. I have tried removing the installed GCC and installing a 4.7.x version of GCC using sudo dnf gcc-4.7.x (with x = [1, 2, 3, 4]), but it seems that none of those versions are hosted on the Fedora package repositories.

Is there any other way to install older versions of GCC on the newer Fedora versions?

Apple Game Development Frameworks Comparison [on hold]

What's actually the difference between the Apple Provide 3D Game Development Frameworks and when to use which one:

  • GamePlayKit
  • Metal
  • SceneKit
  • GLKit

I have searched on Google a lot about the difference or comparison but didn't find any article or blog for comparison between them.

I know that SpriteKit is used for the 2D Game Development and currently its the only framework provided by Apple for 2D Game Development.

How to implement the following animation?

I want to ask how to implement the following number animation?I hope you can help me, thank you!

enter image description here

can use facebook pop to achieve it?

POPSpringAnimation *springAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerBounds];
springAnimation.springSpeed         = 0;
springAnimation.springBounciness    = 20;
if (self.testView.frame.size.width == 100) {
    springAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 50, 50)];
} else {
    springAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 100, 100)];
}
[self.testView.layer pop_addAnimation:springAnimation forKey:nil];

Multi display(monitor) support cocos2d-x

I'm currently investigating if cocos2d-x can support multi display(monitor) for windows. Is it possible for cocos2d-x? For example one monitor screen is for Gameplay and the other screen monitor is for animations effects.

Currently my solution for this is to create 2 application that will run in to two screen. Cocos2d-x for gameplay monitor and the other monitor will just use SDL for rendering the effects.

Is this approach will be good? Any suggestion for this?

advantages of template < auto > in C++17

What are the advantages of template < auto > that will (possibly) be introduced with C++17?

Is it just a natural extension of auto when I want to instantiate template code?

auto v1 = constant<5>;      // v1 == 5, decltype(v1) is int
auto v2 = constant<true>;   // v2 == true, decltype(v2) is bool
auto v3 = constant<'a'>;    // v3 == 'a', decltype(v3) is char

What else do I gain from this language feature?

Value categories in languages other than C++

I recently have learned about C++11's value categories. Frankly, I was astonished by all the nuances and subtleties. I thought C++ is a very complicated language that I had grasped reasonably well, but every now and then something jumps out and proves me simply naïve. I'm very curious whether there are other languages that have something similar to value categories. For example, I googled on Java but nothing interesting showed up. And I know C has lvalue/rvalue, but that's basically pre-C++11 C++.

Include First Argument in va_list object

Is it possible to include the first argument of a function within a va_list? I want to pass the arguments from one function to another function. int main(){ test(1,2,3,4,5,-1); } void test(int firstArg, ...){ va_list va; va_start(va, firstArg); passFunction(va); } void passFunction(va_list va){ int x; while((x = va_arg(ap,int))!=-1){ cout << x << endl; } } Output I Want: 1 2 3 4 5 Actual Output: 2 3 4 5 Is there any way to achieve this without explicitly passing the first argument to the function?

Unable To Ctrl-Drag From Table View Cell to Controller

I am learning about storyboards in iOS and I am having issues creating functions on cell presses in a Table View that is part of a tabbed view. I intend to share the view controller between the two tabs, and I have it working in the other tab, but when I try to ctrl-drag from the cell to the view controller I get nothing. Is there something I have to do to hook the table view up to my view controller that does not happen automatically?

How to get __FILE__ as absolute path on Intel C++ compiler

I've tried using the /Fc flag which works with visual studio but get a message that it isn't recognized by the intel compiler.

I'm trying to write a test which uses data from a directory relative to the cpp test file, however the executable will be deployed elsewhere so it's hard to get it relative to the exe... hence I'd like an absolute path at compile time! How else could I get a path relative to the current cpp file?

iOS 10 App Not Showing in Settings

I recently developed an iOS app using Xcode 8 beta. I ran it on my iPhone (which is currently operating on iOS 10 beta), and it worked fine.

However, my app uses the camera, and I have been attempting to have the user go to settings, and enable the camera.

But my app does not appear in the list of apps in settings. It does not show up in the developer section either.

How can I resolve this bug? Thanks.

admob iOS: To get test ads on this device, call: request.testDevices = @[ GAD_SIMULATOR_ID ];

This is an interesting error. What should I put in the GAD_SIMULATOR_ID slot? What does that mean exactly? Here's my code, directly from Google's Admob tutorial:

bannerView = [[GADBannerView alloc] initWithFrame:CGRectMake(self.view.frame.size.height, 0.0, GAD_SIZE_320x50.width, GAD_SIZE_320x50.height)];
bannerView.adUnitID = @"my adunitid";
bannerView.rootViewController = self;
[self.view addSubview:bannerView];
GADRequest *request = [GADRequest request];
request.testDevices = @[ GAD_SIMULATOR_ID ];
NSLog(@"%@", GAD_SIMULATOR_ID); //This returns "Simulator" if you were wondering
[bannerView loadRequest:request];

How to deny MSVC from including headers by itself

I wrote a small C++ code and compiled it in MSVS 2013. It compiled fine. However, I tried to compile it on Ubuntu using GCC and it gave an error that I am using std::abs which is not exist. Then I solved the problem by including cmath.

Why MSVS did not complain? Does it include some headers by itself. If yes, how can I deny MSVS from including whatever it wants so this kind of non cross-platform code disappears?

How do i get a sharing link for the app if I'm using UIActivityViewController?

I'm developing an iOS app and i haven't bought the dev licence yet, my app is about facts and jokes based on a more categorised view. So i added a button to share the same using UIActivityViewController and the string I'm passing is the joke and an appended string which says "Check out this app (in this place i want to include the app store's link so that others could connect to it)"

Any help would be appreciated. Thanks.

Convert from date string in unknown format

I have data that contains a date string.

Normally it would be in a 'Jan. 3, 1966' type format, but because of international differences, it may not always be exactly that.

I need to read the data in and convert it into a standard date string ('YYYY-MM-DD').

Basically this is what I have so far:

var dataString = 'Jan. 3, 1966'  
var dateFormatter = NSDateFormatter()  
dateFormatter.dateFormat = # I DON'T KNOW THE EXACT INPUT FORMAT !
let dateValue = dateFormatter.dateFromString(dataString)  

Swift 3 - URLRequest creation crashes

        let url = URL(string: "(SERVER_HOST)/post?fb_id=(fb_user)")
        var request = URLRequest(url: url!) // Crashes here

        Alamofire.request(request)
            .responseJSON { response in
                switch response.result {
                case .failure(let error):
                    onComplete(success: false)
                case .success(let responseObject):
                    onComplete(success: true)
                }
        }

The crash error:

fatal error: unexpectedly found nil while unwrapping an Optional value

It worked before the Swift 3.
It was NSURLRequest and it worked. What can I do in order to fix it?

Can a user defined function be called from an event handler? [on hold]

I am a beginner.I am trying to make a calculator using visual c++ 2012 and i want to know whether a user defined function can be called from an event handler.

Suppose if button 2 or 2 or 3 or ..... is pressed call a function that prints 1 or 2 or 3...... in a textbox ! If its possible supply a code using:

A button event handler where it calls a function say void f and prints text of the button in textbox .

In CLR project

Why use base class pointers for derived classes

class base{
    .....
    virtual void function1();
    virtual void function2();
};

class derived::public base{
    int function1();
    int function2();
};

int main()
{
    derived d;
    base *b = &d;
    int k = b->function1() // Why use this instead of the following line?
    int k = d.function1(); // With this, the need for virtual functions is gone, right?

}

Sorry for a noobish question but I am not a CompSci engineer and I would like to know this. Why use virtual functions if we can avoid base class pointers?

Addition of an integer with an hex string

What should I do to add an integer to an hex string.

Say my hex string is:

11'h000

And I want to add integer 7 to it. Output it should give should be

11'h007

If given 11'h00e, Adding integer 1 to it should give me 11'h00f.

Are there any predefined functions in c++? I could have write my switch-case statements to get it but looking for a compact way.

C++ Visual Studio - Regex Whitespaces

I'm having trouble with whitespaces on this topic, can someone help me out?

int main() {

    string test;

    regex foo("Daniels[[:w:]]+");

    cout << "Test me" << endl;
    cin >> test;

    bool result= regex_match(test, foo);
    cout << (result? "Match" : "No Match") << endl;
}

Im trying to get Daniel "Last Name", but it just won't take the whitespace.I also tried [[:spaces:]] but no luck. Any ideas?

I'm using VS Community

jeudi 28 juillet 2016

Add left/right margin to uitableviewcell with dynamic height

I want to add left and right margin to the cells in Table View. I used:

tableView.contentInset = UIEdgeInsetsMake(0.0, 10.0, 0.0, 10.0)

in swift, but it adds margin out of the page, and it's not possible to add contentInset to a TableViewCell.

I tried to add a UIView and add my controls under that, but now dynamic resize for the cells height doesn't work.

How can I add left/right margin to dynamic resized cells?

Thanks

UicollectionView scroll between views in swift ios?

My collection view is working great. It shows a grid of photos and lists hundreds of them. You can swipe vertically to scroll through them all. Life is good. However, I now have a new requirement. I need to be able to detect when the user is swiping left or right. I need to be able to intercept this gesture so I can attach behavior to left and right swipes while keeping intact my collection view's vertical scroll capabilities. Any ideas?

In swift?

How to read a fix-byte data from a c++ std::istream

How to read a fix-byte data from a std::istream without doing any extraction? For example, I have a variable sz of type size_t and I would like to read sizeof(size_t) bytes from the istream.

void foo(std::istream& is) {
  if(is.rdbuf()->in_avail() < sizeof(size_t)) return;
  // how to read to sz from istream is without extraction (advancing pointers)
  size_t sz;
}

unity flickering sprites on iphone5 only

I have my game almost ready, and it's working fine on iphone 6 and iphone 4, 4s, but when I run it on iphone 5 this happens: https://www.youtube.com/watch?v=wS7olrGqbQA

Basically all sprites flicker, except the background texture. You can't even see any sprites up until 3 seconds in the video. I'm using unity 5.3.2f1, if that makes any difference. Please help, I tried playing with settings but nothing works.

Firebase(url:"") function is not working

I have installed the firebase pod in my project and imported Firebase to my swift class but when i am trying to implement Firebase(url:"") function its not working it says :

Cannot call value of non-function type 'module Firebase'

I am using xcode 7.3.1

there is the pic of my code:

enter image description here

How to restrict objects private data member modification in C++?

please check the below code, i need a solution to restrict the modification of private data members of class A. please suggest.

class A{
private:
    int a;
    int b;

public:
    A(int i=0, int j=0):a(i),b(j){
        cout<<"A's constructor runs"<<endl;
    }
    void showVal(){
        cout<<"a: "<<a<<" b: "<<b<<endl;
    }
};

int main(){
    A ob1(10,20);
    ob1.showVal();

    int *ptr = (int*)&ob1;
    *(ptr+0)=1;
    *(ptr+1)=2;

    ob1.showVal();

    return 0;
}

Is it possible a signal handler interrupts another signal handler for the same signal?

C++ documentation states that:

"If a signal handler is executed as a result of a call to the raise function, then the execution of the handler is sequenced after the invocation of the raise function and before its return. [ Note: When a signal is received for another reason, the execution of the signal handler is usually unsequenced with respect to the rest of the program. —end note ]"

Does this means that a handler could interrupt another handler?

How to check if map.find() result is end C++?

I have a map

std::map<long long, string> directory;

I am trying to find a specific number, if that number is found in the map assign it to a variable. But it seems the if condition is not working, its entering the if even when the number is not found which is causing error. Whats missing ?

        auto it = directory.find(12345);
        string response = "value not found"
        if (it != directory.end());
        {
           response = it ->second;
        }

Iphone user agent redirection not working

I am using below code to redirect to my mobile website in .htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteCond %{REQUEST_URI} !^/mobile/
RewriteCond %{REQUEST_URI} !^/index.php/
RewriteRule ^(.*)$ /mobile/mysite/www/#/$1 [L,R=301,NE]

Its wworking fine with android. The site gets redirected correctly. However, when I test it on iphone, I get redirect too many times error.

What's causing the issue here?

Importing C++ proyect in Xcode

How do I import a C/C++ project(NS3, GNU-Radio) to Xcode 7? The main reason I want to do this is to get autocompletion and Quick Help definitions. This can be done in Eclipse by:

File > New > 'Makefile Project with existing code'

It would be nice to have the debugger working as well but not necessary

The answers I have found are mostly for Xcode 4 and seem not to work on Xcode 7

Thanks

Start on specific place on UIScrollView

I would like to know if there is a way to center a UIScrollview, if you will. Let me explain: I've made a ScrollView and connected it to some view controllers so that I can slide back forth, similar to as you would in snapchat. I have 3 view controllers. I wanted to know if there was a way that I could start off in the center view controller (Viewcontroller 2 or the "middle" view controller) instead of always starting on the very left. Thank you for the help.

Stop overscroll UITableView only at the top?

There is similar question Stop UITableView over scroll at top & bottom?, but I need slighty different functionality. I want my table so that it can be overscrolled at the bottom, but cannot be overscrolled at the top. As I understood,

tableView.bounces = false

Allows to disable overscrolling at both top and bottom, however, I need disabling this only at the top. Like

tableView.bouncesAtTheTop = false
tableView.bouncesAtTheBottom = true

Externally load Json with jquery.getJSON

I don't know if this is a duplicate post or not, sorry if it is. I'm using jquery.getJSON to load a json on my server which works just fine. Although, if I try and load a json file on a different server it doesn't work. I know I don't have any code here (because there's not much point) but I just want to know if I'm using it wrong or if it isn't supposed to load external files. I'm using the iOS Safari browser if that effects anything.

Is it possible to interleave parameter packs?

Is it possible, with C++11/14/1z, to have a templated construct with two parameter packs, and within it, instantiate some other templated construct with the two packs inteleaved? i.e. if the first pack is T1_1, T1_2, T1_3 and the second pack is T2_1, T2_2 and T2_3, the interleaved pack will be T1_1, T2_1, T1_2, T2_2, T1_3, T2_3? My guess would be "no", since an ellipsis should not be able to apply to two parameter pack element designators; but perhaps some kind of tuple-construction or recursive-instantiation trick could work?

Change the size of a GroupBox

I am new in Qt and C ++, I have a code and I want to change it, when I open the file .ui i find a GroupBox , I tried to change its size in the interface but it does not work, I tried to change it in the code but I can't find it, is that normal that it is in the interface and not in the code? and how to change it if it does, I expect your help and thank you.

Xcode 7 or 8 issue with Pods

Getting this error for pods in Xcode when trying to run app:

error: A cryptographic verification failure has occurred.

  • Tried reinstalling Pods/repo
  • Reinstalling Xcode(s)
  • Also doesn't run on simulators:

DTAssetProviderService could not start DTXConnection with Simulator

Also, running Sierra at the moment (yes, I know).

Getting Index of an Object from NSArray?

i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,

NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(@" %d",Aindex);

the value i get is something like 2323421. what am i possibly doing wrong??

string.find() returns true wrongfully

Well the code explains what i am trying to do

auto haystack = wstring(L"REGISTRYMACHINESOFTWAREWOW6432NodeData�Path");
auto needle = wstring(L"WOW6432NodeData�Name");
auto found = haystack.find(needle) != haystack.npos;
cout << found << endl;

it returns true although needle is different than haystack notice the former ends with Path while the latter ends with Name... how could i exactly tell if certain string contains another ?

How to prevent user to select and swap images at a same time from image library so that it doesn't to go edit view?

I am having a problem regarding selecting image from image library in iPhone(iOS 8.4). Here is my code: UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; imagePicker.allowsEditing = NO; imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentModalViewController:imagePicker animated:YES]; But if I select an image and swap that image at the same time it opens an edit view and then if I try to delete that image, my app crash. Is it a default feature of image library? Or can it be handled by code? Please let me know. Thanks in advance

Finding Rank of Kernel/Matrix using OpenCV

Basically I want to find the rank of a given kernel/matrix so that I can check whether it is separable or not? Is there a function in OpenCV to find the rank of a kernel? If I'm correct, we can use the compute method of svd class to find the singular values, but after that how do we calculate the rank? The below is the code I used. double k = 3; float kdata[] = {2,0,2,0,1,0,0,0,0}; Mat kernel(k,k,CV_32F, kdata); Mat s,u,v; SVD::compute(kernel,s,u,v);

Is a preprocessor needed for a viable language?

How useful is the C++ preprocessor, really? Even in C#, it still has some functionality, but I've been thinking of ditching its use altogether for a hypothetical future language. I guess that there are some languages like Java that survive without such a thing. Is a language without a preprocessing step competitive and viable? What steps do programs written in languages without a preprocessor take to emulate it's functionality, e.g. different code for debug and release code, and how do these compare to #ifdef DEBUG?

Trying to make rightBarButton appear after making it disappear using Swift

I currently am working on an app in Swift where in my viewDidLoad() method I have purposely hidden my rightBarButton on my navigation bar like this:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(TableViewController.dismiss))
self.navigationItem.setRightBarButtonItem(nil, animated: true)

However, under certain circumstances, I would like to display the rightBarButton. How would I do this? What would be the opposite of the above line of code? Just wondering.

Thanks in advance to all who reply.

Boost::accumulator's percentile giving wrong values

I am using boost::accumulators::tag::extended_p_square_quantile for calculating percentile. In this, I also need to feed probabilities to the accumulator so I did this m_acc = AccumulatorType(boost::accumulators::extended_p_square_probabilities = probs); where probs is a vector containing the probabilities. Values in the prob vector are {0.5,0.3,0.9,0.7} I provided some sample values to accumulator. But when I try to get the percentile using boost::accumulators::quantile(m_acc, boost::accumulators::quantile_probability = probs[0]); it returns incorrect values and even nan sometimes. What is wrong here?

TableView cell size to with respect to label size

I have a UITableView and have my own custom cell containing a UILabel inside the cell.

I want to increase the tableView row size according to the text in the label. I am using AutoLayout and my label have 20 padding from left and 8 padding from right,top and bottom.

I am stuck here because the label context is some time small and sometimes very large and i want to increase the size of that row when the text is increased.

mercredi 27 juillet 2016

Remove object from UIImageView

I want to remove an object from a UIImageView. In the collection I've got 36 UIImageViews that I use to randomly rotate and change the images. But after this code;

self.ImageViews[5].image = UIImage(named: "squirrel")

I want to remove the object (ImageViews[5]) so that it no longer will be changed ---- thereby I think deleting it temporary from the UICollectionView is the best solution.

Something like this?

ImageViews = ImageViews.filter() { $0 != ImageViews[5] }

segmentation fault (core dumped) when I try cout a const char *[i], what is the issue?

g++ compiler says:

segmentation fault (core dumped)

when this code is running:

#include <iostream>
using namespace std;

int main(){

const char *constantChars[3], *variableChars[3];
long int numbers[3];

for(int i=0; i<4; i++){
    constantChars[i] = "hello number: ";
    numbers[i] = i;
    variableChars[i] = (const char *) numbers[i];

    cout<<constantChars[i]<<variableChars[i]<<endl;
}

return 0;}

it crash when cout<<variableChars[i]<<endl in my for loop.

VTK continous display multiple images

I am a newcomer for VTK .I want to display three images,and update it,like video. I use example MultipleViewports show three picture.

  • 1.mapper->SetInputConnection(sphereSource->GetOutputPort());,how to change a matrix to type (vtkAlgorithmOutput *input)?
  • 2.After renderWindowInteractor->Start();, this program stops. How could I change the image data and fresh it? Another better ideas is welcome. Thanks.

Remove object from UICollectionView

I want to remove an object from a UICollectionView. In the collection I've got 36 UIImageViews that I use to randomly rotate and change the images. But after this code;

self.ImageViews[5].image = UIImage(named: "squirrel")

I want to remove the object (ImageViews[5]) so that it no longer will be changed ---- thereby I think deleting it temporary from the UICollectionView is the best solution.

Something like this?

ImageViews = ImageViews.filter() { $0 != ImageViews[5] }

How do I deallocate all derived dynamic memory of a member?

Say I have a class:

struct foo{
    foo* bar=nullptr;
};

Now if I use new to allocate memory like a chain:

foo instance;
instance.bar= new foo;
instance.bar->bar=new foo;
...

Then how can I delete all those children of instance in a single call to delete the top level instance, i.e. when I call destroy(instance); //dummy name then all those dynamically allocated memory are all freed?

view controller changed after cocoapods installation

I was trying to test alamofire in my Xcode project but after pod installation and cocoa-pods installation and setup instead of view controller i see root view controller and Dataviewcontroller. How can i change back it to only view controller. I am adding a snapshot of before and after the installation.

My Xcode version is 7.3.1

please help me out.... enter image description here

How to deep copy an abstract class array in C++

I have abstract class Figure. Then I have an array of it, and I want to resize it, but not sure how to do it.

Figure ** arr; //lets assume it's filled with some data
Figure ** temp = new Figure * [size + 1];
for(int i =0; i < size; ++i)
{
   temp[i] = new Figure(); //it doesn't let me to create object from the abstract class
   temp[i] = arr[i] //if I do this, once I delete arr, I will lose temp as well
}

Any help?

Which will take less time during execution?

In many programs, I have to take mod with 1000000007 and for bigger calculation I have to put it in the loop.

Here I have two options for doing this.

First:`

for(int i=0;i < n;i++){

   //my code for count

   count%=1000000007;
}

Second:`

for(int i=0;i<n;i++){ 

    // my code for count

    if(count > 1000000007)
        count%=1000000007;
}`

I want to know which will take lesser time during execution.

Find placement or order of word in UITextView

I want to find the position of a word in a textview, so that if I have a textview with 300 words, and the user taps on word number 100, a UILabel reads, "100" and so on.

This seems like a helpful place to start to select a word in a textview. And I can go here to get the word count of the textView. But beyond that I'm not sure.

Any ideas?

Qt adding child widget in resizeEvent

I have a widget W deriving from QFrame with layout set to an instance of QVBoxLayout. I wonder if the following resizeEvent implementation is correct or is it going to cause an infinite loop:

void W::resizeEvent(QResizeEvent *event) {
    for (/* some condition based on the new size of this widget */) {
        // Infinite loop or not?
        qobject_cast<QVBoxLayout *>(layout())->addWidget(new QWidget());
    }
}

So far it worked for me, is this by pure luck?

Crash after share by email or sms in iOS swift

I want to share some content. It my app crashes after I send email or sms. The emails and sms received. It works good with all other types. I added Social framework and imported Social to that class

My code:

    if let myWebsite = NSURL(string: "http://www.mstcode.com")
    {
        let messageStr = "Learn how to build iPhone apps"
        let shareItems = [messageStr, myWebsite]
        let activityController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            activityController.popoverPresentationController?.sourceView = sender
        }
        self.presentViewController(activityController, animated: true,completion: nil)
    }

Set overlay when dropdown appears on screen

I have a drop down button and when user clicks on it dropdown appears which is a tableview that is hidden.

- (IBAction)showDropDown:(id)sender {
    self.tableView.hidden = NO;
}

Now i want to set entire screen overlay to 66% just like a blurry screen only excluding button and tableView. They must be visible clearly. And when user made as selection...

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableView.hidden = YES;
}

And everything will be same again.

Compile FFmpeg as iOS 8 Framework

I successfully compiled FFmpeg with iOS 8.2 SDK thanks to https://github.com/kewlbear/FFmpeg-iOS-build-script and last version of gas-preprocessor (https://github.com/libav/gas-preprocessor).

However, I would like to package FFmpeg libraries as a iOS 8 dynamic framework due to legal constraints. I found resources to create iOS 8 dynamic framework however I cannot find any solution for FFmpeg.

Can anyone help me to package these librairies ? Thanks David

Regex to capture all text before { character - Objective C

How would I write a regex to capture all text before the { character but on the same line?

I tried something like the following:

pattern = @"({)";
regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
matches = [regex matchesInString:self options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches) {
    [string addAttribute:NSForegroundColorAttributeName value:        [UIColor colorFromHexString:@"#C41A16"] range:[match range]];
}

I'm trying to style the following CSS code such that p is colored and a is colored:

p {
    color: blue;
}

a {
   color: red;
}

How Do I Parse a Date Time String That Includes Fractional Time?

I have a date time string:

20:48:01.469 UTC MAR 31 2016

I would like to convert this string representation of time to a struct tm using strptime, but my format string isn't working.

Is there a format specifier for fractional seconds? Perhaps %S, %s, or something else?

Code snippet is below:

tm tmbuf;
const char *str = "20:48:01.469 UTC MAR 31 2016"
const char *fmt = "%H:%M:%s %Z %b %d %Y";
strptime(str,fmt,&tmbuf);

dllexport with vs15 don't export

i created a little plugin system that export few functions.

#define EXPORT extern "C" __declspec(dllexport)
EXPORT BOOL WINAPI LoadPlugin()
{
    return TRUE;
}
...

When i compile in command line, cl /LD plugin.cpp, it export my function which is obviously want i want, but i created a vs15 project and the function aren't exported anymore. I don't see the export in a debugger & GetProcAddress doesn't work anymore. The error code is 127. I guess i miss an option, but i cannot find it.

A macro to extract characters of its input text and generate a code using them

Is there any macro that can get a text as input like "abc" and by text I literally mean text like the one mentioned not an array or anything else, then extract characters of that text and generate a selective piece of code like ones below at compile time:

first example of a piece of code :

Func1(a);
Func2(b);
Func3(c);

second example of a piece of code:

{'a','b','c'}

How do i export json data to excel?

I have data in a table form. The data in table form has been called through json. I have created a button and i want to export those data to excel file with that button click. I am working on MFC.

enter image description here

As you see the button I need to click that and the data in the table should be exported in excel

Programmatically add a shared calendar ical link to iOS and/or Android Devices

I'm trying to create a link that lets you select your operating system and then adds a shared calendar to the device using a long link provided.

It's for a site that requires the user to be logged in and then they can view their unique ical link to add as a shared calendar that displays their scheduled events. However, the link is very long and I would like to programmatically add it to their device if possible as a new shared calendar.

Is this possible? Thanks so much.

Getting list of files in documents folder

What is wrong with my code for getting the filenames in the document folder?

func listFilesFromDocumentsFolder() -> [NSString]?{
    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if dirs != nil {
        let dir = dirs![0] as NSString
        let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as [NSString]
        return fileList
    }else{
        return nil
    }
}

I thought I read the documents correctly and I am very sure about what is in the documents folder, but "fileList" does not show anything? "dir" shows the path to the folder.

C++11 std::array

I'd like to use std::array from C++11 as a field of my own class. It takes two template parameters (first defines type of data, second defines size of an array).

But I know the second parameter only in constructor. I'm not familiar with C++11 standard, but I suppose that it's impossible to set a template parameter during execution.

Are there any alternatives for std::array? std::vector is probably a little too much, cause I will never change the size of it.

Implementation of knn

I at moment implementing kNN in c++. I know how the algorithm works, but was wondering whether there was a smart method for computing the distance between a new observation and and its k nearest neighbours?...

The only way i see that possible, is to test all the point against the observation and then determine from that which ones is the closest to the new observation.

I know that kNN is a time comsuming process, but is this really the reason.
It seems like a too simple problem?

iOS: SwiftyJSON parsing from Alamofire is an array. Getting null when trying to parse

the api request returns something like this:

[  
   {  
  "macAddress":"x:x:x:x",
  "hatInfo":{  
     "hatHierarchyString":"hello",
     "floorRefId":"xxx",
     .....

I am using swiftyJSON to parse this, I got data from Alamofire request:

let json = JSON(data)
let mapHeir = json[0]["hatInfo"]["hatHierarchyString"]
print(mapHeir)

This returns null, I tried:

let mapHeir = json[0]["hatInfo"]["hatHierarchyString"].string
let mapHeir = json[0]["hatInfo"]["hatHierarchyString"].stringValue
let mapHeir = json["hatInfo"]["hatHierarchyString"]

and all of them return empty. How can I get to hatHierarchyString?

Ask nickname for clients on omniorb [on hold]

I want to improve my app server/client done a couple of days ago (completed with your help). I readed on omniorb help that is multithread native, meaning execute multiple clients connected to one server. I want to use that multithread feature for giving each client an alias in every client start. Some like: hello new client, please input a name Using java rmi i could give an alias for each client, i dont think its the same but its similar. Thank you.

mardi 26 juillet 2016

VC 8.0 to VS2013 Error

I am using a code in:

https://sourceforge.net/projects/ewavetrade/

Apparently, it is written with VC++ 8.0 and I'm using VS 2013. I get this error:

Error 101 error C2065: 'CString' : undeclared identifier D:program filesmicrosoft visual studio 12.0vcincludestdio.h 211 1 ElliotEngine

on this line,

_Check_return_ _CRT_INSECURE_DEPRECATE(fopen_s) _CRTIMP FILE * __cdecl fopen(_In_z_ CString* _Filename, _In_z_ const char * _Mode);

Could you please help me? Thanks :)

Proper implementation of handleInputModeList in Custom Keyboard

A new API has been added in iOS 10 to present the list of other keyboards the user can switch to - the same list that appears when users long press the globe on a system keyboard. The declaration of the function is as follows:
func handleInputModeList(from view: UIView, with event: UIEvent)

My question is, what's the proper way to generate a UIEvent to supply? I was planning to call this function using a UILongPressGestureRecognizer but this API doesn't reveal UIEvents.

C++ - Maximize sum of two elements in the array and their indexes

How do I solve following programming riddle in O(N)?

Array of integers Tab[N]

Find max(Tab[K] - K + Tab[L] + L)

where 0 <= K <= L <= N

The only solution I can come up with is O(N^2) where I compare each element and update maximum sum.

int curr_max = INTEGER_MIN;
for(int i = 0; i < N; i++){
    for(int j = i; j < N; j++){
        curr_max = max(Tab[i]-i + Tab[j] + j,curr_max);
    }
}

CloudKit Error "User Deleted Zone" (28/2042)

In my app, one of my users is no longer able to access the application iCloud container. The log file contains these errors:

<CKError <redacted>: "User Deleted Zone" (28/2042); 
server message = "Zone was purged by user"; 
uuid = <redacted>; container ID = "iCloud.<redacted>">
  • Has anyone an idea on what the user may have done to unlink the app from his iCloud storage?
  • How should I react within my application to this error to get it "back on track"?

iOS TableViewCell Not Filling Width

I have a UITableView with custom cell. The cell is not filling the entire width, as seen by the photo below. I have created the custom cell using IB and NIB file. I just dragged a UITableViewCell, added my labels and all. It uses AutoLayout, and I even have the far right label pinned to the right edge for trailing, but still it clips it off.

enter image description here

Are C/C++ library functions and operators the most optimal ones?

So, at the divide & conquer course we were taught: Karatsuba multiplication Fast exponentiation Now, given 2 positive integers a and b is operator::* faster than a karatsuba(a,b) or is pow(a,b) faster than int fast_expo(int Base,int exp) { if (exp==0) { return 1; } if (exp==1) { return Base } if (exp%2==0) { return fast_expo(Base,exp/2)*fast_expo(Base,exp/2); } else { return base*fast_expo(Base,exp/2)*fast_expo(Base,exp/2); } } I ask this because I wonder if they have just a teaching purpose or they are already base implemented in the C/C++ language

Swift. Change Color of Custom Tableview Cell Label when selected

I have a Custom Tableview cell in swift and in that cell a label.

I want to be able to change the label when you select a cell.

How can I reference my custom UITableviewCell label in didSelectRowAtIndexPath

In Objective C to reference my custom cell in didSelectRowAtIndexPath I would use the following:

MPSurveyTableViewCell *cell = (MPSurveyTableViewCell *)[tableViewcellForRowAtIndexPath:indexPath];
cell.customLabel.TextColor = [UIColor redColor]; 

What must I do in swift to achieve the same result?

Swift Extensions

I am curious as to what is the purpose of writing extensions for a class that you can already add code?

For example, in Ray Wenderlich's AlamoFire tutorial,

He has a ViewController class, but he writes an extension for that ViewController for his Networking Functions and UIImagePickerControllerDelegate methods. Is the only reason he is writing extensions is for the purpose of dividing up code into logical bits?

Is this a common practice or just personal preference?

UITabBarItem does not update image

For some reason, only one image of my UITabBarItem does not show up. This started to happen after I refactored the storyboards to organize them. When I run the app, no message is triggered to the debugger, it just don't show up. The image is being set in storyboard and nothing programmatically is being done to set it. It shows up in Interface Builder, but when I run the app it doesn't.

Already tried delete the image in catalog, rename it and perform clean up, but nothing helped.

how to convert string date to nsdate using formatter?

i follow stackOverflow answer and Write a code but i Don't know What happen.it won't work. plz,any one can solve it for me. i use fooling code....

        NSMutableArray *movieDate;
    NSArray *temp1 = [_dicUpcomingMovie objectForKey:@"results"];
    for (NSDictionary *temp2 in temp1)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

        NSString *datestring = [temp2 valueForKey:@"release_date"];
        //NSDate *myDate = [[NSDate alloc]init];
        [formatter setDateFormat:@"dd MMM,YYYY"];
        NSDate *date = [formatter dateFromString:datestring];
        NSLog(@"%@",date);
        [movieDate addObject:date];
        NSLog(@"%@",movieDate);
    }

so this is it. the above code was not work myDate object still nil

How to Implement Face Recognition in ios app ? Can Apple provide Face Recognition?

  • I am searching related to Face Recognition SDK or any documents. But i can't find any solution of that.
  • Here i can get Face Detection and i Know about the detection.
  • But i want Implement Face Recognition in my application.
  • I Read many documents.but i can't get any proper solution for that.
  • I implement login system with Face Recognition.
  • So please provide me any Proper Solution for it.

Thanks in Advance.

Accept Integer Input in Swift

Can someone please tell me how to read a set of integers from the keyboard for a console application using Swift?

I have tried the following method:

func input() -> String {
    let keyboard = NSFileHandle.fileHandleWithStandardInput()
    let inputData = keyboard.availableData
    return (NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String)
}

But this function will treat the entered value as a string. And converting the string to Int results in a nil value.

Is there is anything similar to scanf() or cin() like in C, C++ ?

how to download logs file using objective c

> In Xcode, go to Window -> Devices. > Select your device in the left panel. > Click the little arrow as shown in the screenshot below. http://i.stack.imgur.com/acpO7.png How to get above image contain refer above url and step. my question of how to fetch above image display all contain and write file. means my device which application open and how many time open data fetch. for example of me create this type application: https://play.google.com/store/apps/details?id=com.zerodesktop.appdetox.qualitytime&hl=en

How to produce deterministic binary output with g++?

I work in a very regulated environment where we need to be able to produce identical binary input give the same source code every time be build out products. We currently use an ancient version of g++ that has been patched to not write anything like a date/time in the resulting binaries that would change from build to build, but I would like to update to g++ 4.7.2. Does anyone know of a patch, or have suggestions of what I need to look for to take two identical pieces of source code and produce identical binary outputs?

Printing the values of an instantiated structure without using the names of the fields in C++

Can I do it?

For example consider the following structure:

struct bag {
     string fruit;
     string book;
     string money;
};

I want to print the values of the fields of an instance of the structure bag in a sequentially form and obtain an output like this:

apple
Computer Networking, A top-down Approach
100

But without using the names of the fields(fruit, book and money). Any help would be appreciated. The only information I know it is that all the fields are C++ strings.

Getting the nth line of a text file in C++

I need to read the nth line of a text file (e.g. textfile.findline(0) would find the first line of the text file loaded with ifstream textfile). Is this possible? I don't need to put the contents of the file in an array/vector, I need to just assign a specific line of the text file to a varible (specifically a int).

P.S. I am looking for the simplest solution that would not require me to use any big external library (e.g. Boost) Thanks in advance.

CS:GO Base Address "Client.dll"

I have been trying some memory management and I have stumbled upon a problem. I believe the offset for health is wrong. I am trying to read health. I dont really know how to find the base address and offset for health. I have tried to find the static address for health using cheat engine but i am not able to find it.

Thanks in advance!

Here is the code:

ReadProcessMemory(hProc, (LPCVOID)(0x00A30504), &pointed, 4, NULL);
ReadProcessMemory(hProc, (LPCVOID)(pointed + 0x000000FC), &currentHealth, 4, NULL);

use of unimplemented initializer 'init(contentURL:)

I've got a problem.When i integrated the MobilePlayer(Swift version) into my OC project using Cocoapods. I've also added the MobilePlayer into my Swift-bridge.h file.

Here come's the problem:

when i doing this

MobilePlayerViewController *player = [[MobilePlayerViewController alloc] initWithContentURL:url];

The Xcode warning me that MobilePlayerViewController.swift: fatal error: use of unimplemented initializer 'init(contentURL:)' for class 'MobilePlayer.MobilePlayerViewController' after i run it in simulator.

Had anyone know why? Thx

Unexpected lambda behavior C++ with Arduino

I'm trying to understand why the second millis() timer does not work as I would expect. Is there some encapsulation that I don't understand while using lambdas? Or maybe I'm just not seeing something!

the second expression in loop() does not print, the first does:

unsigned long timerVal = 0;
void setup() 
{
  Serial.begin(9600);
  Serial.println();
}
void loop() 
{
  [&timerVal](unsigned long currentTime){if(currentTime - timerVal > 1000UL) {Serial.println("Hello World"); timerVal += 1000UL;}}(millis());
  [&timerVal](){if(millis() - timerVal > 1000UL) {Serial.println("Why Not Me?"); timerVal += 1000UL;}};
}

Share video from youtube app to my app on ios

Is there anyway I can get my app to appear when I click the share button on a video in the youtube app on ios?

I know how to add my app to the open in option, by adding my doc types to Info.plist file, but is there a way to do something similar when the share button is pressed in the youtube app on ios?

Similar to android question answered here.

android youtube: share a youtube video TO my app?

strcmp() doesn't work with command line argument

i'm trying to pass arguments into main through the command line and then compare string in argv[1] with some strings in code. It doesn't work, always block else is executed even if i type exactly the same string! What's wrong?

    #include <iostream>
    #include <string.h>

    using namespace std;

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

    if (argc>2)
    {
        if (strcmp(argv[1], "ball ")==0)
        {...}
        else if (strcmp(argv[1], "dance ")==0)
        {...}

        else

         {
           cout<<"Ops"<<endl;
           cout<<argv[2]<<endl;
           cout<<argv[1]<<endl;
        }

Macro with some sort of condition

I'm trying to create an macro so safe me from some typing and make it nicer/easier to define an property, this is what I have in mind:

#define DefineProperty(Access, Type, Name) 
property<Access, Type> ##Name; 
void Set##Name(Type); 
Type Get##Name(void); 

Where Access is an enum with three possible values: ReadOnly, WriteOnly and ReadWrite. The method in the macro should only be defined if the access value is appropriate for the method.

Is this in any way possible for example using meta-programming?

Compare of std::function with lambda

How to compare of std::function with lambda?

#include <iostream>
#include <functional>
using namespace std;

int main()
{
    using Type = void( float, int );
    std::function<Type> a;
    auto callback = []( float d, int r )
    {
        cout << d << " " << r << endl;
    };  
    static_assert( std::is_same< Type , decltype( callback ) >::value, "Callbacks should be same!" );


    a(15.7f, 15);   
}

Because in case of first parametr of lambda would be int - code would compile with 1 warning. How to protect code?

Type 'UIViewController' does not conform to protocol 'WCSessionDelegate'

Since upgrading on Xcode 8 (Beta 1) and Swift 3 I have an error in this line:

class CloudViewController: UIViewController, WCSessionDelegate {

It says :

Type 'UIViewController' does not conform to protocol 'WCSessionDelegate'

This is my (with Xcode 8 and Swift 3 working) code:

override func viewDidLoad() {
    super.viewDidLoad()

    if(WCSession.isSupported()){
        self.session = WCSession.default()
        self.session.delegate = self
        self.session.activate()
    }
}

func session(_ session: WCSession, didReceiveMessage message: [String : AnyObject]) {

    print("didReceiveMessage")

    watchMessageHandler.getMessage(message)

}

This error also shows up in the WKInterfaceController classes.

lundi 25 juillet 2016

Is auto-chunking enabled by default when GZIP compression is used in the HDF5 C++ api?

I am writing an HDF5 file using the C++ HDF api and performing a few comparisons against the H5py Python library.

In the H5py Python library when a compression algorithm such as GZIP is used H5py will try to apply autochunking.

Does the same condition apply to the HDF5 C++ api? If so, how can I prove that chunks were automatically created when a compression algorithm, such as GZIP, was applied to the data sets.

Lambda key comparator for map

I'm trying to implement my own key comparator for std::map as follows:

auto cost_compare = [](const OffsetCoords& left, const OffsetCoords& right) { 
return (left == right); };

std::map<OffsetCoords, int, decltype(cost_compare)> cost_so_far(cost_compare);

where OffsetCoords is struct, vector of x, y values with overloaded operator==

code builds fine, but when I call cost_so_far.count(some_offsetcoords_variable) it throws exception 'Expression: invalid comparator'.

What's the proper way to do this?

Set of vectors ordered by vector size allowing same size

I have the following structure:

 auto comp = [](const vector<int>& a, const vector<int>& b) -> bool
    { return a.size() < b.size(); };
    auto path = std::set <vector<int>, decltype(comp)> (comp);

When I now insert via

path.insert(vector<int>{g.id(v)});

He inserts of size 1 only 1, of size 2 only 1 etc.

I want him ordered by the size, but he should compare really the vectors to avoid duplicates.

minGW STL containers get error "procedure entry point __gxx_personality_v0 not found in DLL [my exe path]"

I installed minGW g++ on windows 10. When I compile any code that uses STL containers, even such simple as

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> b;
    b.push_back(42);
    cout << b[0];
}

It compiles, but when I try to run it I get error:

“The procedure entry point __gxx_personality_v0 could not be located in the dynamic link library [my exe path]"

I'm compiling just with:

g++ a.cpp

Swift: Skipping first (and more) screens in a Navigation Controller stack

I have a NavigationController in my app. The first screen in its stack is TermsConditionVC, then LoginVC then MainVC. When I run, it goes directly to TermsConditionsVC.

However, depending upon, if the user has once agreed to the TermsConditions and/or is Logged in or not, I wish to skip TermsConditionsVC and/or LoginVC and go straight to MainVC.

It does not make sense for me to have multiple Navigation Controllers in this situation but I cant figure out how to skip screen (especially the very first screen in the Navigation Controller stack?

C++ Convert string to TCHAR*

Below is my code :

string szDllPath = "12345";
size_t size = szDllPath.length();
TCHAR* wArr = new TCHAR[size];
for (size_t i = 0; i < size; ++i)
    wArr[i] = _T(szDllPath[i]);

cout<<szDllPath<<endl;
cout<<wArr<<endl;

And I get this :

enter image description here

I don't understand why I get the extra characters, and how to solve it ?

iOS App Upload is getting CFBundleShortVersionString error message

So I am trying to upload my app to the App store, and I am getting this error message.

ERROR ITMS-90060: "This bundle is invalid. The value for key CFBundleShortVersionString 'HEAD based on 1.0' in the Info.plist file must be a period-separated list of at most three non-negative integers."

If I open the log it gives me, you can clearly see the version short string is correct.

<software_assets apple_id="456805313"
        bundle_short_version_string="27.1.1"
        bundle_version="3221"
        ....
</software_assets>

What am I missing?!?

C++ Native Win32 simple Edit Control

I'm currently experimenting with making a little native Win32 executable. So no external libraries/wrappers/frameworks. I added a simple edit control and a button. The problem is that I can't change the text of an Edit Control in the Properties window of Visual Studio. The default text is Sample edit box and that doesn't show up in the Properties window (IDC_EDIT1), so I can't change it.

How can I change the text of an Edit Control (preferably within the properties window)? Also, is an edit control part of the MFC library?

Calling C++ class methods via a function pointer

How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:

class Dog : Animal
{
    Dog ();
    void bark ();
}

…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…

Also, if possible, I’d like to invoke the constructor via a pointer as well:

NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();

Is this possible, and if so, what is the preferred way to do this?

Displaying files from Bundle into UITableView - iOS

I have got few audio files in my bundle, and I want to display them (names) in a UITableView. And when user taps on any cell, the audio file with that name should play.

e.g. enter image description here

I googled but all I got was to read files from Documents Directory.

How can I display my bundle files?

Please help, Thanks!

3D Touch Peek Swipe Like Mail

Using the 3D Touch Peek and Pop functionality, what is the most effective way of mimicking the capability depicted below (to swipe the "peeked" content side-to-side to perform an action)? The screenshot below comes from the iOS native Mail app.

Mail Swipe 3D Touch - Unread Mail Swipe 3D Touch - Trash

Is it possible to use a function similar to webViewFinishLoad without delegating?

I'm creating a framework to manipulate PDFs and at once point I load PDFs using the following code:

@IBOutlet var webView1: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    if let pdf = NSBundle.mainBundle().URLForResource("template", withExtension: "pdf", subdirectory: nil, localization: nil)  {
        let req = NSURLRequest(URL: pdf)
        webView1.delegate = self
        self.webView1.loadRequest(req)
    }

}

And then making use of the UIWebViewDelegate properties of my ViewController class to benefit from webViewFinishLoad to know when loading is finished.

Is there anyway of achieving this same end result without delegating my webView1 to main view?

CLPlacemark to string in iOS 9

I want to format CLPlacemark to string.

The well known way is to use ABCreateStringWithAddressDictionary but it was deprecated in iOS 9. Warning tells me to use CNPostalAddressFormatter instead.

However, CNPostalAddressFormatter can only format CNPostalAddress. There is no way to properly convert CLPlacemark to CNPostalAddress; only these 3 properties are shared by CLPlacemark and CNPostalAddress: country, ISOcountryCode, and postalCode.

So how should I format CLPlacemark to string now?

How to navigate to 'General/Accessibility/Hearing Aids" page directly from the App?

It is possible to navigate to the device settings directly from the App for iOS versions greater than 8.

This is the link I referred to: iOS UIAlertView button to go to Setting App

This allows only 2 levels of navigation: root and path. Example: General/Accessibility

Is there a way to access 3 levels of navigation to reach the hearing aids page of device settings? ie: General/Accessibility/Hearing Aids

Any help in objective-c or xamarin.ios will be appreciated.

Thank you

GCC and Clang different behaviors on constexpr constructor

For this struct:

struct Wrapper {
    int value;

    constexpr explicit Wrapper(int v) noexcept : value(v) {}
    Wrapper(const Wrapper& that) noexcept : value(that.value) {}
};

And this function:

constexpr Wrapper makeWrapper(int v)
{
    return Wrapper(v);
}

The following code fails to compile for Clang (Apple LLVM version 7.3.0), but compiles fine for GCC (4.9+), both with -Wall -Wextra -Werror -pedantic-errors:

constexpr auto x = makeWrapper(123);

Clang complains that "non-constexpr constructor 'Wrapper' cannot be used in a constant expression." Which compiler is right?

What Swift Version Should I be using?

I have a few questions related to Swift Versions.

I am currently writing an app in Swift 2.2 I am planning on releasing the app to the App Store before iOS 10 is released. Does that mean I need to stay using Swift 2.2 until iOS 10 is released?

Once iOS 10 is released, if I upgrade to Swift 3.0, will I still be able to build for iOS 8 and 9?

What is the purpose of Swift 2.3? Overall, I'm trying to understand what the optimal time to be upgrading versions of Swift is while maintaining compatibility with older iOS versions.

Error: Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'

In Xcode 8 I'm trying to make a subclass of UICollectionViewController and UICollectionViewLayout but I get the error:

Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'

but they have different parents classes. I'm trying to follow http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ tutorial for reorder custom size cells

class WordCollectionViewController: UICollectionViewController, UICollectionViewLayout {
    // ...
    override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
            var context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)

        return context
    }
}

Find object from json

I have one json look like this. { "countrycode" : [["11","","91","INDIA"," New Delhi"], ["112","Mahanagar Telephone Nigam Ltd (MTNL]","91","INDIA"," New Delhi"], ["113","Reliance Communications Ltd","91","INDIA"," New Delhi"], ["114","Bharti Airtel Ltd","91","INDIA"," New Delhi"], ["115","Sistema Shyam TeleServices Ltd (MTS]","91","INDIA"," New Delhi"], ["122","","91","INDIA"," Hapur Ghaziabad"], ["1222","Bharat Sanchar Nigam Ltd (BSNL]","91","INDIA"," Hapur Ghaziabad"], ["1223","Reliance Communications Ltd","91","INDIA"," Hapur Ghaziabad"]] } and i want to find perfect matched record with first row of json with my value. My value may be "1178920" or "1130123" or "1151593248" or "1223798". If i my value is will 1223798 than return me ["1223","Reliance Communications Ltd","91","INDIA"," Hapur Ghaziabad"]] I can't find way please help me.

How to pass OpenSSL socket to another process

I want to pass the SSL socket(along with its SSL session) to another process. Is this possible ?

In the non-SSL socket implementation, I use WSADuplicateSocket(Windows API) to get socket info and then send it to another process to create a duplicated socket.

How can I do this on SSL socket? Which information I has to pass to the second process to let them create the duplicated socket and continue the SSL session from the first process? Once the socket is passed to the second process, the first process will close its socket handle.

XIB required initializers - no storyboard

Click Here For Image

Hey, in the image I am simply creating a view controller that manages a blue view. When I create and initialize everything in the AppDelegate.swift, everything works regardless of whether or not I comment out the 2 top initializers (commented out in green in the photo).

I heard from other developers that when working with XIB and not story board, the 2 initializers are required. Can someone explain to me why it works even if I don't have them?

Is it necessary to implement imagePickerControllerDidCancel?

While working on a simple app where you open a Photo Library then choose an image I faced with a function imagePickerControllerDidCancel.

As I understand this function will be performed upon the click on "Cancel" button (while Camera or Photo Lib is open). And inside this func you need to perform dismissViewControllerAnimated.

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

But i tried not to implement it and the button Cancel was still working as it supposed to.

Is it necessary to use imagePickerControllerDidCancel or what is it for ?

error: too many initializers for 'const int [9]' [on hold]

I have a little problem .. I have a compilation error:

error: too many initializers for 'const int [9]' (for TEST_TEST)

My code: http://pastebin.com/RcA5L5bF

Initializer:

DWORD m_speed[MAIN][2][TEST_TEST][11];

I'm working on an open source program. It is true that I do not know how to use DWORD. I know that WORD is 4 bytes but I do not know what is the [11] side.

Thanks your advance :D

When does a new __LINE__ start?

I do not understand the output of the following program:

#include <iostream>

#define FOO std::cout << __LINE__ << ' ' 
                      << __LINE__ << 'n';
int main()
{
    FOO

    std::cout << __LINE__ << ' ' 
              << __LINE__ << 'n';
}

The first output is 7 and 7, indicating that the expansion of FOO is a single logical line, but the second output is 9 and 10, indicating two distinct logical lines. Why is there a difference?

Keyboard glitch in iOS development [on hold]

enter image description here

I don't know what is causing this. Whenever I set the keyboard in Dark mode, this glitch happens from time to time. This does not happen when I set the keyboard on Default or Light mode.

What can be causing this? How can I fix it?

There is no code on the keyboard, apart from the touchesBegan() method, which closes it whenever I tap outside of it.

dimanche 24 juillet 2016

Firebase + iOS + Swift - transient and boolean fields?

I'm porting my Firebase project from android to iOS using Swift 3 (yeah, young and hip). The first thing, that makes me wonder - data types for database. Integer, Float and Double replaced by NSNumber. Bool is missing 0_o. Really strange. But what confusing me the most - missing transient keyword. In android I used it like this

public transient boolean notify = false;

And so, do I can pass custom object w/o transient fields as value to Firebase? Or I must do it in stupid way - converting Object to NSDictionary? Thanks in advance

Difference in make_shared and normal shared_ptr in C++

std::shared_ptr<Object> p1 = std::make_shared<Object>("foo");
std::shared_ptr<Object> p2(new Object("foo"));

Many google and stackoverflow posts are there on this, but I am not able to understand why make_shared is more efficient than directly using shared_ptr.

Can someone explain me step by step sequence of objects created and operations done by both so that I will be able to understand how make_shared is efficient. I have given one example above for reference.

Detecting when back button is tapped in navigation bar

I need to resignFirstResponder() on a text field when the user taps the back button in the navigation bar of the navigation controller, otherwise I get some error. The back button works as it should (the previous view gets shown) but I don't know where to do resign first responder. It's too late if I do it in viewWillDisappear() (I tried), and prepareForSegue() doesn't get called, so I need to somehow do it as soon as the back button gets tapped or at least before viewWillDisappear(). How do I detect that event?

SDL- move object via keypress starts slow

I'm trying to move a texture via different key presses, eg

Move function:

if (key[SDL_SCANCODE_LEFT])
{
    mPosX = mPosX - 10;
}
//.....

This is my main loop:

newTexture.move(currentKeyStates);
SDL_RenderClear(gRenderer);
newTexture.render();
SDL_RenderPresent(gRenderer);

So, everything works fine, except when I hold down a button, for example "Left", the texture moves 10px, but then it stops for a few miliseconds. If I continue holding the button, everythings works smoothly. But as soon as I change the direction I got the same problem again.

Connect to a certain Wifi network?

I know it was something that Apple did not allowed, but i could see that some things had changed with iOS9 .

So , for example you can know your SSID name with CaptiveNetwork , and even the password.

Sometimes you have to connect to a certain hardware using wifi so instead of sending a user to settings, we would like to do that in code .

  1. is it possible ?
  2. is that requires Apple permission? if yes, is it something hard to get ? depends on ?

thanks .

How remove a "use of undeclared identifier: FIRDynamicLink"?

We are following the dynamic instructions for Firebase here, which lists just one import needed "@import Firebase" - yet when we get to their line

FIRDynamicLink *dynamicLink = [[FIRDynamicLinks dynamicLinks] dynamicLinkFromCustomSchemeURL:url];

if (dynamicLink) { ...

...XCode gives an undeclared identifier for FIRDynamicLink. Unlike some of the other modules like "import FirebaseAnalytics" - there doesn't seem to be another library dedicated to Dynamic Links.

The pod content is: pod "Firebase/DynamicLinks"

What is the trick to get this to compile?

Iphone accelerometer sampling frequency

Some applications are available for measuring frequencies of alternating currents up to 200 Hz using magnetometers and designed for Iphones.

I collected data from Iphone 5s magnetometers and the minimum average value of the acquisition period I recorded was about 0,02 sec, in other words the average sampling frequency was 50 Hz. In my opinion and in this case, it's possible to measure only upto 25 Hz. How is possible to measure alternating current up to 200 Hz ? Did I write something wrong? Is there a trick to decrease the acqusition period? Thank's a lot for you support. Best regards.

Jeff 974

Is there any way to run this faster?

Please help me to get this faster because right now it makes a decent CPU usage.

bool CMemory::IsProcessRunning(DWORD dwPID, char* szProcessName = NULL)
{
    HANDLE hPID = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof(pEntry);

    if (Process32First(hPID, &pEntry))
    {
        do
        {
            if (pEntry.th32ProcessID == dwPID && (!strcmp(pEntry.szExeFile, szProcessName) || szProcessName == NULL))
            {
                CloseHandle(hPID);
                return TRUE;
            }
        } while (Process32Next(hPID, &pEntry));
    }

    CloseHandle(hPID);
    return FALSE;
}

Any answer will be appreciated. Thanks.

By the way, I really like to use built-in WinAPI. Don't suggest any libraries please.

Symbolicating iPhone App Crash Reports

I'm looking to try and symbolicate my iPhone app's crash reports. I retrieved the crash reports from iTunes Connect. I have the application binary that I submitted to the App Store and I have the dSYM file that was generated as part of the build. I have all of these files together inside a single directory that is indexed by spotlight. What now? I have tried invoking: symbolicatecrash crashreport.crash myApp.app.dSYM and it just outputs the same text that is in the crash report to start with, not symbolicated. Am I doing something wrong? Any help would be greatly appreciated, thanks.

UI development for Kinect and Leap Motion

I want to extend an existing OpenGL-based data visualization application programmed in C++ by an user interface specifically designed for Kinect and Leap Motion interaction. Which UI toolkits/frameworks are recommended for this purpose? Optimally they should already provide suitable UI elements/widgets. The existing GUI for mouse interaction is realized with the library AntTweakBar which is not appropriate for NUI building.

As I see there are officially Unity packages for Kinect and Leap Motion. Is it prossible to use Unity just for developing an UI for an existing application?

Retrieving bool array from NSUserdefaults in swift

I have defined an array like this in my iOS app

var array=[Bool]() and assigning some bool values to this.After that I am storing this array in my user defaults in this way.
userDefaults.setObject(dm.array, forKey: "array")

Now I want to retrievw this array. So I did like this

dm.array=userDefaults.arrayForKey("array") as! Array

But here im getting an error

Down cast from[Anyobject]? to array<anyobject> only unwraps optional; did you mean to use '!'?

Including huge string in our c++ programs?

I am trying to include huge string in my c++ programs, Its size is 20598617 characters , I am using #define to achieve it. I have a header file which contains this statement

#define "<huge string containing 20598617 characterd>"

When I try to compile the program I get error as fatal error C1060: compiler is out of heap space

I tried following command line options with no success

/Zm200
/Zm1000
/Zm2000

How can I make successful compilation of this program?

Platform: Windows 7