Vue basics stuff

by Admin 30. October 2020 02:45

install vue Cli > npm install -g @vue/cli

> vue create <prjName>

> vue ui

> vue add storybook (or from the vue UI)

    storybook.js.org

prj > npm run storybook:serve opens on port 6006

 

prj > npm run storybook:build

prj >cd storybook-static/

prj >ls

prj > http-server -p 4005

prj >

Tags:

React UseState hook

by Admin 30. January 2020 11:03
function App() {
  const [ textValue, setValue ] = useState('');
  return (
    <div className='App'>
      Hello
      <input
        type='textbox'
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
      {textValue}
    </div>
  );
}

export default App;

Tags:

useReducer Hook Sample

by Admin 27. January 2020 10:27

Store.tsx

import React from "react";

interface IState {
episodes: [];
favorites: [];
}

const initialState: IState = {
episodes: [],
favorites: []
};
export const Store = React.createContext<IState>(initialState);

function reducer() {
//todo
}

export function StoreProvider(props: any) {
return <Store.Providervalue={initialState}>{props.children}</Store.Provider>;
}

App.tsx

import React from "react";
import "./styles.css";

function App(): JSX.Element {
const reducer = (state, action) => {
switch (action) {
case "Add":
return state + 1;
case "Sub":
return state - 1;
case "Res":
return (state = 0);
default:
return state;
}
};
//similar to useState
//const [value, setValue] = React.useState('')
const [count, dispatch] = React.useReducer(reducer, 0);

return (
<>
<div>{count}</div>
<button onClick={() =>dispatch("Add")}>+</button>
<button onClick={() =>dispatch("Sub")}>-</button>
<button onClick={() =>dispatch("Res")}>Reset</button>
</>
);
}

export default App;

 

Index.tsx

import React from "react";
import ReactDOM from "react-dom";
import { StoreProvider } from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StoreProvider>
<App/>
</StoreProvider>,
rootElement
);

 

Store.tsx

import React from 'react'

interface IState{

episodes : [];

favorites : [];

};

const initialState : IState => {

episodes : [],

favorites : []

};

 

export const Store = React.createContext<IState>(initialState);

 

export function StoreProvider(props: any)

{

return <Store.Provider value = {initialState}>{props.children}</Store.Provider>

}

App.tsx

import React from 'react';

 function App()

{

 //Like useState

 const [count, dispatch] = React.useReducer(reducer, 0);

const reducer = (state, action) =>

{

 switch(action)

 {

   case 'Add' : return state+1;

   case 'Sub' : return state-1;

   case 'Res' : return state=0;

   default: return state;

 }

}

 

return (

<div>

{count}

<button onClick = { ()=> dispatch('Add') }>+</button>

<button onClick = { ()=> dispatch('Sub')}>-</button>

<button onClick = { ()=> dispatch('Res')}>Res</button>

</div>

);

}

export default App;

 

index.tsx

import React from 'react'

import ReactDom fom 'react-dom'

import Store from '/Store'

import App from '/App'

 

const rootElement = document.getElementById('root');

ReactDom.render

(<StoreProvider>

<App />

</StoreProvider>,

rootElement);

Tags:

Using Store & createContext

by Admin 27. January 2020 09:58

store.tsx

import React from "react";

const initialState = {};
export const Store = React.createContext(initialState);

function reducer() {
//todo
}

export function StoreProvider(props: any) {
return <Store.Providervalue="test">{props.children}</Store.Provider>;
}

index.tsx

import React from "react";
import ReactDOM from "react-dom";
import { StoreProvider } from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StoreProvider>
<App/>
</StoreProvider>,
rootElement
);

 

App.tsx

import React, { Fragment } from "react";
import "./styles.css";
import { Store } from "./store";
//const { Provider, Consumer } = React.createContext();

function App(): JSX.Element {
const store = React.createContext(Store);

return (
<Fragment>
{console.log(store)}
<h1>Ricky And Venkat</h1>
<p>Pick your episode</p>
</Fragment>
);
}

export default App;

 

 

Tags:

React CreateContext Hook in action

by Admin 2. January 2020 05:56

Index.tsx

import React from 'React'

const State = React.CreateContext

export function Parent(props ){

const obj = { text : 'sample text here'};

return <Store.Provider value = {obj}>{props.children}</Store.Provider>

}

export function Child(){

const hook = React.useContext(State);

return <div>{hook.text}</div>

}

 

