15 Aralık 2021 Çarşamba

DataTables

Giriş
Şu satırı dahil ederiz
<!-- DataTables.net -->
<script
src="resources/lib/dataTables-1.10.4/js/jquery.dataTables.min.js"
type="text/javascript"></script>
<script src="resources/lib/dataTables-1.10.4/js/dataTables.bootstrap.js"
type="text/javascript"></script>
<!-- TableTools - DataTables extension -->
<script
src="resources/lib/dataTables-1.10.4/extensions/TableTools-2.2.3/js/dataTables.tableTools.min.js"
type="text/javascript"></script>
Css için bir örnek burada

columns Alanı
Örnek
Şöyle yaparız
$('#weatherTable').DataTable({
  data: JSON.parse(res),
  columns: [
    { data: 'cityId' },
    { data: 'cityName' },
    { data: 'temp' },
    { data: 'tempMin' },
    { data: 'tempMax' },
    { data: 'pressure' },
    { data: 'humidity' }
  ],
  "pageLength": 5
});
ajaxSource Alanı
Örnek
index.hml şöyle olsun
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>...</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script src="/js/datatable.js"></script> </head> <body> <h1>Employees Table</h1> <table id="employeesTable" class="display"> <!-- Header Table --> <thead> <tr> <th>Id</th> <th>Name</th> <th>Last Name</th> <th>Email</th> <th>Phone</th> <th>Active</th> </tr> </thead> <!-- Footer Table --> <tfoot> <tr> <th>Id</th> <th>Name</th> <th>Last Name</th> <th>Email</th> <th>Phone</th> <th>Active</th> </tr> </tfoot> </table> </body> </html>
database.js şöyle olsun. Verinin alanları ve sütunlar eşleştirilir
$(document).ready( function () {
  var table = $('#employeesTable').DataTable({
    "sAjaxSource": "/employees",
    "sAjaxDataProp": "",
    "order": [[ 0, "asc" ]],
    "aoColumns": [
      { "mData": "id"},
      { "mData": "name" },
      { "mData": "lastName" },
      { "mData": "email" },
      { "mData": "phone" },
      { "mData": "active" }
    ]
  })
});
Şeklen şöyledir. "Show x entries" ve sayfalama otomatik eklenir. Ayrıca tüm veriyi çektiğim için sayfalamayı da DataTables kendisi yapar






14 Aralık 2021 Salı

Boostrap

Giriş
Twitter tarafından geliştirildi. İlk olarak 2011 yılında ortaya çıktı

fluid 12-grid system
Açıklaması şöyle
The Bootstrap grid system uses containers, rows, and columns to ensure that apps and websites are adaptable to devices of varied screen sizes, especially mobile screens. This 12-grid system follows a series of defined rules; for instance, rows are only used to create columns; rows must be empty; rows and columns come together to create containers, etc.

Örnek - bootstrap-3.3.1
Şu satırı dahil ederiz
<link href="resources/lib/bootstrap-3.3.1/css/bootstrap.min.css"
	rel="stylesheet">
...
<script src="resources/lib/bootstrap-3.3.1/js/bootstrap.min.js"
	type="text/javascript"></script>
Tables
Örnek - striped
Şöyle yaparız
"<table class='table table-striped'>


27 Eylül 2021 Pazartesi

HTML Header Tag

Örnek
Şöyle yaparız
<body>
  <header>
    <img src="/static/logo.png" alt="Logo">
    <nav>
      <a href="/">Main page</a>
    </nav>
  </header>
  <main>
    <article>
      <h1>Title</h1>
      <p>Content</p>
    </article>
  </main>
  <footer></footer>
</body>

7 Eylül 2021 Salı

HTML Embed Tag

Örnek - PDF
Şöyle yaparız
<embed id="plugin" type="application/x-google-chrome-pdf" src="..." 
...
>

2 Eylül 2021 Perşembe

TypeScript Type Guard

Giriş
Type Guard çeşitleri şöyle
null Guard
typeof Guard
instanceof Guard
in Guard
Discriminated Union Guards
User-Defined Guards
null Guard - null kontrolü yapar
Örnek
Şöyle yaparız
const element: HTMLElement | null = document.getElementById('target');

element.innerText = 'Hello'; // Compiler error - null in union

