App installed

func isAppInstalled(name:String)->Bool {
    return UIApplication.sharedApplication().canOpenURL(NSURL(string:"\(name):")!)
}

Tags: 

Meteor setup project with accounts

meteor --version
meteor update --release 1.6.1

Router:

meteor add iron:router

Bootstrap:

meteor add twbs:bootstrap

Accounts:

meteor add accounts-ui accounts-password
meteor add joshowens:accounts-entry
meteor npm install --save bcrypt
meteor add check

adjust client with code from
https://github.com/Differential/accounts-entry/

meteor

Install
cd $HOME

git clone --depth 1 https://github.com/4commerce-technologies-AG/meteor.git

#now it installs if it is the first time!
$HOME/meteor/meteor --version

==========================
======= slow version =======
==========================

cd $HOME

git clone --depth 1 https://github.com/4commerce-technologies-AG/meteor.git

cd meteor

Build bundled node:

scripts/build-node-for-dev-bundle.sh

Get mongodb installation from OS (e.g. Debian based):

sudo apt-get install mongodb

Optional (long runner) build bundled mongo:

scripts/build-node-for-dev-bundle.sh
Beneath the compiler and development tools and standard libaries, you have to also install the zlib1g-dev (or whatever it's named on your OS) library sources. Otherwise the mongo build will fail with an error like "-lz is missing"

Build meteor dev_bundle:

scripts/generate-dev-bundle.sh

Check installed version:

$HOME/meteor/meteor --version
==========================
========= helpfull snips =====
==========================

cd $HOME

# get the command line to checkout the meteor example
$HOME/meteor/meteor create --example simple-todos-react

# this is what you will receive as command hint, so put it in
git clone https://github.com/meteor/simple-todos-react

# jump into the project folder
cd simple-todos-react

# get necessary npm stuff
$HOME/meteor/meteor npm install

# bring that project up to latest module updates
$HOME/meteor/meteor update --packages-only

# add one package to avoid counting of modules usage and DDP error message on start
$HOME/meteor/meteor add package-stats-opt-out

# run that app
$HOME/meteor/meteor

Raspberry gpio

Read value

import RPi.GPIO as GPIO

# read value
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN)
poweron = GPIO.input(21)
GPIO.cleanup(21)

print "turnonheater"
    GPIO.setup(21,GPIO.OUT, initial=GPIO.HIGH)
    GPIO.output(21, GPIO.HIGH)
    GPIO.cleanup(21)

print "turnoffheater"
    GPIO.setup(21,GPIO.OUT, initial=GPIO.LOW)
    GPIO.output(21, GPIO.LOW)
    GPIO.cleanup(21)

Crash Log Helper

.h

@interface CrashLogHelper : NSObject

+(void) writeNoCrashFile;
+(void) removeNoCrashFile;

.m
+(void) writeNoCrashFile
{
    NSError *error;
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"crashloggername.txt"];
    NSLog(@"file path for write nocrash file%@", filePath);
    NSFileManager *filemgr;
   
    filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: filePath ] == YES)
    {
        NSLog (@"File exists, so it did crash");
        [App.persistenceHelper setString:@"-1" forPersistentKey:PERSISTENCEHELPER_ratingsequence];
    }
    else
    {
        NSLog (@"File not found");
        // write new file
        NSString *stringToWrite = @"no crash";
        [stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
}
+(void) removeNoCrashFile
{
    NSFileManager *filemgr;
    NSError *error;
    filemgr = [NSFileManager defaultManager];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"crashlogger.txt"];
  
    if ([filemgr fileExistsAtPath: filePath ] == YES){
        NSLog (@"File exists so remove");
        BOOL success = [filemgr removeItemAtPath:filePath error:&error];
        if (success) {
            NSLog(@"file removed");
        }
        else
        {
            NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        }
    }
    else{
        NSLog (@"File not found"); // something fishy
    }
   
}

Tags: 

Screenwidth screen height

+ (CGFloat) getScreenWidth
{
    CGFloat swidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat sheight = [UIScreen mainScreen].bounds.size.height;
    return MIN(swidth, sheight);
}

+ (CGFloat) getScreenHeight
{
    CGFloat swidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat sheight = [UIScreen mainScreen].bounds.size.height;
    return MAX(swidth, sheight);
}