App.tsx

import {Parent, Child} from './index'

now the app will be rendered as child from parent as below

<ReactDom.Render><Parent><Child /></Parent></ReactDom.Render>

 

Tags:

Azure function validate request with Fluent validation & Ignore null handling

by Admin 11. November 2019 06:10
 
[FunctionName(nameof(Potal))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "v1/potal")]
          HttpRequest request)
        {
            var jsonSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };
            var validator = new PotalRequestValidator();
            var json = await request.ReadAsStringAsync();
            var potalRequest = JsonConvert.DeserializeObject<PotalRequest>(json, jsonSettings);

            var validationResult = validator.Validate(potalRequest);

            if (!validationResult.IsValid)
            {
                return new BadRequestObjectResult(validationResult.Errors.Select(e => new
                {
                    Field = e.PropertyName,
                    Error = e.ErrorMessage
                }));
            }

            return await RunAsync(request);
        }
 

Tags:

Typescript Sort with casing and null handling of properties

by Admin 12. September 2019 00:24

 

SortedChildCustomers = childCustomers.filter(x => x.customerName != null && x.customerID !=null).sort((a, b) => {

{

return (a.customerName.toLowerCase().localeCompare(b.customerName.toLowerCase()));

}

})

customerName  & customerID are nullable properties in the childCustomer class

Tags:

Javascript stuff

by Admin 20. June 2018 01:21

Javascript

What is the Javascript threading model - what are the priorities?

JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread.

JavaScript is single-threaded in the same context, but browser Web APIs are not. 

Also we have possibility of simulating parallelism by using setTimeout function or, with some limitations, 

by the use of the real parallelism provided by WebWorkers.

Event loop

Initial code execution ends once the page is loaded and the initial JavaScript code has run, all event handlers are attached, all AJAX requests are sent and our observables are observing. Why then shouldn’t we just handle all the events we are subscribed to in old-fashioned parallel way? The reason is that we don’t want to change the DOM in parallel: this is because the DOM tree is not thread-safe and it would be a mess if we tried to do it. Because of this limitation, all our JavaScript code should be executed in single thread, while at the same time ensuring that it handles all the events and doesn’t lose any callback. For these reasons we come to the Event loop.

The event loop can be imagined as the following process flow:

ProcessFlow

As described in the picture, the main parts of JavaScript Event loop are:

  • The Call stack, which is a usual call stack that contains all called functions.
  • The Event handlers queue, a queue of event handlers that are waiting to be executed.
  • The Event loop, which is a process that checks whether events handlers queue is not empty and if it is – calls top event handler and removes it from queue.
  • The JavaScript Web APIs: those APIs that are provided by the browser that are responsible for filling the Event handlers queue, providing many features such as the ability to make an AJAX request

  

Does the javascript event loop affect a user typing some text in a textbox.

Event handlers make it possible to detect and react to events happening in our web page. The addEventListener method is used to register such a handler.

Each event has a type ("keydown", "focus", and so on) that identifies it. Most events are called on a specific DOM element and then propagate to that element’s ancestors, allowing handlers associated with those elements to handle them.

When an event handler is called, it is passed an event object with additional information about the event. This object also has methods that allow us to stop further propagation (stopPropagation) and prevent the browser’s default handling of the event (preventDefault).

Pressing a key fires "keydown" and "keyup" events. Pressing a mouse button fires "mousedown", "mouseup", and "click" events. Moving the mouse fires "mousemove" events. Touchscreen interaction will result in "touchstart", "touchmove", and "touchend" events.

Scrolling can be detected with the "scroll" event, and focus changes can be detected with the "focus" and "blur" events. When the document finishes loading, a "load" event fires on the window.

 

 What programming paradigm can you do using javascript?

JavaScript is a multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.

Prototypal Inheritance (objects without classes, and prototype delegation, aka OLOO — Objects Linking to Other Objects), and

 Functional Programming (enabled by lambdas with closure)

 

What is map, reduce and filter (for arrays)

One of the key foundations of functional programming is its use of lists and list operations. In Javascript we have map, filter and reduce, all functions that given an initial list (array of things), transform it into something else, while keeping that same original list intact.

.map()

Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.

// What you have
var officers = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

// What you need
[20, 24, 56, 88]

There are multiple ways to achieve this. You might want to do it by creating an empty array, then using .forEach().for(...of), or a simple .for() to meet your goal.

