Docker.qcow2 never shrinks

~/Library/Containers/com.docker.docker/

rm Docker.qcow2

Tags: 

price in SKProduct in local currency

func priceStringForProduct(item: SKProduct) -> String? {
        let price = item.price
        if price == 0 {
            return "Free!" //todo: Translate
        } else {
            let numberFormatter = NumberFormatter()
            let locale = item.priceLocale
            numberFormatter.numberStyle = .currency
            numberFormatter.locale = locale
            return numberFormatter.string(from: price)
        }
    }

Tags: 

emitter explosion

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
         createParticles()
    }

    func createParticles() {
        let v = UIView(frame: CGRect(x: 180, y: 220, width: 60, height: 60))
        //v.backgroundColor = .lightGray
        view.addSubview(v)
        let particleEmitter = CAEmitterLayer()
       
        particleEmitter.emitterPosition = CGPoint(x: 30, y: 30)
        particleEmitter.emitterShape = kCAEmitterLayerSphere
        particleEmitter.emitterSize = CGSize(width: 1, height: 1)
       
        let red = makeEmitterCell(color: UIColor.red)
        let green = makeEmitterCell(color: UIColor.green)
        let blue = makeEmitterCell(color: UIColor.blue)
       
        particleEmitter.emitterCells = [red, green, blue]
       
        v.layer.addSublayer(particleEmitter)
        UIView.animate(withDuration: 2.0, animations: {
            v.alpha = 0
        }) { (_) in
            v.layer.sublayers?.removeAll()
        }
    }
   
    func makeEmitterCell(color: UIColor) -> CAEmitterCell {
        let cell = CAEmitterCell()
        cell.birthRate = 2.5
        cell.lifetime = 1.9
        cell.lifetimeRange = 1
        cell.color = color.cgColor
        cell.velocity = 158
        cell.velocityRange = 45
        cell.emissionLongitude = CGFloat.pi
        cell.emissionRange = CGFloat.pi
        cell.spin = 4
        cell.spinRange = 6
        cell.scaleRange = 0.04
        cell.scaleSpeed = 0.3
        cell.xAcceleration = -0.03
        cell.yAcceleration = -0.05
        cell.zAcceleration = 0.2
       
        cell.contents = UIImage(named: "cp")?.cgImage
        return cell
    }
}

Tags: 

version build

if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString"),
            let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String)
{
     versionLabel.text = "v\(version).\(build)"
}

Tags: 

String contains substring

extension String {
    func contains(find: String) -> Bool{
        return self.range(of: find) != nil
    }
    func containsIgnoringCase(find: String) -> Bool{
        return self.range(of: find, options: .caseInsensitive) != nil
    }
}

Tags: 

Image from UIView

func imageWithView(inView: UIView) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(inView.bounds.size, inView.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        inView.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
    return nil
}

Tags: 

iPhone x uiviewcontroller

class BaseVC: UIViewController
{
   var shouldHideHomeIndicator     = false
   public let stage                = UIView()

   override func viewDidLoad() {
       super.viewDidLoad()
       HLog.info(function:#function, message: "BaseVC")

       navigationController?.setToolbarHidden(true, animated: false)
       navigationController?.navigationBar.isHidden = true

       setupLayout()
   }


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

       self.shouldHideHomeIndicator = true
       if #available(iOS 11.0, *) {
           self.setNeedsUpdateOfHomeIndicatorAutoHidden()
       } else {
           // Fallback on earlier versions
       }
   }

   override var prefersStatusBarHidden: Bool
   {
       return true
   }

   override func preferredScreenEdgesDeferringSystemGestures() ->
UIRectEdge {
       return .top
   }

   override func prefersHomeIndicatorAutoHidden() -> Bool
   {
       return shouldHideHomeIndicator
   }
   //MARK: - Layout
   func setupLayout()
   {
       createStage()
   }

   func createStage()
   {

       let ninesixteen = (sw/9.0*16.0).rounded()
       if ninesixteen <= sh
       {
           stage.frame = Frame(x: 0, y: 0, width: sw, height: ninesixteen)
       }
       else
       {
           stage.frame = Frame(x: 0, y: 0, width: sh/16.0*9.0, height: sh)
       }
       stage.backgroundColor = .clear
       stage.center = view.center
       view.addSubview(stage)
   }

   //MARK: - Helper
   func goto(vc:UIViewController)
   {
       AudioPlayerHelper.play(audioButtonClick)
       UIApplication.shared.keyWindow?.rootViewController = vc.self
   }
}

