Icon create

after: brew install imagemagick
create iconcreate.sh

#!/bin/bash
for size in {76,40,29,60,57,50,72,167}; do for scale in {1,2,3}; do
    if [[ $scale == 1 ]]; then
        filename="icon_${size}.png"
    else
        filename="icon_${size}@${scale}x.png"
    fi
    gm convert "icon.png" -resize "$(( $scale * $size ))x$(( $scale * $size ))" $
done; done

or
sh iconcreate.sh icon.png

convert $1 -resize 16x16      Icon-16.png
convert $1 -resize 32x32      Icon-16@2x.png
convert $1 -resize 29x29      Icon-Small-29.png          # Settings on iPad and iPhone, and Spotlight on iPhone
convert $1 -resize 58x58      Icon-Small-29@2x.png
convert $1 -resize 87x87      Icon-Small-29@3x.png
convert $1 -resize 32x32      Icon-32.png
convert $1 -resize 64x64      Icon-32@2x.png
convert $1 -resize 40x40      Icon-Small-40.png       # Spotlight
convert $1 -resize 80x80      Icon-Small-40@2x.png       # Spotlight
convert $1 -resize 120x120    Icon-Small-40@3x.png       # Spotlight
convert $1 -resize 50x50      Icon-Small-50.png       # Spotlight on iPad 1/2
convert $1 -resize 57x57      Icon-57.png                # Home screen on non-Retina iPhone/iPod
convert $1 -resize 114x114    Icon-57@2x.png             # Home screen for Retina display iPhone/iPod
convert $1 -resize 120x120    Icon-60@2x.png          # Home screen on iPhone/iPod Touch with retina display
convert $1 -resize 180x180    Icon-60@3x.png          # Home screen on iPhone 6 Plus
convert $1 -resize 72x72      Icon-72.png             # App Store and Home screen on iPad
convert $1 -resize 144x144    Icon-72@2x.png          # Home screen for "The New iPad"
convert $1 -resize 76x76      Icon-76.png             # Home screen on iPad
convert $1 -resize 152x152    Icon-76@2x.png          # Home screen on iPad with retina display
convert $1 -resize 228x228    Icon-76@3x.png
convert $1 -resize 83.5x83.5  Icon-83,5.png
convert $1 -resize 167x167    Icon-83,5@2x.png
convert $1 -resize 128x128    Icon-128.png
convert $1 -resize 256x256    Icon-128@2x.png
convert $1 -resize 256x256    Icon-256.png
convert $1 -resize 512x512    Icon-256@2x.png
convert $1 -resize 512x512    Icon-512.png
convert $1 -resize 1024x1024  iTunesArtwork@2x.png   # App list in iTunes for devices with retina display
convert $1 -resize 1024x1024  Icon-512@2x.png
convert $1 -resize 512x512    iTunesArtwork.png       # Ad Hoc iTunes

rename extension

for file in *.html
do
mv "$file" "${file%.html}.txt"
done

Tags: 

print to file

history > history_for_print.txt

Tags: 

kali

service tor status
service tor start
service tor restart

proxychains firefox www.duckduckgo.com
dns leak test
www.dnsleaktest.com

vpn

cat /etc/resolv.conf
# Generated by NetworkManager
nameserver 192.168.1.1

nano /etc/dhcp/dhclient.conf
service network-manager restart

firfox
about:config

macchanger -s wlan0 //show

nslookup

nmap scanme.nmap.org -vv //verbose
nmap -oG - 192.168.1.1-255 -p 3000 -vv > /home/scan.txt

curl ipinfo.io/74.207.244.221
location info

NSUserDefaults [Int:Int]

load

if let data = NSUserDefaults.standardUserDefaults().objectForKey( "averagesPerLevel") as? NSData
{
    let object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [Int: Int]
    print("average cached : \(object))")
}

save

NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(self.globalAverages!.averagesPerLevel), forKey:"averagesPerLevel")