if (element !== null) {
    element.innerText = 'Hello'; // null removed from union 
}
null Guard yerine Optional kullanmak çok daha kolay. Şöyle yaparız.
element?.innerText = 'Hello';
typeof Guard
Örnek
Şöyle yaparız
// Note that the type of 'primitive' in each branch is different
switch (typeof primitive) { case "number": return primitive.toFixed(2); case "string": return primitive.toUpperCase(); case "boolean": return !primitive; default: throw new Error("Unexpected type") }
Açıklaması şöyle
Remember that typeof can only tell us if a type is string, number, boolean, symbol, function, bigint, undefined. Everything else will return "object".
instanceof Guard
Örnek
Şöyle yaparız
function setupInput(input: HTMLInputElement | HTMLTextAreaElement) {
    input.value = ''; // Valid since value is common to both types

    if (input instanceof HTMLTextAreaElement) {
        // These properties are only valid for HTMLTextAreaElement
        input.rows = 25;
        input.cols = 80;
        input.wrap = 'hard';
    } else {
        // These properties are only valid for HTMLInputElement
        input.width = 400;
        input.height = 50;
    }
}
in Guard
Örnek
Şöyle yaparız
function setupInput(input: HTMLInputElement | HTMLTextAreaElement) {
    if ('rows' in input) {
        // These properties are only valid for HTMLTextAreaElement
        input.rows = 25;
        input.cols = 80;
        input.wrap = 'hard';
    } else {
        // These properties are only valid for HTMLInputElement
        input.width = 400;
        input.height = 50;
    }
}
Açıklaması şöyle
The in operator allows us to test an object for the existence of a member. In the code below, only HTMLTextAreaElement has a rows property so by testing for its existence the compiler determines the type of the input variable on each branch and narrows the type.

