Cypress tests

Long method

func async(_ runner: @escaping @autoclosure () ->())
{
    DispatchQueue.global(qos: .default).async {
        runner()
    }
}

func longMethod() {
    for _ in 1...2 {
        sleep(5)
    }
    print("run like a boss")
}
async(longMethod())

Tags: 

Random in swift 4.2

let double = Double.random(in: -1.2...4.5)
let integer = Int.random(in: .min ... .max)
let unsignedInteger = UInt.random(in: 4...9)
let bool = Bool.random() // false/true

struct SeededRandomNumberGenerator: RandomNumberGenerator {
    init(seed: Int) {
        srand48(seed)
    }
   
    func next() -> UInt64 {
        return UInt64(drand48() * Double(UInt64.max))
    }
}

var seededGenerator = SeededRandomNumberGenerator(seed: 5)
var random = Int.random(in: -5...5, using: &seededGenerator) // 2
random = Int.random(in: -5...5, using: &seededGenerator) // 1
random = Int.random(in: -5...5, using: &seededGenerator) //-3
random = Int.random(in: -5...5, using: &seededGenerator) //-2

Readfile Rxswift

let disposebag = DisposeBag()
 
  enum FileReadError: Error {
    case fileNotFound, unreadable, encodingFailed
  }
 
  func loadText(from filename: String) -> Single<String> {
    return Single.create {
      single in
      let disposable = Disposables.create()
     
      guard let path = Bundle.main.path(forResource: filename, ofType: "txt") else {
        single(.error(FileReadError.fileNotFound))
        return disposable
      }
      guard let data =  FileManager.default.contents(atPath: path) else {
        single(.error(FileReadError.unreadable))
        return disposable
      }
      guard let contents = String(data: data, encoding: .utf8) else {
        single(.error(FileReadError.encodingFailed))
        return disposable
      }
      single(.success(contents))
     
      return disposable
    }
  }
  loadText(from: "filename")
    .subscribe{
      switch $0 {
      case .success(let string):
        print(string)
      case .error(let descript):
        print(descript)
     
      }
  }
    .disposed(by: disposebag)

Tags: 

Dotnet core links

Dotnet Identity & mySQL

working identity with pomelo in dotnet 2.1

Nice article dotnet core 2 with link sql creation file

identity proj

implementing Identity storage provider

UPDATE mysql.user SET Password=PASSWORD('root') WHERE User='root'; 

or

 ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
docker exec -i mysql-server mysql -uroot -p"root" mysql < orkestpit.sql

with homebew:

brew tap homebrew/services
brew services list
brew install mysql@5.7
brew services start mysql
mysql_secure_installation

echo 'export PATH="/usr/local/opt/mysql@5.7/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
mysql -V

Use of React Redux Template in dotnet core

hjh /D/t/Dotnet> mkdir reactnativedotnettest
hjh /D/t/Dotnet> cd reactnativedotnettest/
hjh /D/t/D/reactnativedotnettest> dotnet new reactredux

Welcome to .NET Core!
---------------------
Learn more about .NET Core: https://aka.ms/dotnet-docs
Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs

Telemetry
---------
The .NET Core tools collect usage data in order to help us improve your experience. The data is anonymous and doesn't include command-line arguments. The data is collected by Microsoft and shared with the community. You can opt-out of telemetry by setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to '1' or 'true' using your favorite shell.

Read more about .NET Core CLI Tools telemetry: https://aka.ms/dotnet-cli-telemetry

ASP.NET Core
------------
Successfully installed the ASP.NET Core HTTPS Development Certificate.
To trust the certificate run 'dotnet dev-certs https --trust' (Windows and macOS only). For establishing trust on other platforms refer to the platform specific documentation.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
Getting ready...
The template "ASP.NET Core with React.js and Redux" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /Development/tmp/Dotnet/reactnativedotnettest/reactnativedotnettest.csproj...
  Restoring packages for /Development/tmp/Dotnet/reactnativedotnettest/reactnativedotnettest.csproj...
  Generating MSBuild file /Development/tmp/Dotnet/reactnativedotnettest/obj/reactnativedotnettest.csproj.nuget.g.props.
  Generating MSBuild file /Development/tmp/Dotnet/reactnativedotnettest/obj/reactnativedotnettest.csproj.nuget.g.targets.
  Restore completed in 7.45 sec for /Development/tmp/Dotnet/reactnativedotnettest/reactnativedotnettest.csproj.

