Posts

Showing posts from 2017

Kurbenetes : Retrying. E0611 12:40:36.428003 9060 start.go:133] Error starting host: Error getting state for host: machine does not exist

Image
I face this issue running minikube on Window on my J drive. When i switch it to c drive things seems to be working fine.


webapi streaming

If you need to stream a video from webapi, you can use the following codes. The code is taken from stackvoerflow. I did not write it.

If you're using .net core, use the following code.





There are loads of sample in the internet, but i think this works well for .net 4.6.

You probably need to know that if you not sure exact size of your files, try PushStreamContent.
Otherwise, you can just use StreamContent.




HttpStatusCode Details.....

//
        // Summary:
        //     Equivalent to HTTP status 100. System.Net.HttpStatusCode.Continue indicates that
        //     the client can continue with its request.
        Continue = 100,
        //
        // Summary:
        //     Equivalent to HTTP status 101. System.Net.HttpStatusCode.SwitchingProtocols indicates
        //     that the protocol version or protocol is being changed.
        SwitchingProtocols = 101,
        //
        // Summary:
        //     Equivalent to HTTP status 200. System.Net.HttpStatusCode.OK indicates that the
        //     request succeeded and that the requested information is in the response. This
        //     is the most common status code to receive.
        OK = 200,
        //
        // Summary:
        //     Equivalent to HTTP status 201. System.Net.HttpStatusCode.Created indicates that
        //     the request resulted in a new resource created before the response was sent.
        Created = 201,
        //
       …

differences between dotnet pack vs dotnet publish

dotnet publish build and ensure your application is ready for deployment and ready for runtime - it comes with all the necessary dll, project dependencies.


dotnet pack on the other hand, ensure that you application is build as a nuget package and allows your users to pull down only this .dll. Nuget will resolves dependencies but only your dll is packaged and distributed.


my ruby rails cheat sheet

Skip actions 

skip_before_action :verify_authenticity_tokenprotect_from_forgery :except =>:create
Create an API project 

rails new my_api --api

Create a normal project 

rails new blog

Create Model 

$ bin/rails generate model Article title:string text:text

Start server 

bin/rails server

Controller 

bin/rails generate controller Welcome index

Running Migration 

rails db:migrate

Rollback Migration 

rake db:rollback STEP=1

Scaffold-DbContext update existing model if database changes.

Simple and nice answer -> use Force options as shown below :-

Scaffold-DbContext "Server=localhost;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DataModel -FORCE


Anyways if you would like to find out more about that, please jump into the following link.



Installing Ruby 2.4 without Tears on Windows

Image
First we need to

1. Download ruby installer from here,

2. Download msys2 installer and install it. It is all right if you don't. Step 3 will force you to do it. :)

3. Run ruby installer. At the end of it, installer is intelligent enough to prompt you to install MSYS2.

You basically need to go through all 3 option prompted.

1. MSYS base installation



2. MSYS2 System update




3. MSYS2 and MingGW development toolchain






Once you have done that, open up command prompt and start installing your gems, for example :-

gem install rails.



Scaffold-DbContext context not found error for .net core 2 / net core 1.1.2

I assumed you have already installed

a) Install-Package Microsoft.EntityFrameworkCore.SqlServer


b) Install-Package Microsoft.EntityFrameworkCore.Tools


c) Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

For example, my .net core app is target for 1.1, so

Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 1.1.2
Install-Package Microsoft.EntityFrameworkCore.Tools -version 1.1.1

Might need to restart your VS2017, depending on how convulated your project is. I have a simple project that i just created from scratch i don't eve need to restart. For one for the projects, i did restarted my VS2017.

You will need to get this packages correctly installed depending on what .net project (.netcore 2, .netcore 1.1)

Remember to restart your visual studio, goto Nuget Package Manager console and try running scaffold-dbcontext, for example :-

Scaffold-DbContext "Server=(localdb)\.;Database=IDS_ODS;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlSe…

docker - connecting your host to a container

Image
Phew! Spent a few hours on this and finally i was able to get it right.

Task :- Spin up a new docker container running my app and connect to it from my windows host. 