Tags: 

Xcode snippet

Code Snippet Library within Xcode

variable to edit is within <# var #>

// FIXME: <# Subject #>

to make todo / fix into warning

add run script in Build Phases
shell: /bin/sh
(tick 'Show environment variables in build log')

TAGS="TODO:|FIXME:"
find "${SRCROOT}" \( -name "*.h" -or -name "*.m" -or -name "*.swift" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($TAGS).*\$" | perl -p -e "s/($TAGS)/ warning: \$1/"

Tags: 

Test Webserver from raspberry pi

import smtplib
import httplib
import datetime

GMAIL_USER = 'email@gmail.com'
GMAIL_PASS = 'password'
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

def send_email(recipient, subject, text):
    smtpserver = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(GMAIL_USER, GMAIL_PASS)
    header = 'To:' + recipient + '\n' + 'From: ' + GMAIL_USER
    header = header + '\n' + 'Subject:' + subject + '\n'
    msg = header + '\n' + text + ' \n\n'
    smtpserver.sendmail(GMAIL_USER, recipient, msg)
    smtpserver.close()

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None  

if  get_status_code("site.com") != 200:
    f = open("/home/pi/servertest/logfile.txt", "a")
    f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' status != 200 ERROR' + '\n' )
    f.close()
    print "something wrong"
    send_email('email@gmail.com', 'server not at 200', 'server not at 200')
   
else:
    f = open("/home/pi/servertest/logfile.txt", "a")
    f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' status == 200' + '\n' )
    f.close()
    print "status == 200"

add cron to crontab
crontab -e

test every 10 minutes

*/10     *      *     *    *   python  /home/pi/servertest/servertest.py

to start cron

sudo service cron start

nscodernight

let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
XCPlaygroundPage.currentPage.liveView = containerView
containerView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

var view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 300, height: 200)
view.backgroundColor = #colorLiteral(red: 0.9346159697, green: 0.6284804344, blue: 0.1077284366, alpha: 1)
containerView.addSubview(view)

let timing = UICubicTimingParameters(animationCurve: .easeIn)

let animator = UIViewPropertyAnimator(duration: 5.0, timingParameters: timing)
animator.addAnimations
  {
    view.center = containerView.center
}



let scene = UIViewPropertyAnimator(duration: 2.0, timingParameters: timing)
scene.addAnimations {
  containerView.backgroundColor = #colorLiteral(red: 0.2818343937, green: 0.5693024397, blue: 0.1281824261, alpha: 1)
}
scene.addCompletion { (_) in
  view.backgroundColor = #colorLiteral(red: 0.1991284192, green: 0.6028449535, blue: 0.9592232704, alpha: 1)
}
animator.addCompletion
  { _ in
      scene.startAnimation()
   
}
animator.startAnimation()

Tags: 