Restore succeeded.

hjh /D/t/D/reactnativedotnettest> ll
total 48
drwxr-xr-x  13 hjhubeek  wheel   442B Nov  8 08:14 .
drwxr-xr-x   4 hjhubeek  wheel   136B Nov  8 08:13 ..
-rw-r--r--   1 hjhubeek  wheel   3.7K Nov  8 08:14 .gitignore
drwxr-xr-x   8 hjhubeek  wheel   272B Nov  8 08:14 ClientApp
drwxr-xr-x   3 hjhubeek  wheel   102B Nov  8 08:14 Controllers
drwxr-xr-x   5 hjhubeek  wheel   170B Nov  8 08:14 Pages
-rw-r--r--   1 hjhubeek  wheel   640B Nov  8 08:14 Program.cs
drwxr-xr-x   3 hjhubeek  wheel   102B Nov  8 08:14 Properties
-rw-r--r--   1 hjhubeek  wheel   2.1K Nov  8 08:14 Startup.cs
-rw-r--r--   1 hjhubeek  wheel   146B Nov  8 08:14 appsettings.Development.json
-rw-r--r--   1 hjhubeek  wheel   105B Nov  8 08:14 appsettings.json
drwxr-xr-x   6 hjhubeek  wheel   204B Nov  8 08:14 obj
-rw-r--r--   1 hjhubeek  wheel   2.3K Nov  8 08:14 reactnativedotnettest.csproj
hjh /D/t/D/reactnativedotnettest> cd ClientApp/
hjh /D/t/D/r/ClientApp> npm install

> uglifyjs-webpack-plugin@0.4.6 postinstall /Development/tmp/Dotnet/reactnativedotnettest/ClientApp/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js