Tags: 

array with functions

class Bla
{
   let arrayOfFunctions = [function1, function2]

   func function1()
   {
      print("function1")
   }

    func function2() {
        print("function2")
    }

   func useTheFuncs()
   {
    let fn1 = arrayOfFunctions[0]
    fn1(self)()
   }
}

Tags: 

CABasicAnimation

grow shrink, heartbeat?

let img = UIImage(named: "red_star_2")
let imgv = UIImageView(image: img)
let theAnimation = CABasicAnimation()
theAnimation.keyPath = "transform.scale"
theAnimation.duration = 0.7
theAnimation.repeatCount = .infinity
theAnimation.autoreverses = true
theAnimation.fromValue = 1.0
theAnimation.toValue = 1.3
theAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
imgv.layer.add(theAnimation, forKey: "animateOpacity")
imgv.center = CGPoint(x: 50, y: 50)
view.addSubview(imgv)

rotation
let kRotationAnimationKey = "com.myapplication.rotationanimationkey"

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = Float(M_PI * 2.0)
        rotationAnimation.duration = 0.2
        rotationAnimation.repeatCount = Float.infinity
        turningStar.layer.add(rotationAnimation, forKey: kRotationAnimationKey)

with completion
import UIKit
import PlaygroundSupport

let viewFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
let view = UIView(frame: viewFrame)
view.backgroundColor = .white
PlaygroundPage.current.liveView = view

let v = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
v.backgroundColor = .red
view.addSubview(v)

CATransaction.begin()
print("start")
let a = CABasicAnimation(keyPath: "position")
a.fromValue = [100, 100]
a.toValue = [200, 200]
a.duration = 2
CATransaction.setCompletionBlock{ print("ended")
}

v.layer.add(a, forKey: nil)
CATransaction.commit()

Tags: 

Link write review in app store

#available(iOS 10, *)!!!

let appID = "959379869"

if let checkURL = URL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appID)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8") {
    open(url: checkURL)
} else {
    print("invalid url")
}

...

func open(url: URL) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
            print("Open \(url): \(success)")
        })
    } else if UIApplication.shared.openURL(url) {
            print("Open \(url)")
    }
}

Tags: 

Action order for CAKeyframeAnimation

Swift 3

CATransaction.begin()
CATransaction.setCompletionBlock {
    //Actions to be done after animation
}
//Animation Code
CATransaction.commit()

Array copy clone

//Protocal that copyable class should conform
protocol Copying {
    init(original: Self)
}

//Concrete class extension
extension Copying {
    func copy() -> Self {
        return Self.init(original: self)
    }
}

//Array extension for elements conforms the Copying protocol
extension Array where Element: Copying {
    func clone() -> Array {
        var copiedArray = Array<Element>()
        for element in self {
            copiedArray.append(element.copy())
        }
        return copiedArray
    }
}

//Simple Swift class that uses the Copying protocol
final class MyClass: Copying {
    let id: Int
    let name: String
   
    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
   
    required init(original: MyClass) {
        id = original.id
        name = original.name
    }
}

//Array cloning
let objects = [MyClass]()
//fill objects array with elements
let clonedObjects = objects.clone()

Tags: 

Blurred footprint

extension uiimage