TVOS light dark

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
// Is userInterfaceStyle available?
guard(traitCollection.response(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
  else{ return}
guard(traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle)
  else{ return}
}

class AppearanceViewController: UIViewController
{
var style: UIUserInterfaceStyle = /light
override init(nibName nibNameOrNil: String?, bundle nibNameOrNil: Bundle?){...}

required init?(coder aDecoder: NSCoder) {...}

var viewController: UIViewController
{
  get {return self}
  set {
  //override trait collection
let traitCollection = UITraitCollection(userInterfaceStyle: style)
self.setOverrideTraitCollection(traitCollection, forChildViewController: newValue)

//add child view controller
self.addChildViewController(newValue)
newValue.view.frame = view.bounds
self.view.addSubview(newValue.view)
newValue.didMove(toParentViewController: self)

  }
}
}

to tvos10

info.plist
user Interface style => automatic

storyboard

Interface Builder Document
v use Trait Variations

App delegate

.. didFinishLaunchingWithOptions ..
let light = UITraitCollection(userInterfaceStyle:.light)
let backgroundColor = UIColor(white:1 alpha:  0.5)
UICOllectionViewCell.forTraitCollection(light).backgroundColor = backgroundColor

let dark = UITraitCollection(userInterfaceStyle:.dark)
let darkbackgroundColor = UIColor(white:0.2 alpha:  0.8)
UICOllectionViewCell.forTraitCollection(dark).backgroundColor = darkbackgroundColor

in VC

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
// Is userInterfaceStyle available?
guard( traitCollection.responds(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
  else{ return}
guard(traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle)
  else{ return}
}

if traitCollection.userInterfaceStyle == .dark
{
..do this
}
else
{
..do that
}

Tags: 

Random In

func randomNumberIn(range:Range<Int>)->Int
{
    let result = 0
    let random = range.minElement()!  + Int(arc4random_uniform(UInt32((range.maxElement()!+1) - range.minElement()!)))
    if random != 0
    {
        return random
    }
    return result
}

bv:
let r = randomNumberIn(0...255)
let g = randomNumberIn(0...255)
let b = randomNumberIn(0...255)
backgroundColor = UIColor(red: r, green: g, blue: b)

gameplaykit

let source = GKPerlinNoiseSource(
frequency:2,
octave:3,
persistance: 0.5,
lacunarity: 2
)
let noise = GKNoise(source)

Tags: 

Looping

Looping n times

for var i = 0; i < 10; i++ {
    print(i)
}

// use this:
for i in 0..<10 {
    print(i)
}

Looping n times in reverse

for var i = 10; i > 0; i-- {
    print(i)
}

// use this
for i in (1...10).reverse() {
    print(i)
}

Looping with Stride

for var i = 0; i < 10; i += 2 {
    print(i)
}

// use this
for i in 0.stride(to: 10, by: 2) {
    print(i)
}

Looping through Array Values

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print(someNumbers[i])
}

// use this
for number in someNumbers {
    print(number)
}

// or this
someNumbers.forEach { number in
    print(number)
}

Reverse Looping through Array Values

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/* 100, 83, 8, 6, 45, 3, 2 */

// instead of this
for var i = someNumbers.count - 1; i >= 0; i-- {
    print(someNumbers[i])
}

// use this
for number in someNumbers.reverse() {
    print(number)
}

Looping Through an Array with Index

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/*
1: 2
2: 3
3: 45
4: 6
5: 8
6: 83
7: 100
*/

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print("\(i + 1): \(someNumbers[i])")
}

// use this
for (index, number) in someNumbers.enumerate() {
    print("\(index + 1): \(number)")
}

// or this
someNumbers.enumerate().forEach { (index, number) in
    print("\(index + 1): \(number)")
}

Looping Through Array Indices

let someNumbers = [2, 3, 45, 6, 8, 83, 100]

/* 0, 1, 2, 3, 4, 5, 6 */

// instead of this
for var i = 0; i < someNumbers.count; i++ {
    print(i)
}

// use this
for index in someNumbers.indices {
    print(index)
}

from: Natasha the Robot

Tags: 

Site Maintenance