added 1183 packages from 756 contributors and audited 10649 packages in 24.888s
found 341 vulnerabilities (313 low, 15 moderate, 12 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
hjh /D/t/D/r/ClientApp> dotnet restore
MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.
hjh /D/t/D/r/ClientApp> ll  //// Oops wrong folder... better go one folder up
total 944
drwxr-xr-x    9 hjhubeek  wheel   306B Nov  8 08:15 .
drwxr-xr-x   13 hjhubeek  wheel   442B Nov  8 08:14 ..
-rw-r--r--    1 hjhubeek  wheel   306B Nov  8 08:14 .gitignore
-rw-r--r--    1 hjhubeek  wheel   109K Nov  8 08:14 README.md
drwxr-xr-x  918 hjhubeek  wheel    30K Nov  8 08:15 node_modules
-rw-r--r--    1 hjhubeek  wheel   350K Nov  8 08:15 package-lock.json
-rw-r--r--    1 hjhubeek  wheel   687B Nov  8 08:14 package.json
drwxr-xr-x    5 hjhubeek  wheel   170B Nov  8 08:14 public
drwxr-xr-x    9 hjhubeek  wheel   306B Nov  8 08:14 src
hjh /D/t/D/r/ClientApp> cd ..
hjh /D/t/D/reactnativedotnettest> dotnet restore
  Restore completed in 51.8 ms for /Development/tmp/Dotnet/reactnativedotnettest/reactnativedotnettest.csproj.
hjh /D/t/D/reactnativedotnettest> dotnet run
Using launch settings from /Development/tmp/Dotnet/reactnativedotnettest/Properties/launchSettings.json...
: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/Users/hjhubeek/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.AspNetCore.SpaServices[0]
      Starting create-react-app server on port 49656...
Hosting environment: Development
Content root path: /Development/tmp/Dotnet/reactnativedotnettest
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.SpaServices[0]
      > reactnativedotnettest@0.1.0 start /Development/tmp/Dotnet/reactnativedotnettest/ClientApp
      > rimraf ./build && react-scripts start
     
      Starting the development server...
     
info: Microsoft.AspNetCore.SpaServices[0]
     
      Compiled successfully!
     
info: Microsoft.AspNetCore.SpaServices[0]
      You can now view reactnativedotnettest in the browser.
     
info: Microsoft.AspNetCore.SpaServices[0]
        Local:            http://localhost:49656/
        On Your Network:  http://xx.xx.xx.xx:49656/
     

Side Note

Duplicate files are shown in visual studio...

prevent update to mojave

in /Library/Bundles/
then move it to doc folder and turn off

sudo mv /Library/Bundles/OSXNotification.bundle ~/Documents/ && softwareupdate --ignore macOSInstallerNotification_GM

turn back
move it back to /Library/Bundles/

softwareupdate --reset-ignored

Tags: 

View Userdefault

po UserDefaults.standard.dictionaryRepresentation()

Tags: 

Privacy descriptions in info.plist

<key>NSCameraUsageDescription</key>
    <string>$(PRODUCT_NAME) camera use.</string>
    <key>NSContactsUsageDescription</key>
    <string>$(PRODUCT_NAME) contacts use.</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>$(PRODUCT_NAME) photos and video use.</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>$(PRODUCT_NAME) bluetooth use.</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>$(PRODUCT_NAME) microphone use.</string>
    <key>NSMotionUsageDescription</key>
    <string>$(PRODUCT_NAME) motion use.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>$(PRODUCT_NAME) location use.</string>
    <key>NSLocationUsageDescription</key>
    <string>$(PRODUCT_NAME) location use.</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>$(PRODUCT_NAME) location use.</string>
    <key>NSRemindersUsageDescription</key>
    <string>$(PRODUCT_NAME) reminders use.</string>
    <key>NSSiriUsageDescription</key>
    <string>$(PRODUCT_NAME) siri use.</string>
    <key>NSVideoSubscriberAccountUsageDescription</key>
    <string>$(PRODUCT_NAME) video use.</string>
    <key>NSSpeechRecognitionUsageDescription</key>
    <string>$(PRODUCT_NAME) speech recognition use.</string>
    <key>NSCalendarsUsageDescription</key>
    <string>$(PRODUCT_NAME) user your calendar.</string>

Tags: 

Upload with form

model

public class ProductEditModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Rate { get; set; }
        public int Rating { get; set; }
    }

controller
[HttpGet]
        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public IActionResult Create(ProductEditModel model)
        {
            string message = "";

            if (ModelState.IsValid)
            {
                message = "product " + model.Name + " Rate " + model.Rate.ToString() + " With Rating " + model.Rating.ToString() + " created successfully";
                ProductEditModel p = new ProductEditModel();
                p.Name = model.Name;
                p.Rate = model.Rate;
                p.Rating = model.Rating;
                ViewData["product"] = p;
                ViewData["isSuccess"] = true;

            }
            else
            {
                ViewData["isError"] = true;
                message = "Failed to create the product. Please try again";
            }
            ViewData["Message"] = message;
            return View();
        }

razor
@{
    ViewData["Title"] = "Bla Create";
    var product = ViewData["Product"] as ProductEditModel;
    var isSuccess = ViewData["isSuccess"] as Boolean?;
    var isError = ViewData["isError"] as Boolean?;
}

<h2>Create</h2>
@if (@isSuccess == true)
{

    <div class="alert alert-success" role="alert">
        @ViewData["Message"]
    </div>
}
@if (@isError == true)
{

    <div class="alert alert-danger" role="alert">
        @ViewData["Message"]
    </div>
}

@if (@product != null)
{
    <p>
        <a asp-area="" asp-controller="Bla" asp-action="Create">Create</a>
        <a asp-area="" asp-controller="Bla" asp-action="Index">Bla</a>
    </p>

}
else
{
    <form action="/bla/create" method="post">
        <label for="Name">Name</label>
        <input type="text" name="Name" />

        <label for="Rate">Rate</label>
        <input type="text" name="Rate" />
        <label for="Rating">Rating</label>
        <input type="text" name="Rating" />
        <input type="submit" name="submit" />
    </form>
}

html linking