public func modifiedImage(_ draw: (CGContext, CGRect) -> ()) -> UIImage {
       
        // using scale correctly preserves retina images
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context: CGContext! = UIGraphicsGetCurrentContext()
        assert(context != nil)
       
        // correctly rotate image
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
       
        let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
       
        draw(context, rect)
       
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
public func tintPictogram(with fillColor: UIColor) -> UIImage {
       
        return modifiedImage { context, rect in
            // draw tint color
            context.setBlendMode(.normal)
            fillColor.setFill()
            context.fill(rect)
           
            // mask by alpha values of original image
            context.setBlendMode(.destinationIn)
            context.setAlpha(0.15)
            context.draw(cgImage!, in: rect)
        }
    }

general:
func blurImage(_ image:UIImage) -> UIImage? {
    let context = CIContext(options: nil)
    let inputImage = CIImage(image: image)
    let originalOrientation = image.imageOrientation
    let originalScale = image.scale
   
    let filter = CIFilter(name: "CIGaussianBlur")
    filter?.setValue(inputImage, forKey: kCIInputImageKey)
    filter?.setValue(3.0, forKey: kCIInputRadiusKey)
    let outputImage = filter?.outputImage
   
    var cgImage:CGImage?
   
    if let asd = outputImage
    {
        cgImage = context.createCGImage(asd, from: (inputImage?.extent)!)
    }
   
    if let cgImageA = cgImage
    {
        return UIImage(cgImage: cgImageA, scale: originalScale, orientation: originalOrientation)
    }
   
    return nil
}

use:
if let image = UIImage(named:name)
            {
                 let tintimg = image.tintPictogram(with: .black)
                if let shadowedimage = blurImage(tintimg){
                //...    shadowImages.append(shadowedimage)
                }
               
            }

Tags: 

notes from new es6

probeer in:
http://jsbin.com/

imports

You got two different types of exports: default (unnamed) and named exports:

default => export default ...;

named => export const someData = ...;

You can import default exports like this:

import someNameOfYourChoice from './path/to/file.js';

Named exports have to be imported by their name:

import { someData } from './path/to/file.js'

snips

const myName = 'hjh';
///console.log(myName);

function printName(name){
  console.log(name);
}
const printName2 = (name,age) =>{
  console.log('2: '+name+' age: '+age);
}
//printName("hhhh");
//printName2("hhhh");

const multiply = (number) =>{
  return number * 2;
}
const multiply2 = number => number * 2;

//printName(multiply(4));
//printName(multiply2(4));

class Person{
 
  constructor(name){
    this.name = name;
  }
 
  call() {
    console.log( 'hi from '+ this.name);
  }
}
const p = new Person('hjc');
p.call();

const numbers = [1,2,3];
//spread
const newNumbers = [...numbers,4];
console.log('newNumbers: '+newNumbers);
const newPerson = {
  ...p,
  age: 26
}
console.log(newPerson)

const filter = (...args) => {
  return args.filter(el => el === 1);
}

console.log('filter : '+filter(1,2,3));

[num1,num2] = numbers;
console.log(num1,num2);

// Arrrays & Class's are copied by reference!

const person3 = {
  name: 'Max'
}

const person4 = person3;
const person5 = {
  ...person3
}
person3.name = 'Manu';

console.log(person4);
console.log(person5);

// array .map function
const doubleNumbers = numbers.map((num)=> {return num*2});
console.log('double numbers '+doubleNumbers);

meer array functions
map() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
find() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
findIndex() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
filter() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
reduce() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
concat() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
slice() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
splice() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...

react components playground:
https://codepen.io

Tags: 

React Native notes

Lifecycle
constructor(props) {
super(props);
}
render (){}

componentDidMount() {}
componentDidUpdate() {}
componentWillUnmount() {}

React with typoscript
# Make a new directory
$ mkdir react-typescript

# Change to this directory within the terminal
$ cd react-typescript

# Initialise a new npm project with defaults
$ npm init -y

# Install React dependencies
$ npm install react react-dom

# Make index.html and App.tsx in src folder
$ mkdir src
$ cd src
$ touch index.html
$ touch App.tsx

# Open the directory in your favorite editor
$ code .

then index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>React + TypeScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="main"></div>
<script src="./App.tsx"></script>
</body>
</html>

# Install Parcel to our DevDependencies
$ npm i parcel-bundler -D

# Install TypeScript
$ npm i typescript -D

# Install types for React and ReactDOM
$ npm i -D @types/react @types/react-dom

add to pack.json
"scripts": {
"dev": "parcel src/index.html"
},

create Counter.tsx

import * as React from 'react';

export default class Counter extends React.Component {
    state = {
        count: 0
    };

    increment = () => {
        this.setState({
            count: (this.state.count += 1)
        });
    };

    decrement = () => {
        this.setState({
            count: (this.state.count -= 1)
        });
    };

    render () {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.increment}>Increment</button>
                <button onClick={this.decrement}>Decrement</button>
            </div>
        );
    }
}

