How to display a Date with TextField Click with Swift

Displaying Date with TextField Click with Swift

First you must have a textfield connected to storyboard.


@IBOutlet weak var txtField_helloDatePicker: UITextField!

Next you should have a constant of UIDatePicker type.

let datePicker = UIDatePicker()

Then inside the viewDidLoad function, you should set the date picker mode to date

datePicker.datePickerMode = UIDatePickerMode.Date

Then to show the date picker on tapping the textfield, you should set the input view of that textfield to the date picker
        
txtField_helloDatePicker.inputView = datePicker

Then to manage the changes in the selection
        

datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

Then to handle the action  of the date picker, you should have 

func datePickerChanged(datePicker:UIDatePicker) {
        println("time picker changed for ceremony")
        
        var dateFormatter = NSDateFormatter()
        
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        
        var strDate = dateFormatter.stringFromDate(datePicker.date)
        
        txtField_helloDatePicker.text = strDate
 }

Summary of Code:

datePicker.datePickerMode = UIDatePickerMode.Date
        
txtField_helloDatePicker.inputView = datePicker
        
datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

func datePickerChanged(datePicker:UIDatePicker) {
        println("time picker changed for ceremony")
        
        var dateFormatter = NSDateFormatter()
        
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        
        var strDate = dateFormatter.stringFromDate(datePicker.date)
        
        txtField_helloDatePicker.text = strDate
 }

Common Swift collection casting or type conversion

Collection of Common Swift Casting  or Type Conversion

String to Double
var a  = "1.5"
var b  = (a as NSString).doubleValue

Double to String
var a : Double = 1.5
var b  = String(format:"%f", a)

Double to Int
var a : Double = 1.5
var b  = Double(a)

String to Float
var a  = "1.5"
var b  = (a as NSString).floatValue

String to Float
var a  = "1.5"
var b  = (a as NSString).intValue


How to Display an Alert View with Swift

Display an Alert View with Swift

First we'll create a constant of UIAlertController. Since we'll be using an alert, the UIAlertControllerStyle is set to default. It can have other values such as ActionSheet, Alert, and RawValue.

 let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

Next, we'll be adding a button inside the newly created alertcontroller. We'll set the handler to nil since we don't need any action yet. But you may call a function when a button is click by setting the handler to some function. 
Note: The handler function must have a parameter of UIAlertAction type (e.g. func buttonHandler(alertView: UIAlertAction){})

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil))
            
And lastly in order to show the alert view, you must present it by the calling the presentViewController method.


presentViewController(alertPrompt, animated: true, completion: nil)

Summary of Code:

Inside an action function, place the following line of codes.

let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil))
            

presentViewController(alertPrompt, animated: true, completion: nil)

or to handle a button click in the alert view, we can have

let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:"btn_clicked"))
            

presentViewController(alertPrompt, animated: true, completion: nil)

Then we can declare the button handle:

func btn_clicked(alertView: UIAlertAction!){
        presentViewController(imagePicker, animated: true, completion: nil)
 println("Ok")
 }

Technical analysis of Qualys' GHOST

This morning, a leaked note from Qualys' external PR agency made us aware of GHOST. In this blog entry, our crack team of analysts examines the technical details of GHOST and makes a series of recommendations to better protect your enterprise from mishaps of this sort.





Figure 1: The logo of GHOST, courtesy of Qualys PR.



Internally, GHOST appears to be implemented as a lossy representation of a two-dimensional raster image, combining YCbCr chroma subsampling and DCT quantization techniques to achieve high compression rates; among security professionals, this technique is known as JPEG/JFIF. This compressed datastream maps to an underlying array of 8-bpp RGB pixels, arranged sequentially into a rectangular shape that is 300 pixels wide and 320 pixels high. The image is not accompanied by an embedded color profile; we must note that this poses a considerable risk that on some devices, the picture may not be rendered faithfully and that crucial information may be lost.



In addition to the compressed image data, the file also contains APP12, EXIF, and XMP sections totaling 818 bytes. This metadata tells us that the image has been created with Photoshop CC on Macintosh. Our security personnel notes that Photoshop CC is an obsolete version of the application, superseded last year by Photoshop CC 2014. In line with industry best practices and OWASP guidelines, we recommend all users to urgently upgrade their copy of Photoshop to avoid exposure to potential security risks.



The image file modification date returned by the HTTP server at community.qualys.com is Thu, 02 Oct 2014 02:40:27 GMT (Last-Modified, link). The roughly 90-day delay between the creation of the image and the release of the advisory probably corresponds to the industry-standard period needed to test the materials with appropriate focus groups.



Removal of the metadata allows the JPEG image to be shrunk from 22,049 to 21,192 bytes (-4%) without any loss of image quality; enterprises wishing to conserve vulnerability-disclosure-related bandwidth may want to consider running jhead -purejpg to accomplish this goal.