<!doctype html>
<title>Site Maintenance</title>
<style>
  body { text-align: center; padding: 150px; }
  h1 { font-size: 50px; }
  body { font: 20px Helvetica, sans-serif; color: #333; }
  article { display: block; text-align: left; width: 650px; margin: 0 auto; }
  a { color: #dc8100; text-decoration: none; }
  a:hover { color: #333; text-decoration: none; }
</style>

<article>
    <h1>We&rsquo;ll be back soon!</h1>
    <div>
        <p>Sorry for the inconvenience but we&rsquo;re performing some maintenance at the moment. If you need to you can always <a href="mailto:">contact us</a>, otherwise we&rsquo;ll be back online shortly!</p>
        <p>&mdash; Webmaster</p>
    </div>
</article>

Tags: 

Switch Language HTML query

script.js

//switch language

$( "img" ).click(function()
{
$( "div.languageselect" ).toggle();
  var _this = $(this);
      var current = _this.attr("src");
      var swap = _this.attr("data-swap");    
     _this.attr('src', swap).attr("data-swap",current);
});

html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Switch Languages</title>
<meta name="description" content="Switch Languages">
<meta name="author" content="huh.snips.nl">
</head>

<body>

<img src="assets/images/englishflag.png" data-swap="assets/images/dutch.jpg" class="languageselect" alt="Mountain View" style="width:40px;height:22px;">
<div class="languageselect">English</div>
<div class="languageselect" style="display: none">Nederlands</div>

<script src="assets/js/jquery-2.1.3.min.js"></script>
<script src="assets/js/jquery.actual.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>

3d touch

Voor icon on 'desktop'

In info.plist
add:

<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconFile</key>
<string>button_continue</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Continue last puzzle</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Continue</string>
<key>UIApplicationShortcutItemType</key>
<string>com.company.bla.bla</string>
</dict>
<dict>
<key>UIApplicationShortcutItemIconFile</key>
<string>button_puzzles</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Choose new puzzle</string>
<key>UIApplicationShortcutItemTitle</key>
<string>New puzzle</string>
<key>UIApplicationShortcutItemType</key>
<string>com.company.bla.bla</string>
</dict>
</array>

in UIView

import UIKit
import AudioToolbox

protocol SelectLetterViewDelegate: class
{
    func foundChar(foundChar:String)
    func addChar(foundChar:String)
}

class SelectLetterView:UIView
{
   
    weak var delegate: SelectLetterViewDelegate?
   
    var charsToChoose =
        [">","A","B","C","D","E","F",
         "G","H","I","J","K","L",
         "M","N","O","P","Q","R",
         "S","T","U","V","W","X",
         "Y","Z","*"
    ]
    var lastChosenString = ""
    var charCollection: [UILabel] = []

    var clickon = false
    var useForceTouch = false
   
    //Mark: - Init / setup
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        self.initialize()
    }
   
    convenience init() {
        self.init(frame: CGRectZero)
       
        self.initialize()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func initialize() {
        addCharsToView()
        print("traitCollection.forceTouchCapability \(traitCollection.forceTouchCapability)")
        if traitCollection.forceTouchCapability == UIForceTouchCapability.Available
        {
            print("we have forceTouchCapability")
            useForceTouch = true
        }
        else
        {
            print("we dont have forceTouchCapability...")
        }
    }
   
    //Mark: - Layout
    func addCharsToView()
    {
        if charsToChoose.count > 0
        {
            let dimensionHeight:CGFloat = self.frame.height / CGFloat(charsToChoose.count)
            for i in 0 ..< charsToChoose.count
            {
                let view = UILabel(frame: CGRectMake(0,CGFloat(i) * dimensionHeight,self.frame.width,dimensionHeight))
                if i%2==0
                {
                    view.backgroundColor = .darkGrayColor()
                }
                else
                {
                    view.backgroundColor = .clearColor()
                }
                view.text = "\(charsToChoose[i])"
                view.textColor = .whiteColor()
                view.textAlignment = .Center
                charCollection.append(view)
                self.addSubview(view)
            }
        }
    }
   
   
    //Mark: - Touches
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        reactToTouch(touches, withEvent: event)
    }
    var canAddChar                      = false
    var lastFractionPressure:CGFloat    = 0
   
    func reactToTouch(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
       
        if let touch = touches.first
        {
            let fractionTouchPressure = touch.force/touch.maximumPossibleForce
            if fractionTouchPressure >= 1.0 && touch.force > 0 && touch.maximumPossibleForce > 0 && clickon == false && lastFractionPressure == 0
            {
                lastFractionPressure = fractionTouchPressure
                clickon = true
                canAddChar = true
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
                dispatch_after(200, dispatch_get_main_queue())
                {
                    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate)
                }
                print("click On \(touch.force/touch.maximumPossibleForce)")
               
            }
            if clickon == true && fractionTouchPressure <= 0.2
            {
                print("click off")
                clickon = false
                lastFractionPressure = 0
            }
            let position :CGPoint = touch.locationInView(self)
            if event != nil
            {
                foundCharOnTouch(position,event: event!, clickon: clickon)
            }
        }
    }
   
    func foundCharOnTouch(point:CGPoint,event:UIEvent,clickon:Bool)
    {
        for l in self.subviews
        {
            if l is UILabel
            {
                if let label = l as? UILabel
                {
                   
                    if label.pointInside(convertPoint(point, toView: label), withEvent: event)
                    {
                        lastChosenString = label.text!
                        if clickon == false
                        {
                            delegate?.foundChar(label.text!)
                        }
                        else
                        {
                            if lastFractionPressure != 0 && canAddChar
                            {
                                canAddChar = false
                                delegate?.addChar(label.text!)
                               
                            }
                        }
                    }
                }
            }
          
        }
    }
}

AppDelegate

import UIKit


enum DGShortcutItemType: String {
    case Continue
    case NewPuzzle
   
    init?(shortcutItem: UIApplicationShortcutItem) {
        guard let last = shortcutItem.type.componentsSeparatedByString(".").last else { return nil }
        self.init(rawValue: last)
    }
   
    var type: String {
        return NSBundle.mainBundle().bundleIdentifier! + ".\(self.rawValue)"
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
            handleShortcutItem(shortcutItem)
        }
        return true
    }


    func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
        handleShortcutItem(shortcutItem)
    }

    private func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) {
        if let rootViewController = window?.rootViewController, let shortcutItemType = DGShortcutItemType(shortcutItem: shortcutItem) {
            rootViewController.dismissViewControllerAnimated(false, completion: nil)
            let alertController = UIAlertController(title: "", message: "", preferredStyle: .Alert)
           
            switch shortcutItemType {
            case .Continue:
                alertController.message = "Continue"
                break
            case .NewPuzzle:
                alertController.message = "New Puzzle"
                break
            }
           
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            rootViewController.presentViewController(alertController, animated: true, completion: nil)
        }
    }
}

