Gesture

var uilongPRec = UILongPressGestureRecognizer(target: self, action: "lpAction:")//funcName: : for adding var to fund!
        uilongPRec.minimumPressDuration = 1.5 //time for long press
        mapView.addGestureRecognizer(uilongPRec) // add long press to mapview

func lpAction(gestureRecognizer: UIGestureRecognizer){
       
        var touchPoint = gestureRecognizer.locationInView(self.mapView)

        var newCoord:CLLocationCoordinate2D = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
       
        var annotation:MKPointAnnotation = MKPointAnnotation()
        annotation.coordinate = newCoord
        annotation.title = "New Ann"
        annotation.subtitle = "One day I will come by"
       
        mapView.addAnnotation(annotation)
       
       
       
    }

Tags: 

Timer

timer = NSTimer.scheduledTimerWithTimeInterval(
            0.1,
            target: self,
            selector: "updateTime",
            userInfo: nil,
            repeats: true
        )

Tags: 

Animation

override func viewDidAppear(animated: Bool) {
       
        UIView.animateWithDuration(1.0, animations: { () -> Void in
           
            self.image.center = CGPointMake(self.image.center.x + 400, self.image.center.y)
            self.image.alpha = 1.0
            self.image.frame = CGRectMake(0 , 0, 320, 320)
        })
    }

Tags: 

Extensions Convenience init!

extension UIColor{
   
    convenience init(red: Int, green: Int, blue: Int)
    {
        let newRed   = CGFloat(Double(red) / 255.0)
        let newGreen = CGFloat(Double(green) / 255.0)
        let newBlue  = CGFloat(Double(blue) / 255.0)
       
        self.init(red: newRed, green: newGreen, blue: newBlue, alpha: CGFloat(1.0))
    }
}

let swiftOrange = UIColor(red: 255, green: 149, blue: 0)
let swColor = UIColor(red:34, green:223, blue:123)

Tags: 

json call rest

import urllib, json
>>> url = "http://maps.googleapis.com/maps/api/geocode/json?address=googleplex&sens..."
>>> url = "http://myexternalip.com/json"
>>> response = urllib.urlopen(url);
>>> data = json.loads(response.read())
>>> print data
{u'ip': u'80.57.121.251'}

Tags: 

string replace

var str:String = "AS3 rocks!";
var search:String = "AS3";
var replace:String = "Actionscript 3";

function strReplace(str:String, search:String, replace:String):String {
return str.split(search).join(replace);
}

trace(strReplace(str, search, replace)); //Outputs Actionscript 3 rocks!

check if app is running in 64 bit

There are two ways to determine this: at runtime (i.e. in your running code), and at compile time (i.e. before the code is compiled). Let’s take a look at both options.

Runtime Check
// testing for 64bit at runtime

if (sizeof(void*) == 4) {
self.textLabel.text = @"You're running in 32 bit";

} else if (sizeof(void*) == 8) {
self.textLabel.text = @"You're running in 64 bit";
}
Determines the size of a pointer.

Compile Time Check
#if __LP64__
// you're running 64bit
#else
// you're running 32bit
#endif
Asks the compiler which architecture it compiles for.

Tags: 

Abstract Factory

protocol Decimal {
    func stringValue() -> String
}

protocol NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal
}

// Number implementations.

struct NextStepNumber : Decimal {
    private var nextStepNumber : NSNumber

    func stringValue() -> String { return nextStepNumber.stringValue }
}

struct SwiftNumber : Decimal {
    private var swiftInt : Int

    func stringValue() -> String { return "\(swiftInt)" }
}

// Factories.

class NextStepNumberFactory : NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal {
        return NextStepNumber(nextStepNumber:NSNumber(longLong:(string as NSString).longLongValue))
    }
}

class SwiftNumberFactory : NumberFactoryProtocol {
    func numberFromString(string : String) -> Decimal {
        return SwiftNumber(swiftInt:(string as NSString).integerValue)
    }
}

// Abstract factory.

enum NumberType {
    case NextStep, Swift
}

class NumberAbstractFactory {
    class func numberFactoryType(type : NumberType) -> NumberFactoryProtocol {

        switch type {
            case .NextStep:
                    return NextStepNumberFactory()
            case .Swift:
                    return SwiftNumberFactory()
        }
    }
}