Tags: 

Read Write file IO

+(void) writeTextFile
{
    NSError *error;
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"text.txt"];
    NSFileManager *filemgr;
   
    filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: filePath ] == YES)
    {
        NSLog (@"File exists");
    }
    else
    {
        NSLog (@"File not found");
        // write new file
        NSString *stringToWrite = @"text text text";
        [stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
}
+(void) removeTextFile
{
    NSFileManager *filemgr;
    NSError *error;
    filemgr = [NSFileManager defaultManager];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"text.txt"];
  
    if ([filemgr fileExistsAtPath: filePath ] == YES){
        NSLog (@"File exists so remove");
        BOOL success = [filemgr removeItemAtPath:filePath error:&error];
        if (success) {
            NSLog(@"file removed");
        }
        else
        {
            NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        }
    }
    else{
        NSLog (@"File not found"); // something fishy
    }
   
}

Tags: 

port mysql

SHOW GLOBAL VARIABLES LIKE 'PORT';

Tags: 

Drupal small core update drush

sudo apt-get update

put in maintenance mode:
drush vset --exact maintenance_mode 1 drush cache-clear all
update:
drush pm-update drupal
update modules:
drush up
update specific module:
drush up [module]
put out of maintenance mode:
drush vset --exact maintenance_mode 0 drush cache-clear all

Swift raspberry

sudo apt-get update
sudo apt-get install -y clang
wget https://s3-us-west-2.amazonaws.com/swiftpi.swiftlite.v1/swift-lite-3.0-r...
sudo tar -xzpf swift-lite-3.0-raspberrypi-universal.tar.gz -C/

examples
wget https://s3-us-west-2.amazonaws.com/swiftpi.swiftlite.v1/helloworld3.tar.gz
tar -xzpf helloworld3.tar.gz

cleanup
rm swift-lite-3.0-raspberrypi-universal.tar.gz helloworld3.tar.gz

to build
cd swiftProjects
swift-lite-build helloworld.swift

test/run
./helloworld.swapp

swift server Kitura

first

mkdir tuinhok
cd tuinhok
swift package init --type executable

adjust Package.swift
import PackageDescription


let package = Package(
  name: "proj1",
  dependencies: [
    .Package(url: "https://github.com/IBM-Swift/Kitura.git",
             majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1)
    ]
)

swift package generate-xcodeproj
mkdir public - for js css img etc
mkdir Views - for stencil files

in main swift
import Kitura
import LoggerAPI
import HeliumLogger
import KituraStencil

HeliumLogger.use(.info)
let router = Router()
router.setDefault(templateEngine: StencilTemplateEngine())
router.all("/static", middleware: StaticFileServer())

router.get("/") {
  request, response, next in
  defer { next() }
  try response.render("home", context: [:])
}

Kitura.addHTTPServer(onPort: 8090, with: router)

Kitura.run()

Tags: 

size databases

SELECT table_schema AS `Database`,
SUM(data_length + index_length) / 1024 / 1024 AS `Size in MB`
FROM information_schema.TABLES
GROUP BY table_schema;

Tags: 

xcode 3.7.1 cocoapods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'testNetworkingOperation' do
    pod 'Alamofire', '~> 3.0'
     pod 'SwiftyJSON', '2.4.0'
end

Tags: 

nodejs express

npm init

npm install express --save
npm install body-parser --save
npm install nodemon --save / --g
npm install bcryptjs --save

create app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('listening on port 3000')
})

Tags: 

Gitignore visual studio 2017

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# JetBrains Rider
.idea/
*.sln.iml

# CodeRush personal settings
.cr/personal

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

Symphony snips

timezone
in app kernel.php

public function __construct($environment, $debug)
{
    date_default_timezone_set('Europe/Amsterdam');
    parent::__construct($environment, $debug);
}

server:
php bin/console server:run

php bin/console generate:bundle

composer require knplabs/knp-menu-bundle dev-master

bin/console doctrine:database:create
( drop:
bin/console doctrine:database:drop --force
)

bin/console doctrine:generate:entity
bin/console doctrine:schema:update --force

Fish, bash commands as functions

edit start .bashrc

~/.config/fish/config.fish

functions

p/crossword> function nrh
                               npm run hot
                       end