Tags: 

edit sites from local machine to dev server

sudo nano /etc/hosts

#server windows linux test
192.168.0.12 test.com
192.168.0.12 example.com

Tags: 

UIView init

class AView:UIView
{
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        self.initialize()
    }
   
    convenience init() {
        self.init(frame: CGRectZero)
       
        self.initialize()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func initialize() {
        doAFunc()
    }
}

Tags: 

Enum with var and func

public enum LanguageForGame:Int
{
   
    case All    = 1,
    Dutch       = 2,
    French      = 3,
    English     = 4,
    Spanish     = 5,
    German      = 6,
    Italian     = 7,
    Swedish     = 8,
    Danish      = 9
   
    public var createLanguageCode:String
    {
        switch self {
        case .English:
            return "en"
        case .German:
            return "de"
        case .Danish:
            return "da"
        case .Swedish:
            return "sv"
        case .Dutch:
            return "nl"
        case .Spanish:
            return "es"
        case .French:
            return "fr"
        case .Italian:
            return "it"
        case .All:
            return "*"
        }
    }
   
    public var createCultureCodeWithMinus:String
    {
        switch self {
        case .English:
            return "en-GB"
        case .German:
            return "de-DE"
        case .Danish:
            return "da-DK"
        case .Swedish:
            return "sv-SE"
        case .Dutch:
            return "nl-NL"
        case .Spanish:
            return "es-ES"
        case .French:
            return "fr-FR"
        case .Italian:
            return "it-IT"
        case .All:
            return "*"
           
        }
    }
    public var createCultureCodeWithUnderScore:String
    {
        switch self {
        case .English:
            return "en_GB"
        case .German:
            return "de_DE"
        case .Danish:
            return "da_DK"
        case .Swedish:
            return "sv_SE"
        case .Dutch:
            return "nl_NL"
        case .Spanish:
            return "es_ES"
        case .French:
            return "fr_FR"
        case .Italian:
            return "it_IT"
        case .All:
            return "*"
           
        }
    }
   