Sounds simple enuff, I think the biggest gotcha is setting your application port to "0.0.0.0" instead of "localhost", as shown in diagram below.






My app is a .net core app - of course it is, how else would u want to host it in docker. :)

Here is my docker file




And then i use the following command to spin up my docker.

docker build . -t accmicroserve

docker run -P accmicroserve (if you do it this way, you might get a random PORT from your container)

docker run -p 5000:5000 accmicroserve (here we're saying we're fixed the port to 5000).

Your docker instance already started, and ready to go.













weird things can go wrong with asp.net core configuration

Image
Been working on .net core configuration lately and take me a bit longer to wire up this up.

When you create the configuration, create a configuration that matches the entire appsettings.json file. For example,

We have a configuration called AppConfig which contains a property called BlommbergAimConfiguration.(highlighted in orange) Under this, we have some other tokens settings (highlighted in green)




Once you have this, as long as you call Configure(Configuration), any configuration will be populated accordingly.


tls1.2 support in .net core

When you trying to support tls1.2 in .net core or porting existing application from .net 4.6, these might not work :-


ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;


You need to make the change from this to WinHttpHandler.

First, you need to install nuget package.

Install-Package System.Net.Http.WinHttpHandler -Pre

Next you need to run dotnet build (somehow my VS2017 Express wasn't able to recognize this nuget package that i've ran)


Once you have done that, you should be able to write this piece of code.


Reactive extesion for .Netcore.

To get it running on your system, just try adding it into your project.

Install-Package System.Reactive -Version 3.1.1



async ValueTask gives performance improvement

Instead of using Task, might be good that add a value in what we call by calling ValueTask. It's suppose to be faster. Hopefully i can get some numbers out here.

Essentially to call it, just simply use the followings :-

async ValueTaskTestValueTask(int d){ await Task.Delay(d);return10;}

Weird case C#7 Tuple for .Net 4.6

If you're using .Net 4.6 or lower, you need to install

Install-Package"System.ValueTuple" To get this to work ....