p/crossword> funcsave nrh
p/crossword> nrh
make Atom.app run from terminal:
ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom
make function in Fish:
nano ~/.config/fish/functions/atom.fish
some functions:
function atom
    bash -c 'atom .'
end
function pstorm
    bash -c 'open -a /Applications/PhpStorm.app .'
end

function xcodeclean
        command rm -rf ~/Library/Developer/Xcode/DerivedData/*
end

function ll
    ls -lahG $argv
end

function rmpoddata
    pod deintegrate
    rm -rf Pods
    rm -rf Podfile.lock
    pod install
end

function rmderiveddata
    sudo rm -rf ~/Library/Developer/Xcode/DerivedData/*
end

Tags: 

for loop log vector

// log vector
for (auto const& c : numbers)
{
    std::cout << c << ' ';
}

Tags: 

Before After in collection

public extension Collection where Iterator.Element: Equatable {

public func after(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(after: idx) < endIndex else { return nil }
let nextIdx = index(after: idx)
return self[nextIdx]
}

public func before(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(before: idx) >= startIndex else { return nil }
let previousIdx = index(idx, offsetBy: -1)
return self[previousIdx]
}

public func index(before idx: Index) -> Index {
return index(idx, offsetBy: -1)
}
}

Tags: 

ZoomableGridVC

enum GridFillDirection
{
    case Horizontal, Vertical
}

class ZoomableGridViewController: UIViewController,UIScrollViewDelegate {
   
    //MARK: - Properties
   
    var scrollView: UIScrollView!
    var scrollIsZoomedIn = false
    var gridView: UIView!//Grid!//or image etc
   
    var puzzleDirection:GridFillDirection = .Horizontal
   
    var logText:UILabel!
   
    //MARK: - VC
    override func viewDidLoad() {
        super.viewDidLoad()
       
        gridView = UIImageView(image: UIImage(named: "nasa_big"))//UIView(frame: CGRectMake(0,0,view.bounds.width,view.bounds.width))//
       
        scrollView = UIScrollView(frame: CGRectMake(0,80,view.bounds.width,view.bounds.width))
        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.contentSize = gridView.bounds.size
        scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
        scrollView.delegate = self
        scrollView.maximumZoomScale = 4.0
        setZoomScale()
        scrollView.contentOffset = CGPoint(x: 0, y: 0)
        scrollView.addSubview(gridView)
        view.addSubview(scrollView)
       
        setupGestureRecognizer()
       
        setupLogText()
    }
   
    //MARK: - Setup Layout
    func setupLogText()
    {
        let logtextHeight:CGFloat = 40
        logText = UILabel(frame: CGRectMake(0,view.bounds.height-logtextHeight,view.bounds.width,logtextHeight))
        logText.textAlignment = .Center
        view.addSubview(logText)
        createLogText()
    }
   
    func createLogText()
    {
        let text = (puzzleDirection == .Horizontal) ? "Hori" :  "Verti"
        logText.text = "\(text) zoom : \(scrollView.zoomScale) "
    }
   
    func setZoomScale() {
       
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        let heightScale = scrollView.bounds.size.height / gridView.bounds.size.height
       
        scrollView.minimumZoomScale = min(widthScale, heightScale)
        scrollView.zoomScale = widthScale
    }
   
    //MARK: - ScrollView delegates
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return gridView
    }
   
    func scrollViewDidZoom(scrollView: UIScrollView) {
       
        let verticalPadding = gridView.bounds.size.height < scrollView.bounds.size.height ? (scrollView.bounds.size.height - gridView.bounds.size.height) / 2 : 0
        let horizontalPadding = gridView.bounds.size.width < scrollView.bounds.size.width ? (scrollView.bounds.size.width - gridView.bounds.size.width) / 2 : 0
       
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
       
    }
   
    //MARK: - Gestures
    func setupGestureRecognizer() {
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleDoubleTap(_:)))
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
       
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSingleTap(_:)))
        singleTap.numberOfTapsRequired = 1
        scrollView.addGestureRecognizer(singleTap)
       
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRight)
       
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeDown.direction = UISwipeGestureRecognizerDirection.Down
        self.view.addGestureRecognizer(swipeDown)
       
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        self.view.addGestureRecognizer(swipeLeft)
       
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeUp.direction = UISwipeGestureRecognizerDirection.Up
        self.view.addGestureRecognizer(swipeUp)
       
    }
   
    func handleSwipeGesture(gesture: UIGestureRecognizer) {
       
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
           
            createLogText()
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
               
                logText.text? += "Swiped right select next horizontal region"
                if swipeGesture.state == UIGestureRecognizerState.Began
                {
                   
                }
               
            case UISwipeGestureRecognizerDirection.Down:
               
                logText.text? += "Swiped down select next vertical region"
               
               
            case UISwipeGestureRecognizerDirection.Left:
               
                logText.text? += "Swiped left select previous horizontal region"
               
               
            case UISwipeGestureRecognizerDirection.Up:
               
               
                logText.text? += "Swiped up select previous vertical region"
               
               
            default:
                break
            }
        }
    }
   
    func checkZoomState()
    {
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        if widthScale == scrollView.zoomScale
        {
            //print("zoom scale full")
            scrollIsZoomedIn = false
        }
        else
        {
            //print("zoom scale zoomed")
            scrollIsZoomedIn = true
        }
    }
   
    func handleSingleTap(recognizer: UITapGestureRecognizer)
    {
        checkZoomState()
        createLogText()
        if scrollIsZoomedIn
        {
            logText.text? += "singleTap - selected cell if selected change direction"
        }
        else
        {
            logText.text? += "singleTap - selected cell "
        }
    }
   
    func handleDoubleTap(recognizer: UITapGestureRecognizer) {
        //print("double tap")
        checkZoomState()
        createLogText()
        if puzzleDirection == .Horizontal
        {
            puzzleDirection = .Vertical
        }
        else
        {
            puzzleDirection = .Horizontal
        }
    
    }
 
}

Tags: 

UIGesture Tap

let tap = UITapGestureRecognizer(target: self, action: #selector({class}.{func}))
addGestureRecognizer(tap)

Tags: 

Pool

class Pool<T> {
    private var objectPool = [T]()
   
    init(items:[T]) {
        objectPool.reserveCapacity(objectPool.count)
        for item in items {
            objectPool.append(item)
        }
    }
   
    func getFromPool() -> T? {
        var result:T?
        if objectPool.count > 0 {
            result = self.objectPool.removeAtIndex(0)
        }
        return result
    }
   
    func returnToPool(item:T) {
        self.objectPool.append(item)
    }
}

Tags: 

Touch Tap

func handleSingleTap(sender:UITapGestureRecognizer){
        print("tapped")
    }
   
    func addTapGesture()
    {
        let singleTap = UITapGestureRecognizer(target:self, action:#selector(handleSingleTap))
        singleTap.numberOfTouchesRequired = 1
        singleTap.addTarget(self, action:#selector(handleSingleTap))
        view.userInteractionEnabled = true
        view.addGestureRecognizer(singleTap)
    }

or a touch view

enum Tap {
    case Single
    case Draw
    case Long
   
}

protocol HJHTouchViewDelegate: class{
    func removeSelectedFields()
    func checkThisLoc(pnt:CGPoint)
    func checkThisLocForMove(pnt:CGPoint)
    func touchEnded()
    func longpressAt(pnt:CGPoint)
    func longPressEnd()
}

class TouchView: UIView {
   
    weak var delegate: HJHTouchViewDelegate?
    var tC = 0
    var touchCells = [UIButton]()
    var startTime = NSDate()
    var longPresseTime:Double = 0.5
    var longPressTimer = NSTimer()
    var isInLongPress = false
    var isMoving = false
   
   
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        let touch = touches.first!
        tC = 0
        longPressTimer = NSTimer()
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.removeSelectedFields()
        delegate?.checkThisLoc(pnt)
        isInLongPress = false
        isMoving = false
       
        startTime = NSDate()
        longPressTimer =
            NSTimer.scheduledTimerWithTimeInterval(longPresseTime, target: self, selector: #selector(TouchView.updateTime(_:)), userInfo: [pnt.x, pnt.y], repeats: false
        )
       
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        isMoving = true
        if isInLongPress
        {
            isInLongPress = false
            delegate?.longPressEnd()
        }
        let touch = touches.first! //as! UITouch
        tC += 1
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.checkThisLocForMove(pnt)
       
    }
   
   
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        longPressTimer.invalidate()
        isInLongPress = false
       
        delegate?.touchEnded()
    }
   
    func updateTime(timer:NSTimer)
    {
        if isInLongPress ==  true || isMoving == true
        {
            return
        }
       
        if timer.userInfo != nil
        {
            if let info: AnyObject = timer.userInfo
            {
                if isInLongPress == false
                {
                    isInLongPress = true
                    var arr:[CGFloat] = info as! [CGFloat]
                    delegate?.longpressAt( CGPoint(x: arr[0],y: arr[1]))
                }
            }
        }
    }
}

Tags: 

MongoDb on rasp (notes)

on rasp
sudo /usr/bin/mongod --quiet --rest --config /etc/mongodb.conf
===
sudo nano /etc/mongodb.conf
>
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

bind_ip = 127.0.0.1,192.168.0.14
port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

in rested

http://192.168.0.14:28017/test/
POST
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/json
Accept-Language: en-us

{
"user": {
"email": "blassa4@bbbla.com",
"pwd": "test4",
"username": "test4"
}
}

base64

var str = "Hello, playground"
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)//<48656c6c 6f2c2070 6c617967 726f756e 64>

if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
   
    "Encoded:  \(base64Encoded)"//"Encoded:  SGVsbG8sIHBsYXlncm91bmQ="
   
    if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
        .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
    {
        // Convert back to a string
        "Decoded:  \(base64Decoded)"//"Decoded:  Optional(Hello, playground)"
    }
}

Tags: 

Regex

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var string = "aarde"
matchesForRegexInText("aa..e", text: string)

Tags: 

Remove Duplicates Use a Set

// Initialize the Array
var a = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates:
// first by converting to a Set
// and then back to Array
a = Array(Set(a))

print(a)

Tags: 

Text Spacing

extension UILabel{
    func addTextSpacing(spacing: CGFloat){
        let attributedString = NSMutableAttributedString(string: self.text!)
        attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.text!.characters.count))
        self.attributedText = attributedString
    }
}

cell.titleLabel.addTextSpacing(1.4)

Tags: 

moving/renaming xcode

from:
/Applications/Xcode.app
=>
/Applications/xcode/Xcode73.app

sudo xcode-select -switch /Applications/xcode/Xcode73.app/Contents/Developer

remove xcode plugins:
rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/*

Tags: 

nd char in String

extension String {

    func index(at offset: Int, from start: Index? = nil) -> Index?
    {
        return index(start ?? startIndex, offsetBy: offset, limitedBy: endIndex)
    }

    func character(at offset: Int) -> Character?
    {
        precondition(offset >= 0, "offset can't be negative")
        guard let index = index(at: offset) else { return nil }
        return self[index]
    }

    subscript(_ range: CountableRange<Int>) -> Substring
    {
        precondition(range.lowerBound >= 0, "lowerBound can't be negative")
        let start = index(at: range.lowerBound) ?? endIndex
        return self[start..<(index(at: range.count, from: start) ?? endIndex)]
    }

    subscript(_ range: CountableClosedRange<Int>) -> Substring
    {
        precondition(range.lowerBound >= 0, "lowerBound can't be negative")
        let start = index(at: range.lowerBound) ?? endIndex
        return self[start..<(index(at: range.count, from: start) ?? endIndex)]
    }

    subscript(_ range: PartialRangeUpTo<Int>) -> Substring
    {
        return prefix(range.upperBound)
    }

    subscript(_ range: PartialRangeThrough<Int>) -> Substring
    {
        return prefix(range.upperBound+1)
    }

    subscript(_ range: PartialRangeFrom<Int>) -> Substring
    {
        return suffix(max(0, count-range.lowerBound))
    }

}

extension Substring {
    var string: String { return String(self) }
}

var abc = "abcdefg"
//2nd char
String(abc[abc.characters.startIndex.advancedBy(1)]) //"b"

get range with
extension String {
   
    subscript (i: Int) -> Character
    {
        return self[self.startIndex.advancedBy(i)]
    }
   
    subscript (r: Range<Int>) -> String
    {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        return self[Range(start ..< end)]
    }
}

results: abc[0...1] // "ab"
abc[1] = "a"
Or
Array(abc.characters)[1] //"b"

Tags: 

Pages

Subscribe to hjsnips RSS