    public static func getLanguageNumberFromLanguagesForGame(langString:String)->Int
    {
       
        switch langString
        {
        case "en":
            return LanguageForGame.English.rawValue
        case "de":
            return LanguageForGame.German.rawValue
        case "da":
            return LanguageForGame.Danish.rawValue
        case "se":
            return LanguageForGame.Swedish.rawValue
        case "nl":
            return LanguageForGame.Dutch.rawValue
        case "es":
            return LanguageForGame.Spanish.rawValue
        case "fr":
            return LanguageForGame.French.rawValue
        case "it":
            return LanguageForGame.Italian.rawValue
        default:
            return LanguageForGame.All.rawValue
        }
       
    }
   
}

struct HashableSequence<T: Hashable>: SequenceType {
    func generate() -> AnyGenerator<T> {
        var i = 0
        return AnyGenerator {
            guard sizeof(T) == 1 else {
                return nil
            }
            let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
            if next.hashValue == i {
                i += 1
                return next
            }
           
            return nil
        }
    }
}
extension Hashable {
    static func enumCases() -> Array<Self> {
        return Array(HashableSequence())
    }
   
    static var enumCount: Int {
        return enumCases().count
    }
}

let numberOfLanguages = LanguageForGame.enumCount // 9

Tags: 

Switch Button

class SwitchButton: UIButton
{
   
    var imageOn:UIImage?
    var imageOff:UIImage?
    var stateOn = true
        {
        didSet
        {
            setImageToState(stateOn)
        }
    }
   
   
   
    //MARK: - VC
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
   
    convenience init(frame: CGRect, imgOn:UIImage, imgOff:UIImage)
    {
       
        self.init(frame: frame)
       
        self.imageOn = imgOn
        self.imageOff = imgOff
        if let img = imageOn as UIImage?
        {
            setImage(img, forState: .Normal)
        }
        self.addTarget(self, action: #selector(SwitchButton.changeState), forControlEvents: UIControlEvents.TouchUpInside)
       
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    func changeState()
    {
        self.stateOn = !self.stateOn
    }
   
    func setImageToState(On:Bool)
    {
        switch On {
        case false:
            setImage(imageOff, forState: .Normal)
        default:
            setImage(imageOn, forState: .Normal)
        }
    }
   
}

Tags: 

minecraft raspberry server

sudo apt-get update && sudo apt-get install oracle-java7-jdk
or
sudo apt-get update && sudo apt-get install oracle-java8-jdk

https://s3.amazonaws.com/Minecraft.Download/versions/1.9/minecraft-serve...

or
https://minecraft.net/download

java -Xmx1G -Xms1G -jar minecraft_server.1.9.jar -nogui

========

java -Xms512m -Xmx2048m -jar craftbukkit.jar nogui

Symphony notes

// get version 3.0 name it symfresttest

php composer.phar create-project symfony/framework-standard-edition symfresttest 3.0

// add in composer.json
// require
"symfony/console": "2.4.*@dev"
//
php composer.phar install
//
php bin/console

// Workinghours
php composer.phar create-project symfony/framework-standard-edition workhours 2.3.3

php app/console doctrine:database:create
php app/console generate:bundle
php app/console doctrine:generate:entity
php app/console doctrine:schema:update --force
php app/console generate:doctrine:crud

// udemy course
// composer
curl -sS https://getcomposer.org/installer | php
// symfony
php composer.phar create-project symfony/framework-standard-edition 3.0
//

in composer.json
onder extra

"symfony-assets-install": "symlink",

php composer.phar update -d symfonyCourse/

in controller

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
/**
* @Route("/hello/{name}")
* @Template()
*/
public function indexAction($name)
{
$response = new Response(json_encode(array("name"=>"hjh!")));
$response->headers->set('Content-Type', 'Application/json');
return $response;

}
}

php bin/console doctrine:generate:entity

php bin/console doctrine:schema:update --dump-sql

php bin/console doctrine:database:create

$em = $this->getDoctrine()->getManager();
$em->persist($workout);
$em->flush();

$response = new Response(json_encode(array("addWorkout"=>"","errors"=>0)));
$response->headers->set('Content-Type', 'Application/json');
return $response;

public function indexAction()
{
$workouts = $this->getDoctrine()
->getRepository('AppallWorkoutBundle:Workout')
->findAll();
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
JsonEncoder()));
$workouts_json = $serializer->serialize($workouts, 'json');
$response = new Response(json_encode(array("workouts"=>$workouts_json,"errors"=>0)));
$response->headers->set('Content-Type', 'Application/json');
return $response;

}