Let’s compare!

Using .forEach():

var officersIds = [];

officers.forEach(function (officer) {
  officersIds.push(officer.id);
});

Notice how you have to create an empty array beforehand? Let’s see what it looks like when using .map():

var officersIds = officers.map(function (officer) {
  return officer.id
});

We can even be more concise with arrow functions (requires ES6 support, Babel or TypeScript)

const officersIds = officers.map(officer => officer.id);

So how does .map() work? Basically is takes 2 arguments, a callback and an optional context (will be considered as this in the callback) which I did not use in the previous example. The callback runs for each value in the array and returns each new value in the resulting array.

Keep in mind that the resulting array will always be the same length as the original array.

.reduce()

Just like .map().reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.

The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce().

Time for an example! Say you have an array with these pilots and their respective years of experience:

var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];

We need to know the total years of experience of all of them. With .reduce(), it’s pretty straightforward:

var totalYears = pilots.reduce(function (accumulator, pilot) {
  return accumulator + pilot.years;
}, 0);

Notice that I’ve set the starting value as 0. I could have also used an existing variable if necessary. After running the callback for each element of the array, reduce will return the final value of our accumulator (in our case: 82).

Let’s see how this can be shortened with ES6’s arrow functions:

const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);

Now let’s say I want to find which pilot is the most experienced one. For that, I can use reduce as well:

var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});

I named my accumulator oldest. My callback compares the accumulator to each pilot. If a pilot has more years of experience than oldest, then that pilot becomes the new oldest so that’s the one I return.

As you can see, using .reduce() is an easy way to generate a single value or object from an array.

.filter()

What if you have an array, but only want some of the elements in it? That’s where .filter() comes in!

Here’s our data:

var pilots = [
  {
    id: 2,
    name: "Wedge Antilles",
    faction: "Rebels",
  },
  {
    id: 8,
    name: "Ciena Ree",
    faction: "Empire",
  },
  {
    id: 40,
    name: "Iden Versio",
    faction: "Empire",
  },
  {
    id: 66,
    name: "Thane Kyrell",
    faction: "Rebels",
  }
];

Say we want two arrays now: one for rebel pilots, the other one for imperials. With .filter() it couldn’t be easier!

var rebels = pilots.filter(function (pilot) {
  return pilot.faction === "Rebels";
});

var empire = pilots.filter(function (pilot) {
  return pilot.faction === "Empire";
});

That’s it! And it’s even shorter with arrow functions:

const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
const empire = pilots.filter(pilot => pilot.faction === "Empire");

Basically, if the callback function returns true, the current element will be in the resulting array. If it returns false, it won’t be.

 

 

 

React lifecycle

React component communication

React component lifecycle

C#

What is the difference between a thread and a task

Exceptions in tasks, what happens.

In async and await what does configureawait do.

What memory types are available in C#

How are variables assigned in memory.

What is the Order of magnitude of indexing a dictionary?

Typescript

What is a type assertion

What are the available types of typescript

Architecture:

What are the advantages of a monolith software architecture as opposed microservices

communication of microservices

messaging architecture

Others

Nodejs basics

NoSQL

Messaging

Tags:

React Setup and start

by Admin 15. January 2018 03:11

1. install node 

npm install @latest -g (if this does not work go and download and install from here https://nodejs.org/en/)

2.  install react dependencies 

npm i -g create-react-app

3. Create first React App

create-react-app <your-react-app-name> 

Alternatively with npx  as below

npx create-react-app my-app

cd my-app

npm start

 

Note: JSX is known as  Javascript Xml

Babel is mordern javascript compiler which converts code to which browsers can understand

You can try out at babeljs.io

install bootstrap: npm i bootstrap

 multicursor editor: ctrl + d

 

 

Tags:

Typescript enum usage

by Admin 2. January 2018 01:36
enum Answer {
    Accepted = 1, 
    Rejected = 2, 
    NotFound = 3 
}

type LogLevelStrings = keyof typeof Answer;

let foo = () : Answer  => {
const prev : LogLevelStrings = "Accepted"; return Choose[prev]; } console.log('running'); console.log(`foo:${foo()}`);

Tags:

The launch of the uk replica watches new timepiece series undoubtedly symbolizes the replica watches history of the brand, and the classic hublot replica watches design explains the mission of the replica watches uk brand's precision watchmaking.

TextBox

Tag cloud

    RecentPosts