Of course, all this mundane technical detail about JPEG images distracts us from the broader issue highlighted by the GHOST report. We're talking here about the fact that the JPEG compression is not particularly suitable for non-photographic content such as logos, especially when the graphics need to be reproduced with high fidelity or repeatedly incorporated into other work. To illustrate the ringing artifacts introduced by the lossy compression algorithm used by the JPEG file format, our investigative team prepared this enhanced visualization:





Figure 2: A critical flaw in GHOST: ringing artifacts.



Artifacts aside, our research has conclusively showed that the JPEG formats offers an inferior compression rate compared to some of the alternatives. In particular, when converted to a 12-color PNG and processed with pngcrush, the same image can be shrunk to 4,229 bytes (-80%):





Figure 3: Optimized GHOST after conversion to PNG.



PS. Tavis also points out that ">_" is not a standard unix shell prompt. We believe that such design errors can be automatically prevented with commercially-available static logo analysis tools.



PPS. On a more serious note, check out this message to get a sense of the risk your server may be at. Either way, it's smart to upgrade.

How to get the client's ip address in jax rs and ws

In this tutorial I'll not teach how to create jax-rs nor jax-ws web service but rather will show how we can get the client's or the caller's ip address who invoke the service.

In jax-rs:
//inject
@Context
private HttpServletRequest httpServletRequest;

public void serviceMethod() {
//get the ip
log.debug("IP=" + httpServletRequest.getRemoteAddr());
}
In jax-ws, we inject a different resource but it's almost the same.

@Resource
private WebServiceContext wsContext;

public void serviceMethod() {
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);

log.debug("IP=" + req.getRemoteAddr());
}

If you need help building jax-rs service here's how I'm doing things: http://czetsuya-tech.blogspot.com/2014/11/rest-testing-with-arquillian-in-jboss.html.

On the Instability of Unilateral Fixed Exchange Rate Regimes

Was there an easy way to bet on a CHF/EUR appreciation? Because if there was, we must all be kicking ourselves for not exploiting that trade!

The difference between winning and losing in the FX market is usually just a matter of luck. To a first approximation, floating exchange rates seem to follow a random walk (see here). But the trade I'm describing here is one I think we should have expected to pay off for reasons beyond pure luck. That is, there is a pretty sensible theory of currency crises that might have guided our investment strategy in the present context. In particular, I'm thinking of Paul Krugman's (1979) model, which he describes here.

The basic idea is as follows. Suppose that a central bank wants to peg its currency relative to some other currency. Suppose that it does so unilaterally. The success of the peg will depend critically on its perceived credibility. This credibility may depend on, among other things, the amount of foreign reserves held by our intrepid central bank. To defend the peg, the central bank must stand ready to buy its own currency on the FX market, which it does so by selling off its stock of foreign reserves.

A unilateral peg of this sort is just ripe for speculation. The two most likely outcome in this case are (1) the peg holds or (2) the peg fails (the domestic currency depreciates). The trade in this case is to go short on the pegging bank's currency and long in the foreign currency. A speculator either breaks even if (1) or wins if (2). It's a can't lose proposition (but please don't try this at home kids). Rational speculators, recognizing the opportunity, start shorting the pegged currency. If they do so en masse, our little central bank will soon run out of reserves and be forced to abandon the peg--a self-fulfilling prophecy.

I didn't spot this in the case of the SNB because, well, Switzerland is not a banana republic--the Swiss Franc is considered a safe-haven security. And the SNB was pegging because it was worried about currency appreciation--not the usual concerns about excess volatility or depreciation. Of course, there was never any danger of the SNB running out of reserves--they can print all the Francs they want! So what was the danger?

Central bankers are by nature a highly conservative bunch. They become uncomfortable with things that are unfamiliar. Like balance sheets the size of the moon, for example. With an ECB QE policy on the horizon, there was the prospect of EUR for CHF conversions proceeding at an even more rapid rate--leading to a very, very large SNB balance sheet. My claim is this: we should have guessed that the SNB would have at some point in this process lost its nerve and abandoned the peg, allowing their currency to appreciate (And if it didn't lose its nerve, the peg would have been maintained, so we would not have lost on the other likely outcome of my proposed bet). Rational speculators anticipating this should have ... oh well, forget it. (Let's try it next time and see what happens?).

As for the SNB abandoning its peg, especially the way it did, well, it just seems crazy to me. It would have made sense if one thought that EUR inflation was likely to take off. But all the worry at present is directed toward the prospect of EUR deflation. Yes, that's right, the SNB is stocking up on a currency whose purchasing power is projected to increase. And as for being concerned about EUR inflation because of QE, it seems unlikely to me that the ECB wouldn't be willing and able to defend its low inflation target.

In short, I think the SNB could have let it's balance sheet grow much larger without any significant economic repercussions. Instead, by removing the peg as they did, they suffered a huge and needless capital loss on their EUR assets. Strange move. But how can we argue against the past success of Swiss bankers?

On the plus side, I suppose we can no longer claim the Swiss to be boring