Note, in can only be used if ALL members of the union are object types (not primitives).
in Guard kullanıyorsak return type'a dikkat etmek gerekir. Şöyle yaparız
function isTextArea(input: HTMLInputElement | HTMLTextAreaElement):
input is HTMLTextAreaElement { return 'rows' in input; } if (isTextArea(input)) { // input has type HTMLTextAreaElement input.rows = 25; // Valid }
Eğer şöyle yapsaydık derleme hatası alırdık. Çünkü boolean dönünce "type narrowing" yapılmıyor.
function isTextArea(input: HTMLInputElement | HTMLTextAreaElement): boolean {
    return 'rows' in input;
}

if (isTextArea(input)) {
    // input still has union type
    input.rows = 25; // Compiler error
}
Ayrıca TypeScipt 4.4 ile "type narrowing" şöyle de oluyor. Buna Control Flow Analysis information (CFA) deniliyor.
const isTextArea = 'rows' in input;

if (isTextArea) {
    // Narrowing has taken place
    input.rows = 25;
}
Örnek
Elimizde şöyle bir kod olsun.
interface A {
  text: string;
}
interface B {
  type: string;
}
type C = A|B;
B tipindeki nesneleri süzmek için şöyle yaparız.
function isB(c: C): c is B {
  if ('type' in c) { 
    return typeof c.type === 'string';
  }

  return false;
}
Elimizde bir array olsun.
const arr: Array<C> = [....]
Şöyle yaparız.
const output = arr.find(isB);





TypeScript Type Unions

Giriş
Açıklaması şöyle
Type Unions allow us to define a new type which represents any one of a set of possible types. 
Örnek
Şöyle yaparız
type Primitive = 
    | string
    | number
    | boolean;

let x: Primitive;
Kullanmak için şöyle yaparız.
x = 'Hello';
x = 123;
x = false;

x = new Date(); // Compiler Error
Değişkenin tipini anlamak için şöyle yaparız.
if (typeof x === 'number') {
  console.log(x.toFixed(2)); // 'x' can safely use 'number' operations 
}

TypeScript Derive New Types From Existing Types

Giriş
Açıklaması şöyle
It’s possible in TypeScript to derive new types from existing types using type unions, type intersections, mapped types, and conditional types
Type Intersection
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// Type Intersection
type EmployeeWithId = Employee & { id: string };
// This type will be equivalent to
// {
//    id: string;
//    name: string
//    age: number;
//    dob: Date;
// }

// Readonly uses Mapped Types
type ReadonlyEmployee = Readonly<Employee>;
// This type will be equivalent to
// {
//    readonly name: string
//    readonly age: number;
//    readonly dob: Date;
// }

// A Mapped Type with a Conditional Type allows for interesting transformations
type DateToString<T> = {
    [P in keyof T]: T[P] extends Date ? string : T[P];
};

type EmployeeJson = DateToString<Employee>
// This type will be equivalent to
// {
//    name: string
//    age: number;
//    dob: string; // Date has changed to string
// }
ReadOnly
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// Readonly uses Mapped Types
type ReadonlyEmployee = Readonly<Employee>;
// This type will be equivalent to
// {
//    readonly name: string
//    readonly age: number;
//    readonly dob: Date;
// }
MappedType
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// A Mapped Type with a Conditional Type allows for interesting transformations
type DateToString<T> = {
    [P in keyof T]: T[P] extends Date ? string : T[P];
};

type EmployeeJson = DateToString<Employee>
// This type will be equivalent to
// {
//    name: string
//    age: number;
//    dob: string; // Date has changed to string
// }

24 Ağustos 2021 Salı

Chrome Developer Tools

Giriş
F12 ile açılır

Console Sekmesi
Bir değişkene yeni değer atamak için kullanılabilir.

Network Sekmesi
1. Throttle
Şöyle yaparız. 5. adımda anlatıldığı gibi "Reload this page" simgesine basılı tutarken DevTools penceresi açık olmalı
Steps To Use the Throttler
1. Open DevTools (Ctrl + Shift + I)
2. Switch to the Network Tab.
3. By default, the throttler is set to ‘No Throttle’.
4. From the dropdown menu, you can select the type of network to simulate.
5. Long Press the reload icon while the DevTools panel is open.
6. Select ‘Empty Cache and Hard Reload’ from the advanced reload options. It is important to empty cache to examine the page as a first time visitor.

29 Temmuz 2021 Perşembe

TypeScript Optional

Örnek
Şöyle yaparız
interface Cat {
  name: string;
  age: number;
  ownerName?: string; // not every cat has an owner
}

const mrWhitePaws: Cat = {
  name: "Mr. White Paws",
  age: 7,
  ownerName: "Jane", // domestic cat, lucky guy
};

const wildLynx: Cat = {
  name: "Lynx lynx",
  age: 6,
  // this wild cat lives a free life!
};
Örnek
null Guard yerine Optional kullanmak çok daha kolay. Şöyle yaparız.
element?.innerText = 'Hello';
optional chaining ve nullish coalescing
Açıklaması şöyle
The optional chaining allows to safely “navigate” through possibly absent values (without throwing an error), while the nullish coalescing operator, or the ??, enables providing a failover (default) value in case of stumbling upon a null (think of it as a good, old || operator, but for null or undefined values only, instead of all “falsy” ones). Again, keep in mind, that this is an example of a feature eventually available in pure JavaScript, too.
Örnek
Şöyle yaparız
// optional chaining:
// The value will be undefined. Without `?.`, this would error with
// "Uncaught TypeError: Cannot read property 'length' 
const nameLength: string | undefined = wildLynx?.name?.length; of undefined".

// nullish coalescing:
const nope = null;
const calculation = (nope ?? 0) + 42; // The value will be 0 + 42, ergo 42.

25 Temmuz 2021 Pazar

HTML Img Tag

alt Alanı
Örnek
Şöyle yaparız
<img src="/static/cat.jpg" alt="Cat" />
srcset Alanı
Örnek
Şöyle yaparız
<img srcset="small-car-image.jpg 400w,
             medium-car-image.jpg 800w,
             large-car-image.jpg 1200w"

     sizes="(min-width: 1280px) 1200px,
            (min-width: 768px) 400px,
            100vw"
     
     src="medium-car-image.jpg" alt="Car">
Açıklaması şöyle
srcset attribute accepts multiple images with their respective width in pixels, and the browser uses these values to choose between provided images. In the above example, there are 3 versions of the same image in 3 different sizes

The sizes attribute defines the space that the image will take up on the screen. In the above example, the image will take up 1200px if the screen’s minimum width is 1280px.

HTML Picture Tag

HTML Img tag yetersiz kalıyor. Açıklaması şöyle
However, with the development of devices of various screen sizes, resolutions, and complex user requirements, questions have begun to raise about its responsiveness and ability to be used in multi-device applications.
Yani iki temel sebep var. 
1. Resolution Switching
2. Art Direction : 

Bu iki sebepten herhangi birisi tek başına HTML Picture tag'i seçmek için yeterli değil. Sadece Resolution Switching gerekiyorsa, HTML Img tag te kullanılabilir.

Resolution Switching
HTML Img tag ile olan problem şöyle
Suppose you use a simple Img tag for high-res images. In that case, that same image is used in each device your application runs, and indeed it will result in performance issues in devices with lower screen resolutions like mobile devices.
Art Direction
Orientation yani Landscape veya Portrait demek

source/media Alanı
Örnek
Şöyle yaparız
<picture>
<source media="(orientation: landscape)" srcset="land-small-car-image.jpg 200w, land-medium-car-image.jpg 600w, land-large-car-image.jpg 1000w" sizes="(min-width: 700px) 500px, (min-width: 600px) 400px, 100vw"> <source media="(orientation: portrait)" srcset="port-small-car-image.jpg 700w, port-medium-car-image.jpg 1200w, port-large-car-image.jpg 1600w" sizes="(min-width: 768px) 700px, (min-width: 1024px) 600px, 500px"> <img src="land-medium-car-image.jpg" alt="Car"> </picture>
Açıklaması şöyle
If the screen orientation is landscape browser will show the images from the first image set, and if the orientation is portrait browser will use the second set. 
En alttaki img için açıklaması şöyle
The last img tag is there for backward compatibility for browsers that do not support picture tags.
Örnek
Şöyle yaparız
<picture>
     <source media="(max-width: 767px)" ....>
     <source media="(min-width: 768px)" ....>
</picture>
source/srcset Alanı
Örnek
Şöyle yaparız
<picture>
   <source
      srcset="small-car-image.jpg 400w,
              medium-car-image.jpg 800w,
              large-car-image.jpg 1200w"
      sizes="(min-width: 1280px) 1200px,
             (min-width: 768px) 400px,
             100vw">
   <img src="medium-car-image.jpg" alt="Car">
</picture>
Örnek - type
Şöylee yaparız
<picture>
  <source srcset="test.avif" type="image/avif">
  <source srcset="test.webp" type="image/webp">
  <img src="test.png" alt="test image">
</picture>
Açıklaması şöyle
The above example includes three image types from avif, webp, and png formats. First, the browser will try avif format, and if that fails, it will try webp format. If the browser does not support both of these, it will use png image.

19 Temmuz 2021 Pazartesi

Supervisor.js

Giriş
Açıklaması şöyle. Kod değişikliğini hemen uygular
The development problem is that when we change the code, we have to stop and start the application to get our changes picked up.
To solve that, we usually use some sort of Node process manager like supervisor or nodemon. These packages will watch our project and restart our server whenever we make changes. 
Örnek
Şöyle yaparız
"scripts": {
  "dev": "npx supervisor index.js",
  "start": "node index.js"
}

16 Temmuz 2021 Cuma

Fs.js

pipe metodu
Örnek
Şöyle yaparız
const fs = require('fs')

const original = fs.createReadStream('./original.txt')
const copy1 = fs.createWriteStream('./copy1.txt')
const copy2 = fs.createWriteStream('./copy2.txt')

original.pipe(copy1)
original.pipe(copy2)

1 Temmuz 2021 Perşembe

TypeScript Pick

Giriş
Açıklaması şöyle
Have you ever tried to narrow a type because you realized that your next class doesn’t need this bunch of properties? Or maybe you arrived at this point in the process of refactoring, trying to distribute pieces of a system in a new way. There are several types that can solve this problem.

Pick helps you to use a defined already interface but take from the object only those keys that you need.

Omit which isn’t predefined in the Typescript lib.d.ts but is easy to define with the Pick and Exclude. It excludes the properties that you don’t want to take from an interface.

TypeScript Required

Giriş
Açıklaması şöyle
... the Required built-in type introduced in Typescript v2.8, makes all properties of a described object required.
One of the use cases for Required is selectors: sometimes you want to make a selector for a property from a nested object and you know that at the moment of selector invocation this property will be defined. 



25 Haziran 2021 Cuma

Loose Equality Comparison - 2 Tane Eşittir

Giriş
Açıklaması şöyle. Farklı tiplerdeki nesnelerin eşitliğini kontrol etmek için kullanılır
The JavaScript operator == means equal after type juggling.
Nasıl Çalışır
Mantıksal olarak şuna benzer. Her iki nesneyi de string'e çevirip karşılaştırmak gibidir.
static boolean compareData(Object v1, Object v2)
{
  if(v1 != null && v2 != null)
    return (v1.getClass() == v2.getClass() && (v1.toString().equals(v2.toString())));
  else
  {
    return (v1 == null ? v2 == null : v1.equals(v2));
  }
}
Açıklaması şöyle. Eğer her iki tip de aynı ise == yavaş değildir.
== is exactly as fast as === when both operands have the same type, and there's nothing wrong with using it when you know that both operands have the same type. You only got a problem when you don't know what types the operands have. 
Örnek
Şu kod  true döner
'0e111' == 0
Örnek - Number ve BigInt Karşılaştırma
Şöyle yaparızz
42 == 42n  // true!