let factoryOne = NumberAbstractFactory.numberFactoryType(.NextStep)
let numberOne = factoryOne.numberFromString("1")
numberOne.stringValue()

let factoryTwo = NumberAbstractFactory.numberFactoryType(.Swift)
let numberTwo = factoryTwo.numberFromString("2")
numberTwo.stringValue()

Tags: 

Builder

protocol ThreeDimensions {
    var x: Double? {get}
    var y: Double? {get}
    var z: Double? {get}
}

class Point : ThreeDimensions {
    var x: Double?
    var y: Double?
    var z: Double?

    typealias PointBuilderClosure = (Point) -> ()

    init(buildClosure: PointBuilderClosure) {
        buildClosure(self)
    }
}

let fancyPoint = Point { point in
point.x = 0.1
point.y = 0.2
point.z = 0.3
}

fancyPoint.x
fancyPoint.y
fancyPoint.z
Shorter but oh-so-ugly alternative:

let uglierPoint = Point {
$0.x = 0.1
$0.y = 0.2
$0.z = 0.3
}

Tags: 

SingletonClass

class SingletonClass {
    class var shared : SingletonClass {

        struct Static {
            static let instance : SingletonClass = SingletonClass()
        }

        return Static.instance
    }
}

use:
let instance = SingletonClass.shared

Tags: 

uitextfield

var txtField: UITextField = UITextField()
    txtField.frame = CGRectMake(50, 70, 200, 30)
    txtField.backgroundColor = UIColor.grayColor()
    self.view.addSubview(txtField)

Tags: 

uilabel

   
var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label..numberOfLines = 0
label.text = "test label"
self.view.addSubview(label)

Multiline

label.lineBreakMode = .ByWordWrapping
label.numberOfLines = 0

Tags: 

uibutton

let button = UIButton(type: .Custom)
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)

button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)

Tags: 

Starling

var t:Tween = new Tween(b, 3, Transitions.LINEAR);
t.moveTo((0 - b.width - 2), b.y);
Starling.juggler.add(t);
/*
t.onStart = bOnStart();
t.onUpdate = bOnStart();
t.onComplete = bOnStart();

*/

tweenlite

//import the GreenSock classes
import com.greensock.*;
import com.greensock.easing.*;

//tween the MovieClip named "mc" to an alpha of 0.5 over the course of 3 seconds
TweenLite.to(mc, 3, {alpha:0.5});
//scale myButton to 150% (scaleX/scaleY of 1.5) using the Elastic.easeOut ease for 2 seconds
TweenLite.to(myButton, 2, {scaleX:1.5, scaleY:1.5, ease:Elastic.easeOut});
//tween mc3 in FROM 100 pixels above wherever it is now, and an alpha of 0. (notice the vars object defines the starting values instead of the ending values)
TweenLite.from(mc3, 1, {y:"-100", alpha:0});
//after a delay of 3 seconds, tween mc for 5 seconds, sliding it across the screen by changing its "x" property to 300, using the Back.easeOut ease to make it shoot past it and come back, and then call the onFinishTween() function, passing two parameters: 5 and mc
TweenLite.to(mc, 5, {delay:3, x:300, ease:Back.easeOut, onComplete:onFinishTween, onCompleteParams:[5, mc]});
function onFinishTween(param1:Number, param2:MovieClip):void {
trace("The tween has finished! param1 = "   param1   ", and param2 = "   param2);
}
//call myFunction() after 2 seconds, passing 1 parameter: "myParam"
TweenLite.delayedCall(2, myFunction, ["myParam"]);
//use the object-oriented syntax to create a TweenLite instance and store it so we can reverse, restart, or pause it later.
var myTween:TweenLite = new TweenLite(mc2, 3, {y:200, alpha:0.5, onComplete:myFunction});
//some time later (maybe in by a ROLL_OUT event handler for a button), reverse the tween, causing it to go backwards to its beginning from wherever it is now.
myTween.reverse();
//pause the tween
myTween.pause();
//restart the tween
myTween.restart();
//make the tween jump to exactly its 2-second point
myTween.currentTime = 2;

wit scherm na loading

na loader