staticvoidMain(string[] args){var x =DoSomething();Console.WriteLine(

.Net core logging info is abit out of date

I find that Microsoft .Net core logging documentation is a bit out of date for Log Level. Somehow if we set to Log level to Warning, it will not show logs on "Information level". It will show Error log level. This only if we're calling this command here in the startup.cs.

 loggerFactory.AddConsole(Configuration.GetSection("Logging"));

appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

The docs had it reversed. 
Adding a serilog logger, will logs everything and this doesn't applies. 

Elixir tuple, struct and map

Elixir Tuple

To declare a tuple, you simply declare

d = {1, "b", :c"}

And to retrieve it use elem function.

 elem(d, 0) // return 1
 elem(d, 1) // return "b"

You can use Tuple function to help out with tuple manipulation.

Elixir Map

Sometimes it can be confusing because we are declaring  map using the same operator {}.

Map are key value pair.

To declare, simple type

a = %{  a  => 1, b => 2 } // you can't do this

 a = %{"a" => 1, "b" => 2} // ok

if you're using ATOM, you can declare as follows (notice the change of parameter from => (arrow key) to ":" below) :-

 l = %{a: 1, b: 2 }

Accessing map (Non-Atom Map), you can simply, 
 a["a"] // output 1   a["b"] // output 2 
Or you can use 
Map.get(a, "a") // output 1  Map.get(a, "b") // output 2
Accessing Atom map  If your map is declare this way :    l = %{a: 1, b: 2 } 
l[:a] //output 1  Map.get(l, :a) // output 1 
Elixir stru…

Creating a simple phoenix plug

Plug is a execution component in Phoenix processing pipeline. Here we're gonna create one and hook it up to the existing pipeline. First you need the code below.





The most important thing to do here is to define

a) init which execute "call" method.

b) call method -> which has the actual functions / implementation of what you're going to do.
For this example, we're just going to write a simple output to the screen.




if  you look at line 12, we're already tied up our plug and pass in a parameter with the value "en".

If you run your "mix phoenix.server" and make a request, you should be able to see some funny output on the command prompt.











Print out the Plug connection object.

We can easily use IO.inspect to debug dump Plug conn object as shown in code below :-



defindex(conn, _params) do render conn, "index.html"
IO.inspect conn.req_headers IO.inspect conn
end

ES7 has only two features

ES7 features: Array.prototype.includes - if you declare        var a =[1,2,3];     a.includes(1); True      a.includes(1, 0); True      a.includes(1, 2)     The second parameter is fromIndex - which ask it to start seeking after certain no of position.

Exponentiation Operator ** - example 4 ** 9 = 262144

Elixir postgrex error - Could not start application postgrex: could not find application file: postgrex.app

If you get postgrex error above, please open a file called "mix.exs" and look for application and remove postgrex from your list as shown below.


# Type `mix help compile.app` for more information. defapplicationdo [mod: {HelpOn, []}, applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext, :phoenix_ecto, postgrex]] <-- div="" error="" here="">end

Using MySql with Ecto

Image
You might need to create a folder manually, priv\repo\migrations if it doesn't exist. Otherwise ecto will complain when you run "mix ecto.migrate"

Let's create some schema

mix  phoenix.gen.model User users name:string email:string bio:string number_of_pets:integer

Details of phoenix mix task can be found here.

Next run

"mix ecto.migrate"



The actual documentation uses slightly different command.








Using Elixir pipe example

To demonstrate how pipe operator is used in Elixir, we try out with the following codes.

defmodule Test do
   def exact(a) do
     a
   end

   def toInt(a) do
     Integer.parse(a)
   end

end

This basically takes 200, pass it to Test.exact (which returns anything that it get) and pass it on to Test.toInt which convert it into an integer. 

"200" |> Test.exact |> Test.toInt


Elixir demonstrate if, case and cond keyword

The following code demonstrate how we can use if, case and cond keyword.

defmodule Test do

  def bigger(a) do  
    if (a > 2) do
      :ok
    else
      :error
   end
 end

def getSize(a) do  

 case a do
    n when n in 1..20 ->  
        :small
    n when n in 21..30 ->
        :med
    n when n in 31..40->
       :big
   end
  end

def getSizeCond(a) do  

 cond do
  a > 30 ->
     :big
  a > 20 ->
     :med
  a > 10 ->
      :small
   end  
 end
end


So you can quickly run some case checking using code below :-

case Test.bigger(2) do
 :ok -> 1
 :error -> -1
end






Installing Tensorflow using Anaconda

Image
The process is pretty straight forward, just that you need to keep in mind that you need to install python 3.5 in your environment and you need Anaconda 64bit installer.

It is best that you use Conda instead of pip as the installer.



Let's kick things off with :-
conda create -n tensorflow python=3.5activate tensorflowpip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.2.1-cp35-cp35m-win_amd64.whl
If you get messages like tensorflow is not supported in this platform, please check your anaconda installer and make sure it is 64 bits.


To test out, fire up your python command prompt and

import tensorflow as tf
Sneaking in Theano

Let's sneak in Theano into our Anaconda project

conda install theano pygpu To test out, fire up your python command prompt and  from theanoimport* Sneaking in KerasTo install Keras, you need to use the following command :-conda install -c conda-forge keras

Working example for Elixir EchoServer

The Elixir's sample code for Echo server doesn't exactly work for me. So i created my own EchoServer with some modification here and there. This supports multiple client request.


Here's the sample code


defmoduleProcessboydo requireLogger
@doc """ Starts accepting connections on the given `port`. Processboy.Supervisor.start(nil, nil) """ defaccept(port) do {:ok, socket} = :gen_tcp.listen(port, [:binary, packet: :line, active: false, reuseaddr: true]) Logger.info "Accepting connections on port #{port}" loop_acceptor(socket) end
definit() do importSupervisor.Spec
children = [ supervisor(Task.Supervisor, [[name: Processboy, restart: :transient]]) ]
#opts = [strategy: :one_for_one, name: Processboy] {:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
end
defploop_acceptor(socket) do {:ok, client} = :gen_tcp.accept(socket) Logger.info "getting connections from client" {:ok, pid} = Task.Supervisor.start_child(Processboy…