<a asp-area="" asp-controller="Bla" asp-action="Index">Bla</a>

Routing mvc dotnet core

In startup.cs

app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }
    );

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});

with attributes
[Route("[controller]")]
public class AnalyticsController : Controller
{
    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}

rest
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] {"hello", "world!"};
    }

    // POST api/values
    [HttpPost]
    public void PostCreate([FromBody] string value)
    {
    }
}

constraints
[HttpGet("{id:int}")]
public string GetById(int id)
{
    return "item " + id;
}

.net core connect local mysql

choose mysql
local with mamp or docker
---
install
nuget
Pomelo.EntityFrameworkCore.MySql
---
in appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=dotnetmysqltest;uid=username;password=password",
  }

setup entities
recipe.class

using System;
using System.Collections.Generic;

namespace testlocalmysql.Entities
{
    public class Recipe
    {
      
        public int RecipeId { get; set; }
        public string Name { get; set; }
       // public TimeSpan TimeToCook { get; set; } // gave error time(6) ???
// works as double
        public double TimeToCook { get; set; }
        public bool IsDeleted { get; set; }
        public string Method { get; set; }

        public ICollection<Ingredient> Ingredients { get; set; }
    }
}

ingredient.class
using System;
namespace testlocalmysql.Entities
{
    public class Ingredient
    {
        public int IngredientId { get; set; }
        public int RecipeId { get; set; }
        public string Name { get; set; }
        public decimal Quantity { get; set; }
        public string Unit { get; set; }
    }
}

register dbcontext

using System;
using Microsoft.EntityFrameworkCore;
using testlocalmysql.Entities;

namespace testlocalmysql.Db
{
    public class AppDbContext: DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
       
        }
           
        public DbSet<Recipe> Recipes { get; set; }

    }
}

add to startup.cs
            services.AddDbContext<AppDbContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

use ef
test if works

dotnet ef --help

apply first migration
dotnet ef migrations add InitialSchema

migration folder is created with 3 new files
finish it with
dotnet ef database update

versions & beyond compare

/Users/hjhubeek/Library/Application Support/Versions/Compare Scripts

on run argv
set original_path to (item 1 of argv)
set modified_path to (item 3 of argv)
do shell script "/usr/local/bin/bcomp \"" & original_path & "\" \"" & modified_path & "\""
end run

in contents/resources of the Versions.app

in compareTools.plist
add to array of applications

<dict>
<key>Name</key>
<string>Beyond Compare</string>
<key>Type</key>
<string>ApplicationBinary</string>
<key>Path</key>
<string>BCompare.sh</string>
<key>Application</key>
<string>Beyond Compare</string>
</dict>

create file Compare.sh
#!/bin/bash

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

FILEMERGE=`/usr/local/bin/bcomp`
if [ ! -e "$FILEMERGE" ]; then
FILEMERGE=/usr/local/bin/bcomp
fi

if [ ! -e "$FILEMERGE" ]; then
FILEMERGE=/usr/local/bin/bcomp
fi

if [ ! -e "$FILEMERGE" ]; then
echo "The FileMerge tool opendiff could not be located. Please install Xcode Tools from the Apple Developer website." >&2
exit 1
fi

if [ -n "$3" ]; then
"$FILEMERGE" "$1" "$2" -merge "$3"
else
"$FILEMERGE" "$1" "$2"
fi

# on run argv
#   set original_path to (item 1 of argv)
#   set modified_path to (item 3 of argv)
#   do shell script "/usr/local/bin/bcomp "" & original_path & "" "" & modified_path & """
# end run

avoid errors
#!/bin/sh
IFS=
bcompare "$6" "$7" -title1="$3" -title2="$5" -readonly
case $? in
'0','1','2')
exit 0
;;
'11','13','14')
exit 1
;;
'12')
echo "Important error???"
exit $?
;;
'*')
exit $?
;;
esac

Tags: 

playground network request