app.tsx

import * as React from 'react';
import { render } from 'react-dom';

import Counter from './Components/Counter';

render(<Counter />, document.getElementById('main'));

run:
$ npm run dev

shake animations

func shakeByRotateView(view:UIView){
    let shake:CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation")
    shake.duration = 0.12
    shake.repeatCount = Float.infinity
    shake.autoreverses = true
   
    shake.fromValue = NSNumber(value: 0.05*Double.pi)
    shake.toValue = NSNumber(value: -0.05*Double.pi)
    view.layer.add(shake, forKey: "lineRotation")
}

func shakeView(view:UIView){
    let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 2
    shake.autoreverses = true
   
    var from_point:CGPoint = CGPoint(x:view.center.x - 5,y: view.center.y)
    var from_value:NSValue = NSValue(cgPoint: from_point)
   
    var to_point:CGPoint = CGPoint(x:view.center.x + 5,y: view.center.y)
    var to_value:NSValue = NSValue(cgPoint: to_point)
   
    shake.fromValue = from_value
    shake.toValue = to_value
    view.layer.add(shake, forKey: "position")
}

Tags: 

Python rest_framework Docker setup

Dockerfile

FROM python:3

ENV PYTHONUNBUFFERED = 1
RUN mkdir /code
WORKDIR /code
COPY . /code/
RUN pip install -r requirements.txt

docker-compose.yml

version: '3'

services:
  web:
    build: .
    command: python src/profiles_project/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"

docker-compose run web python src/profiles_project/manage.py migrate

docker-compose up

Codable Decodable

enum PlanetState:String, CodingKey {
    case UnLocked = "unlocked"
    case Locked = "locked"
    case Completed = "completed"
    case Tutorial = "tutorial"
    case ComingSoon = "comingsoon"
}


class Planet: Codable
{
    var state:PlanetState
    var order:Int
    var planetBrev:String
    var bought:Bool
    var collectableGold:Int
   
    enum CodingKeys: String, CodingKey
    {
        case state      = "state"
        case order      = "order"
        case planetBrev = "planetBrev"
        case bought     = "bought"
        case collectableGold = "collectableGold"
    }
   
    init(state: PlanetState, order: Int, planetBrev:String, bought: Bool, collectableGold:Int = -1)
    {
        self.state = state
        self.order = order
        self.planetBrev = planetBrev
        self.bought = bought
        self.collectableGold = collectableGold
    }
   
    required init(from decoder: Decoder) throws {
       
        let values = try decoder.container(keyedBy: CodingKeys.self)
        self.state = (try PlanetState(rawValue: values.decode(String.self, forKey: CodingKeys.state)))!
        self.order = try values.decode(Int.self, forKey: CodingKeys.order)
        self.planetBrev = try values.decode(String.self, forKey: CodingKeys.planetBrev)
        self.bought = try values.decode(Bool.self, forKey: CodingKeys.bought)
        self.collectableGold = try values.decode(Int.self, forKey: CodingKeys.collectableGold)
    }
   
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try? container.encode(self.state.stringValue, forKey: CodingKeys.state)
        try? container.encode(self.order, forKey: CodingKeys.order)
        try? container.encode(self.planetBrev, forKey: CodingKeys.planetBrev)
        try? container.encode(self.bought, forKey: CodingKeys.bought)
        try? container.encode(self.collectableGold, forKey: CodingKeys.collectableGold)
    }
}