[Embed(source="../../../../../../bin/assets/menuscreen/bg.png")]
                                public var BM:Class;
                                public var backgroundBMP:Bitmap;

                                public function MenuScreen()
                                {
                                                this.background = null;//forget this for the first screen// 'assets/menuscreen/bg.png';
                                                backgroundBMP = new BM();
                                                backgroundBMP.smoothing = true;
                                                addChild(backgroundBMP);
}

prevent android device from dimming screen

in main.as
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;

in application.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Log Line Numbers

trace(">",new Error().getStackTrace().match(/(?<=:)[0-9]*(?=])/g)[0]);

remove from parent

if (obj.parent)
{
obj.parent.removeChild(obj);
trace('remove chld');
}

saveSharedObject

var saveDataObject:SharedObject;
saveDataObject = SharedObject.getLocal("test");
of
in 1en
saveDataObject:SharedObject = SharedObject.getLocal("test");

saveDataObject.data.savedScore = currentScore;

When you want the SharedObject to actually, immediately write its save data to its file on the player’s local hard drive you flush it:

saveDataObject.flush();

This is a very processor intensive action to call, so use it sparingly (never include it an a loop function).

To load “currentScore” from the “savedScore”, we would write:

currentScore = saveDataObject.data.savedScore;

add folder

if (!Directory.Exists(path))
{
  DirectoryInfo di = Directory.CreateDirectory(path);
}

Tags: 

debug message

// using System.Diagnostics;
Debug.WriteLine("Hello World");

Tags: 

remove a specific object

this.collectionOtherObjects.splice(this.collectionOtherObjects.indexOf(bombC), 1);

add webserver

Installing The Web Server

sudo apt-get install apache2 php5 libapache2-mod-php5

restart:
sudo service apache2 restart
OR
sudo /etc/init.d/apache2 restart

Enter the I.P. address of your Raspberry Pi into your web browser. You should see a simple page that says "It Works!"

Install MySQL

sudo apt-get install mysql-server mysql-client php5-mysql

Install FTP
Take ownership of the web root:
sudo chown -R pi /var/www

install vsftpd:
sudo apt-get install vsftpd

sudo nano /etc/vsftpd.conf

Make the following changes:

    anonymous_enable=YES to anonymous_enable=NO
    Uncomment local_enable=YES and write_enable=YES by deleting the # symbol in front of each line
    then go to the bottom of the file and add force_dot_files=YES.

sudo service vsftpd restart

ln -s /var/www/ ~/www

General

Update

sudo apt update -y && apt upgrade -y

Reboot

sudo shutdown -h now (or sudo reboot)

Locale

edit ~/.bashrc add LANG="en_US.UTF-8"

temperature sensor

sudo modprobe w1-gpio sudo modprobe w1-therm ls /sys/bus/w1/devices

temp sensor not visible in /sys/bus/w1/devices

sudo nano /boot/config.txt

add :

dtoverlay=w1-gpio

masking cutting out shapes

1) Inflexible hole cutting:

this.graphics.beginFill(0x666666);
this.graphics.drawRect(0,0,256, 256);
this.graphics.drawCircle(128,128,32);
this.graphics.endFill();
this will create a rectangle of 256 by 256 with a 64px hole in it.

2) Flexible hole cutting:

Obviously this will not work when you're not using the graphics class. In That case I would go with BlendMode.ERASE.

var spr:Sprite = new Sprite();
var msk:Sprite = new Sprite();

addChild(spr);
spr.addChild(msk)

spr.graphics.beginFill(0x666666);
spr.graphics.drawRect(0,0,256, 256);
spr.graphics.endFill();

msk.graphics.beginFill(0x000000);
msk.graphics.drawEllipse(0,0,64,64);
msk.graphics.endFill();
msk.x = 128;
msk.y = 128;

spr.blendMode = BlendMode.LAYER;
msk.blendMode = BlendMode.ERASE;

Random min max && random color

Random between min max:
var x:* = min + (max - min) * Math.random();

Random Color:
var randomColor:Number = Math.random()*0xFFFFFF;

min max array

var myArray:Array = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = Math.max.apply(null, myArray);
var minValue:Number = Math.min.apply(null, myArray);

switch

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}

Tags: 

uiiamge background

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"statistics"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *imageView = [[UIImageView alloc] initWithImage: image];

[self.view addSubview: imageView];

[self.view sendSubviewToBack: imageView];

Tags: 

Pages

Subscribe to hjsnips RSS