do not forget:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

    func getAll(completion: @escaping (GetResourcesRequest<ResourceType>)->Void)
    {
        let dataTask = URLSession.shared.dataTask(with: resourceURL) {

            data , _, _ in
            //print("datatask \(data) b \(b) c \(c)")
            guard let jsonData = data else {
                completion(.failure)
                return
            }
            do {
                let resources = try JSONDecoder().decode([ResourceType].self, from: jsonData)
                completion(.success(resources ))
            }
            catch {
                completion(.failure)
            }
        }
        dataTask.resume()
    }

Tags: 

++-)

extension Int {
  static postfix func ++ (lhs: inout Int){
    return lhs += 1
  }
}

Tags: 

Mute log output

scheme arguments, Environment variables

OS_ACTIVITY_MODE disable
-FIRDebugDisabled

Tags: 

UIImage from a UIView

extension UIImage {
    // UIImage extension that creates a UIImage from a UIView
    convenience init (view:UIView) {
        UIGraphicsBeginImageContext(view.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: image!.cgImage!)
    }

}

Tags: 

return to looser

sudo defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText "Please return ....."

texts small improvements app store translations

en
minor improvements.
da
Mindre forbedringer.
nl
Kleine verbeteringen.
fr
Améliorations mineures.
de
Kleinere Verbesserungen.
it
Miglioramenti minori.
es
Pequeñas mejoras.
se
Små förbättringar.

xcode environment variables

if ProcessInfo.processInfo.environment["TESTING"] == "1"
{
    Constants.requestTimeoutInterval = 5
}

Tags: 

Random Color with seed

extension UIColor
{
    func randomColor(seed: String) -> UIColor
    {
       
        var total: Int = 0
        for u in seed.unicodeScalars {
            total += Int(UInt32(u))
        }
       
        srand48(total * 200)
        let r = CGFloat(drand48())
        srand48(total)
        let g = CGFloat(drand48())
        srand48(total / 200)
        let b = CGFloat(drand48())
       
        return UIColor(red: r, green: g, blue: b, alpha: 1)
    }
}

let str = "abcd"
let a = UIColor().randomColor(seed: str)
is the same with
let b = UIColor().randomColor(seed: str)
is the same with
let c = UIColor().randomColor(seed: str)
etc etc

Tags: 

Dispatch async

DispatchQueue.global(qos: .background).async {
    // Background Thread
    DispatchQueue.main.async {
        // Run UI Updates or call completion block
    }
}

Main and Background Queues

let main = DispatchQueue.main
let background = DispatchQueue.global()
let helper = DispatchQueue(label: "another_thread")
Working with async and sync threads!

background.async { //async tasks here }
background.sync { //sync tasks here }

Tags: 

NSAttributedString

One liner swift 4:

label.attributedText = NSAttributedString(string: "Text", attributes:
    [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

Tags: 

Wifi qr code format

Wi-Fi QR Code Format

WIFI:T:WPA;S:mynetwork;P:mypasscode;;

    WPA—the authentication type
    mynetwork — the network SSID
    mypasscode — the password
    ⚠️ Hidden SSIDs are not supported.

Tags: 

Remove Android Studio

rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/.AndroidStudio*
rm -Rf ~/.gradle
rm -Rf ~/.android
rm -Rf ~/Library/Android*

Device Enrollment notification

move

/System/Library/LaunchAgents/com.apple.ManagedClientAgent.enrollagent.plist
/System/Library/LaunchDaemons/com.apple.ManagedClient.enroll.plist

to
/Library/LaunchAgentsDisabled and /Library/LaunchDaemonsDisabled

Tags: 

Objects Without xml

in activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);


        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        float height = displayMetrics.heightPixels;
        float width = displayMetrics.widthPixels;

        RelativeLayout myLayout = new RelativeLayout(this);
        myLayout.setBackgroundColor(Color.BLUE);

        Button myButton = new Button(this);
        myButton.setText("Press me");
        myButton.setBackgroundColor(Color.YELLOW);
        float w = (width*(float)0.3);
        myButton.setLayoutParams(new RelativeLayout.LayoutParams((int)w, (int)w));
        myButton.setX(width*(float)0.1);
        myButton.setY(width*(float)0.1);

        myLayout.addView(myButton);
        setContentView(myLayout);
    }

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: 

Pages

Subscribe to hjsnips RSS