php bin/console doctrine:schema:update --force

Tags: 

Git remote repo lokaal network

op de server git proj maken

mkdir repoName.git
cd repoName.git/
git --bare init
Initialized empty Git repository in /volume1/git/repoName.git/
git update-server-info
cd ..
chown -R loginname repoName.git

clonen proj van server

git clone ssh://login@192.168.0.1/volume1/git/repoName.git

lokaal proj files toevoegen:

git init
git remote add origin ssh://login@192.168.0.1/volume1/git/repoName.git
//git push -f
git config --global push.default simple
// add your files
git add .
git commit -a -m "Initial Commit"
git push -u origin --all

extra:

git remote
bv : origin

git remote -v
origin https://github.com/schacon/ticgit (fetch)
origin https://github.com/schacon/ticgit (push)

push to remote

git push origin master

inspecting

git remote show origin

renaming

$ git remote rename pb paul
$ git remote
origin
paul

removing

$ git remote rm paul
$ git remote
origin

New clean mac install

Old macbook and reinstall fails with error while preparing ... on clean reinstall
Is because of not having a set date...
goto Terminal and

date mmddHHMMyyyy

now it will reinstall

hidden files in terminal mac

defaults write com.apple.finder AppleShowAllFiles YES

killall Finder

Tags: 

c++ for loops

char s[] = "string";
  printf("string is %s\n",s);
  for (int i = 0 ; s[i]; i++)
  {
    printf("string is %c\n",s[i]);
  }
  printf("---\n");
  for (char *cp=s;*cp;++cp)
  {
    printf("string is %c\n",*cp);
  }
  printf("---\n");
  for (char c: s)
  {
    if (c==0)break;// extra element 0!!so break!!
    printf("string is %c\n",c);
  }// extra element 0!!

Tags: 

find file type in terminal

find . -type f -name "*.txt"

Tags: 

Installing CocoaPods on OS X 10.11

Installing CocoaPods on OS X 10.11

$ sudo chmod -R 755 /usr/local/bin
$ sudo gem uninstall cocoapods
Remove executables:
pod, sandbox-pod

in addition to the gem? [Yn] Y

$ gem install cocoa pods

$ pod install

==
OR
==

These instructions were tested on all betas and the final release of El Capitan.

Custom GEM_HOME

This is the solution when you are receiving Above Error

$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version

Tags: 

Cocoapods in Playgrounds

Install:

$ gem install cocoapods-playgrounds
Create a Playground with Alamofire:

$ pod playgrounds Alamofire
Create a Playground with multiple pods:

$ pod playgrounds RxSwift,RxCocoa
The new Playground will automatically open.

You will have to first build the project, to enable the pods, then the Playground will be available.

===
Or:

During the app development, you may find a third-party libraries or frameworks may save you a lot of time and let you focus on your fancy features. However, you always want to verify whether the functions provided by the library are what you expect. To do so, playground is a prefect place to test them out.

Using CocoaPods
CocoaPods manages library dependencies for your Xcode projects.
You first need to install CocoaPods. Open Terminal and enter the following command:

sudo gem install cocoapods

Enter your password when requested. Then enter this command in Terminal to complete the setup:

pod setup --verbose

This process will likely take a few minutes, and the verbose option logs progress as the process runs, allowing you to watch the process instead of seeing a seemingly “frozen” screen.

Installing Your Dependency
Create a Xcode project if you don't have one, and then close Xcode.
Open Terminal and navigate to the directory that contains your project:

cd ~/Path/To/Folder/Containing/YourProject

Next, enter this command:

pod init

This creates a Podfile for your project.
Open the Podfile using Xcode for editing, and you can use this command:

open -a Xcode Podfile

The default Podfile looks like this:

# Uncomment this line to define a global platform for your project
# platform :ios, '8.0'

target 'YourProject' do

end

target 'YourProjectTests' do

end

Change it with following:

platform :ios, "8.0"
use_frameworks!

link_with 'YourProject', 'YourProjectTests'
pod 'Alamofire'
pod 'SwiftyJSON'

In my example, I am going to use Alamfire and SwiftyJSON libraries in my project. You can change it to whatever library you would like to play with.

Jump back the Terminal, and use this command to install pods:

pod install

And after the installation, the last line of the output should be like this:

[!] Please close any current Xcode sessions and use `YourProject.xcworkspace` for this project from now on.

The CocoaPads creates a workspace based on your project, as the command-line warning mentioned, you must always use the workspace and not the project, otherwise you’ll encounter build errors.

By using a workspace, all dependencies are available cross the workspace.
Create a playground in the workspace, and add it to the Podfile with following:

platform :ios, "8.0"
use_frameworks!

link_with 'YourProject', 'YourProjectTests', 'YourPlayground'
pod 'Alamofire'
pod 'SwiftyJSON'

You can import and use the pod your have installed in the playground:

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

import SwiftyJSON
import Alamofire

Congratulations, you can play with your third-party pods in Playground!

Tags: 

Sails js 2

Sailsjs for backend rest api

==
help with salsas:

  • Google Groups: sails.js
  • IRC: #sailsjs
  • Stack Overflow (using tag sails.js)

==
instal

mac:
nodejs.org
download pkg
(
/usr/local/bin/node
/usr/local/bin/npm
add to $PATH
/usr/local/bin
)

(sudo) npm install sails –global

==
setup first project
sails new firstApp

move to folder
cd firstApp

to start sails:
sails lift

generate new model via blueprint engine
sails generate api user

then question about migrate on sails lift
choose alter in non Prod env
change firstApp/config/model.js

module.exports.models = {
migrate: 'alter'
};

http://localhost:1337/user
first results
in json response []

localhost:1337/user/create?name=HJSnips
results in

[
 
  {
    "name": "HJSnips",
    "createdAt": "2016-03-30T07:30:39.555Z",
    "updatedAt": "2016-03-30T07:30:39.555Z",
    "id": 1
  }
]

==
use Sails built-in integration
with websockets and Socket.io

create
firstApp/assets/js/test.js

io.socket.get('/user', function (users){ console.log(users);});
io.socket.on('user', function (message) {
console.log("Got message: ", message);
});

==
policies
firstApp/config/policies.js
module.exports.policies = {
'UserController': {
'create': ['sessionAuth']
}
};

==
static assets
npm install sails-generate-static --save

sails generate static

sails lift
now when adding content to assets Grunt will create routes files in .tmp

== css assets
to use css in html via grunt make sure:

<!--STYLES-->
<!--STYLES END-->

are in!

<head>
<title>New Sails App</title>
<!-- Viewport mobile tag for sensible mobile support -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
   
<!--STYLES-->
<!--STYLES END-->
</head>

<html>
<body>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<!--TEMPLATES-->
<!--TEMPLATES END-->
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>


</html>

Calc days between dates

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Tags: 

Pages

Subscribe to hjsnips RSS