load
do {
   let planet = try decoder.decode(Planet.self, from: pData)
   HLog.info(function: #function, message: "planet \(planet.planetBrev) \(planet.collectableGold)")
   self.planets.append(planet)
} catch {
    print("error \(error)")
}

save to default for example
if let jsonData = try? encoder.encode(planet)
            {
                defaults.set(jsonData, forKey: "\(Constants.kQuarkPlanetSave)\(planet.planetBrev)")
                HLog.info(function: #function, message: "defaults did save data \(planet.planetBrev)")
                savedPlanets.append(planet.planetBrev)
            }

class Excercise: Encodable,Decodable {
    var date:Date
    var remarks:[String]
   
    init(date:Date,remarks:[String]) {
        self.date = date
        self.remarks = remarks
    }
 
}

let x = Excercise(date:Date(),remarks:["avc","def"])
let encoder = JSONEncoder()
let jsonData = try encoder.encode(x)
String(data: jsonData, encoding: .utf8)!//"{"date":531262938.28764498,"remarks":["avc","def"]}"
let decoder = JSONDecoder()
let decoded = try decoder.decode(Excercise.self, from: jsonData)
decoded.date//"Nov 1, 2017 at 10:01 PM"
decoded.remarks//["avc", "def"]
type(of: decoded)//Excercise.Type

Tags: 

UILabel outlined / stroked text

class StrokedLabel: UILabel {
   
    var strockedText: String = "" {
        willSet(newValue) {
            let strokeTextAttributes = [
                NSAttributedStringKey(rawValue: NSAttributedStringKey.strokeColor.rawValue) : UIColor.black,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor.white,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.strokeWidth.rawValue) : -4.0,
                NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.boldSystemFont(ofSize: 30)
                ] as [NSAttributedStringKey : Any]?
           
            let customizedText = NSAttributedString(string: newValue
                , attributes: strokeTextAttributes)
           
           
           
            attributedText = customizedText
        }
    }
}

Tags: 

raspi config ssh problem

ssh pi@192.168.1.27
Connection reset by 192.168.1.27 port 22
solution:

sudo rm /etc/ssh/ssh_host_* && sudo dpkg-reconfigure openssh-server

Path Finding

import GameplayKit

let graph = GKGraph()


let nodeA = GKGraphNode()
let nodeB = GKGraphNode()
let nodeC = GKGraphNode()
let nodeD = GKGraphNode()
let nodeE = GKGraphNode()


graph.addNodes([nodeA,nodeB,nodeC,nodeD,nodeE])
nodeA.addConnectionsToNodes([nodeB,nodeD], bidirectional: true)
nodeB.addConnectionsToNodes( [nodeD], bidirectional: true)
nodeC.addConnectionsToNodes( [nodeE], bidirectional: false)
nodeD.addConnectionsToNodes( [nodeC], bidirectional: false)
let path:[GKGraphNode] = graph.findPathFromNode(nodeA, toNode: nodeE)

Tags: 

Server side Swift

Kitura

mkdir serverside
cd serverside/
mkdir server
cd server
docker run -itv $(pwd):/projects --name projects -w /projects -p 8089:8089 -p 8090:8090 -p 5984:5984 twostraws/server-side-swift /bin/bash
docker start projects
docker attach projects
root@c661e0faa890:/projects# mkdir project1
root@c661e0faa890:/projects# cd project1/
root@c661e0faa890:/projects/project1# swift package init --type executable
root@c661e0faa890:/projects/project1# swift build
root@c661e0faa890:/projects/project1# .build/debug/project1
Hello, world!

change package to:
let package = Package(
name: "project1",
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 build
swift package generate-xcodeproj

docker ps - shows a list of running containers
docker ps -a shows list all projects

docker start #NAME PROJ#
docker attach #NAME#
ctrl-p ctrl-q to get back to local terminal without stopping
docker start -i #NAME#

Vapor

Use & adjust Post template.
change in fluent.json
"driver":"memory" into "driver":"sqlite"

create
sqlite.json
insert
{
"path":"pokemonDB.sqlite"
}

in config+Setup
change setupPreparations into desired Pokemon class

private func setupPreparations() throws {
        preparations.append(Post.self)
        preparations.append(Pokemon.self)
    }

in router
get("version"){
            request in
            let result = try Pokemon.database?.driver.raw("select sqlite_version();")
            return try JSON(node: result)
        }

MySql

start mysql server
docker run -p 3306:3306 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:latest

Tags: 

bitbucket push origin problem

With Bitbucket problem on the raspi :

git push -u origin master 

Counting objects: 87, done. error: pack-objects died of signal 9 fatal: The remote end hung up unexpectedly fatal: The remote end hung up unexpectedly ../html# fatal: write error: Bad file descriptor

git config pack.windowMemory 10m
git config pack.packSizeLimit 20m

Failed to push

in git: error: failed to push some refs to

  1. Insufficient permissions: You may not have the necessary permissions to push to the remote repository. Make sure you have the appropriate access rights and try again. Contact the repository owner or administrator if needed.
  2. Network or connectivity issues: There might be network problems or connectivity issues preventing the push operation. Check your internet connection and try again. If the problem persists, it could be a temporary issue with the remote server or the network infrastructure.
  3. Outdated local branch: If the remote repository has been updated since your last pull or clone, you might need to fetch and merge the changes before pushing your local changes. Use the git pull command to update your local branch and resolve any conflicts if necessary. Then attempt the push again.
  4. Remote repository changes: It's possible that someone else has made changes to the remote repository, which conflict with your local changes. In this case, you need to pull the latest changes, resolve any conflicts, and then push your changes.
  5. Git configuration issues: Verify your Git configuration settings, including your username and email address, to ensure they are correctly set up. Use the following commands to check and update if necessary:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
  1. Repository or branch restrictions: The remote repository may have certain restrictions in place, such as branch protection rules or branch permissions. Make sure you are following the guidelines and restrictions set by the repository.

combine adding CGRects in array

Adding two CGRect:

let area0 = CGRectZero //{x 0 y 0 w 0 h 0}
let area1 = CGRect(x:0,y:0,width: 2.0, height: 2.0)//{x 0 y 0 w 2 h 2}
let area2 = CGRect(x:2.0,y:2.0,width: 2.0, height: 2.0)
let area3 = CGRect(x:4.0,y:4.0,width: 2.0, height: 2.0)
let union = CGRectUnion(area1, area2)//{x 0 y 0 w 4 h 4}

in an array
var areatotal:[CGRect] = []
areatotal.append(area1)
areatotal.append(area2)
areatotal.append(area3)
areatotal.append(area0)
areatotal.reduce(CGRectZero, combine: CGRectUnion)//{x 0 y 0 w 6 h 6}

Tags: 

Nginx

apt-get update
apt-get install nginx
service nginx start

Download the init script for the relevant platform and save it to /etc/rc.d/init.d/nginx
chmod +x /etc/rc.d/init.d/nginx

directives and context

search & analytics nginx

nginx
/var/log/nginx

cat access.log | awk '{print $7}' | sort -rn | uniq -c

ips in log
cat access.log | grep xmlrpc | awk '{print $1}' | sort -n | uniq

per req uri
cat /var/log/nginx/access.log | awk '{print $11}' | sort | uniq -c | sort -n

problems with server restart
/usr/sbin/nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

sudo apachectl stop
sudo pkill -f nginx
sudo systemctl start nginx

Mysql General notes

cheat sheet MySQL

Commands
Access monitor: mysql -u [username] -p; (will prompt for password)

Show all databases: show databases;

Access database: mysql -u [username] -p [database] (will prompt for password)

Create new database: create database [database];

Select database: use [database];

Determine what database is in use: select database();

Show all tables: show tables;

Show table structure: describe [table];

List all indexes on a table: show index from [table];

Create new table with columns: CREATE TABLE [table] ([column] VARCHAR(120), [another-column] DATETIME);

Adding a column: ALTER TABLE [table] ADD COLUMN [column] VARCHAR(120);

Adding a column with an unique, auto-incrementing ID: ALTER TABLE [table] ADD COLUMN [column] int NOT NULL AUTO_INCREMENT PRIMARY KEY;

Inserting a record: INSERT INTO [table] ([column], [column]) VALUES ('[value]', [value]');

MySQL function for datetime input: NOW()

Selecting records: SELECT * FROM [table];

Explain records: EXPLAIN SELECT * FROM [table];

Selecting parts of records: SELECT [column], [another-column] FROM [table];

Counting records: SELECT COUNT([column]) FROM [table];

Counting and selecting grouped records: SELECT *, (SELECT COUNT([column]) FROM [table]) AS count FROM [table] GROUP BY [column];

Selecting specific records: SELECT * FROM [table] WHERE [column] = [value]; (Selectors: <, >, !=; combine multiple selectors with AND, OR)

Select records containing [value]: SELECT * FROM [table] WHERE [column] LIKE '%[value]%';

Select records starting with [value]: SELECT * FROM [table] WHERE [column] LIKE '[value]%';

Select records starting with val and ending with ue: SELECT * FROM [table] WHERE [column] LIKE '[val_ue]';

Select a range: SELECT * FROM [table] WHERE [column] BETWEEN [value1] and [value2];

Select with custom order and only limit: SELECT * FROM [table] WHERE [column] ORDER BY [column] ASC LIMIT [value]; (Order: DESC, ASC)

Updating records: UPDATE [table] SET [column] = '[updated-value]' WHERE [column] = [value];

Deleting records: DELETE FROM [table] WHERE [column] = [value];

Delete all records from a table (without dropping the table itself): DELETE FROM [table]; (This also resets the incrementing counter for auto generated columns like an id column.)

Delete all records in a table: truncate table [table];

Removing table columns: ALTER TABLE [table] DROP COLUMN [column];

Deleting tables: DROP TABLE [table];

Deleting databases: DROP DATABASE [database];

Custom column output names: SELECT [column] AS [custom-column] FROM [table];

Export a database dump (more info here): mysqldump -u [username] -p [database] > db_backup.sql

Use --lock-tables=false option for locked tables (more info here).

Import a database dump (more info here): mysql -u [username] -p -h localhost [database] < db_backup.sql

Logout: exit;

Aggregate functions
Select but without duplicates: SELECT distinct name, email, acception FROM owners WHERE acception = 1 AND date >= 2015-01-01 00:00:00

Calculate total number of records: SELECT SUM([column]) FROM [table];

Count total number of [column] and group by [category-column]: SELECT [category-column], SUM([column]) FROM [table] GROUP BY [category-column];

Get largest value in [column]: SELECT MAX([column]) FROM [table];

Get smallest value: SELECT MIN([column]) FROM [table];

Get average value: SELECT AVG([column]) FROM [table];

Get rounded average value and group by [category-column]: SELECT [category-column], ROUND(AVG([column]), 2) FROM [table] GROUP BY [category-column];

Multiple tables
Select from multiple tables: SELECT [table1].[column], [table1].[another-column], [table2].[column] FROM [table1], [table2];

Combine rows from different tables: SELECT * FROM [table1] INNER JOIN [table2] ON [table1].[column] = [table2].[column];

Combine rows from different tables but do not require the join condition: SELECT * FROM [table1] LEFT OUTER JOIN [table2] ON [table1].[column] = [table2].[column]; (The left table is the first table that appears in the statement.)

Rename column or table using an alias: SELECT [table1].[column] AS '[value]', [table2].[column] AS '[value]' FROM [table1], [table2];

Users functions
List all users: SELECT User,Host FROM mysql.user;

Create new user: CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Grant ALL access to user for * tables: GRANT ALL ON database.* TO 'user'@'localhost';

Find out the IP Address of the Mysql Host
SHOW VARIABLES WHERE Variable_name = 'hostname'; (source)

Sizes databases

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

index, indices, indexes
alter table book add index idx_name(name)
alter table book drop index idx_name

multiple row updates at same time
set sql_save_updates=0

check
SHOW VARIABLES LIKE 'sql_safe_updates'

renumber id column
SET @i=0;
UPDATE table_name SET column_name=(@i:=@i+1);

set @rank=0;select @rank:=@rank+1 as rank , screenname, score from gameScore order by score desc;

select groep , screenname from user where userGroup.groep < 98 order by groep;

Explain Select

explain select  count(*) from `tuinhokmetingen`.`AspNetUsers`;

Show create

show create TABLE `temperatures`;

Tags: 

remove mongo

# See if mongo is in the launch/startup list
launchctl list | grep mongo

# Remove mongodb from the launch/startup
launchctl remove homebrew.mxcl.mongodb

# Kill the mongod process just in case it's running
pkill -f mongod

# Now you can safely remove mongodb using Homebrew
brew uninstall mongodb

Tags: 

Docker

cleanup

~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2
never shrinks...

Dockerfile recipes

Java hello

FROM openjdk:14-alpine
COPY out/artifacts/testdockerhello_jar/testdockerhello.jar /usr/src/hello.jar
CMD java -cp /usr/src/hello.jar Main

Spring basic

with maven pom.

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>docker-spring-demo</finalName>
    </build>

Dockerfile
FROM openjdk:11

EXPOSE 8080

ADD target/docker-spring-demo.jar app.jar

ENTRYPOINT ["java","-jar", "app.jar"]

Mysql recipe

docker run --name mysql -e MYSQL_USER=user -e MYSQL_PASSWORD=password -e MYSQL_DATABASE=databasename -p 3306:3306 -d mysql/mysql-server

Sails

run sails from local dir in docker conatiner
docker container run -it -p 1337:1337 -v $(pwd):/server artificial/docker-sails /bin/bash

Swift

run docker app
then

docker pull swift
docker pull postgres:alpine

docker container run -d -p 3306:3306 --name mysql -e MYSQL_RANDOM_ROOT_PASSWORD=yes  mysql
docker container run --name mysql -p 3306:3306 -e MYSQL_RANDOM_ROOT_PASSWORD=yes -d mysql
docker container logs mysql
docker exec -it mysql bash -l

docker container run -d --name mysql -e MYSQL_ROOT_PASSWORD=root -p 3306 -v /Users/lappie2010/Documents/docker/mysql/:/var/lib/mysql mysql


docker container logs mysql

docker container run -d --name webserver -p 8080:80 httpd

docker container run -d --name proxy -p 80:80 nginx


docker run --cap-add sys_ptrace -it --privileged=true swift bash

Docker Mysql + Wordpress

docker container run -d \
    --name wordpress \
--link mysql:mysql\
    -p 8080:80 \
    -e WORDPRESS_DB_PASSWORD=root \
    wordpress

    docker container run -d \
        --name mysql \
        -e MYSQL_ROOT_PASSWORD=root \
        -e MYSQL_DATABASE=wordpress \
        mysql

Swift Perfect

mkdir hjh
cd hjh
swift package init --type executable
swift package generate-xcodeproj
open ./hjh.xcodeproj/

edit package.swift

import PackageDescription
let package = Package(
  name: "hjh",
  dependencies: [
    .Package(url: "https://github.com/PerfectlySoft/Perfect-
HTTPServer.git", majorVersion: 2),
    .Package(url: "https://github.com/SwiftORM/SQLite-StORM.git",
majorVersion: 1, minor: 0),
    .Package(url: "https://github.com/PerfectlySoft/Perfect-
Mustache.git", majorVersion: 2),
] )

terminal:

swift package update
swift package generate-xcodeproj

main.swift:

import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

terminal:

mkdir public
touch public/file.txt
swift package generate-xcodeproj

terminal:

mkdir public
touch public/file.txt
swift package generate-xcodeproj

let server = HTTPServer()
server.serverPort = 8080
server.documentRoot = "public"

do {
  try server.start()
} catch PerfectError.networkError(let err, let msg) {
  print("Network error thrown: \(err) \(msg)")
}

// func for fitst json response
func jsonresponsefunc(request: HTTPRequest, response: HTTPResponse) {
  do {
    try response.setBody(json: ["message": "JSON!"])
      .setHeader(.contentType, value: "application/json")
      .completed()
  } catch {
    response.setBody(string: "Error handling request: \(error)")
      .completed(status: .internalServerError)
  }
}
// routes
var routes = Routes()
routes.add(method: .get, uri: "/", handler: jsonresponsefunc)
server.addRoutes(routes)

Tags: 

Read file

file io swift 2.2

        let fileLocation = NSBundle.mainBundle().pathForResource("2311393", ofType: "xml")!
        let text : String
        do
        {
            text = try String(contentsOfFile: fileLocation)
        }
        catch
        {
            text = ""
        }

Tags: 

Pages

Subscribe to hjsnips RSS