DTO projections are very important to doing abstraction over model and data processing. Most common interests are fecthing data with a spesific partition and/or different format other than model. Also DTOs can be very usefull for partial database updates. In JPQL, query results can be transfered into DTOs with new keyword as following:
SELECT new org.module.submodule.ExampleDTO(b) FROM Book b
Also you can send parameters via constructor separately. But this approach provide you to control DTO flow and lazy initializations.
@Getter
@Setter
public class ExampleDTO {
private String bookName;
private Set<BookOwner> bookOwners;
public ExampleDTO (Boob b) {
this.bookName = b.getName();
this.bookOwners = b.getBookOwners();
Hibernate.initialize(b.getBookOwners());
}
}
In the constructor block, you can manage all initialization, property inclusions, property exclusions and customizations.
For some reason, you may need to generate GUID in an excel document. For me, because of using GUID as primary keys in database, I have needed to generate insert scripts and GUIDs as primary keys. First of all you need to activate developer options of excel. After that, you are able to write macros. Finally, create a module and create function given below:
Function createguid()
Dim guid As String
guid = CreateObject("WScript.Shell").Exec("powershell -command [guid]::newGuid().ToString()").StdOut.ReadAll
createguid = Application.WorksheetFunction.Clean(guid)
End Function
In this approach, powershell is used for GUID generation. You can use this function in formulas after creation. Only drawback of this method is powershell console is opened and closed as many as generated GUIDs.
In this article, we render CSS styled HTML to image. With this method, HTML can be exported to png, jpeg or bmp without using any external js library. SVG 2 is a new recommendation that is exposed by w3 consortium. SVG 2 has a new feature, foreign object, that enables us to use different rendering engines in a SVG representation. So, we use HTML rendering engine to render image representation of HTML. Example codes are at below:
<div id="export_html_to_svg_container" style="display: flex;flex-direction: row;width: 300px; height: 100px;flex-grow: 1">
<div style="width: 100%; background-color: #ff7070;"></div>
<div style="display: flex;justify-content: center;text-align: center;align-items: center;width: 100%;background: #a624a8;font-weight: 500;color: white;">OUTPUT</div>
<div style="width: 100%; background-color: #7070ff;"></div>
</div>
<div style="margin-top:10px">
<button onclick="exportToImage('png')">PNG</button>
<button onclick="exportToImage('jpeg')">JPEG</button>
<button onclick="exportToImage('bmp')">BMP</button>
</div>
<script>
function exportToImage(imageType) {
let content = document.getElementById("export_html_to_svg_container");
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
let foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
svg.appendChild(foreignObject);
foreignObject.innerHTML = content.outerHTML;
svg.setAttribute("width", "300px");
svg.setAttribute("height", "100px");
foreignObject.setAttribute("width", "100%");
foreignObject.setAttribute("height", "100%");
let serializer = new XMLSerializer();
let serializedContent = serializer.serializeToString(svg);
let base64Content = btoa(serializedContent);
let imageUrl = "data:image/svg+xml;base64," + base64Content;
let img = document.createElement("img");
img.onerror = function (a, b) {
alert("error");
}
img.onload = function () {
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
let dataUrl = canvas.toDataURL("image/" + imageType);
simulateDownload("output." + imageType, dataUrl);
}
img.src = imageUrl;
}
function simulateDownload(download, href) {
const a = document.createElement('a');
a.download = download;
a.href = href;
a.click();
a.remove();
}
</script>
In example, we render div (export_html_to_svg_container) object with its content to image. First of all, we create an SVG object. We need a foreign object to place the HTML in, so we create one. We put the HTML in the foreign object and the foreign object in the SVG object. Before rendering, we must set the SVG object's width and height attributes. Finally, we serialize the SVG object to string with XMLSerializer and generate an image url using that string. With this url, we render the output image with the help of the image(img) object and canvas.
This method is compatible with many modern browsers like Chrome, Firefox and Edge.
k Nearest Neighbours Classifier (kNN) is a powerful but computational costly nonlinear classifier. Basically, kNN works based on distance calculation and finding of closest neighbour vectors according to a distance function. Distance function can be l1 (Manhattan distance), l2 (Euclidean distance) or a different available appropriate distance function. kNN uses a hyper parameter (k) that implies count of closest neighbours.
Algorithm find closest k vector to current vector, and returns classification result as class label of the largest matched number of class between these k closest vectors.
In this example; classes 1,2,3 corresponds to red, green and purple respectively. Algorithm takes k, x and y as input and return class label as color and draw last input point as a orange point.
While using Devextreme toast widget, you may need to configure it. By default, toast widget placed bottom middle of window. In this article, I write a wrapper javascript code to configure widget globally, and I provide to show widged at bottom right of window and widget will be continuing to display content while mouse hover on it. This wrapper code is also compatible with older browsers.
Wrapper code is dependent to Jquery.
dx-toast-wrapper.js:
var toastDefault = {
width: "500px",
displayTime: 4000,
cancelHiding: false,
contentTemplate: null,
position: {
at: "right bottom",
collision: "fit",
boundaryOffset: "20 20",
},
onContentReady: function (e) {
$(e.element).on("mouseenter", function () {
this.cancelHiding = true;
}.bind(this));
$(e.element).on("mouseleave", function () {
this.cancelHiding = false;
e.component.hide();
}.bind(this));
}.bind(this),
onHiding: function (e) {
e.cancel = this.cancelHiding;
}.bind(this)
};
var toast = {
success: function (message) {
toastDefault.contentTemplate = function () {
return $("</p>").html(message);
};
toastDefault.type = "success";
DevExpress.ui.notify(toastDefault);
},
error: function (message) {
toastDefault.contentTemplate = function () {
return $("</p>").html(message);
};
toastDefault.type = "error";
DevExpress.ui.notify(toastDefault);
},
info: function (message) {
toastDefault.contentTemplate = function () {
return $("</p>").html(message);
};
toastDefault.type = "info";
DevExpress.ui.notify(toastDefault);
},
warning: function (message) {
toastDefault.contentTemplate = function () {
return $("</p>").html(message);
};
toastDefault.type = "warning";
DevExpress.ui.notify(toastDefault);
}
}
We can use ProjectBaseCore(PBC) without dependency injection(DI) by instantiating DatabaseFactory class with new keyword. We can give to factory class's constructor function a object that is implemented IConfiguration interface, or we can create database object by simply giving connection string and provider parameters to GetDbObject function. I give a console application example of how to use PBC without DI.
Program.cs:
class Program
{
static void Main(string[] args)
{
DatabaseFactory databaseFactory = new DatabaseFactory(GetConfiguration());
IDatabase2 db = databaseFactory.GetDbObject();
var dt = db.ExecuteQueryDataTable("select * from product");
}
static IConfigurationRoot GetConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(System.AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
}
ProjectBaseCore (PBC) has to be injected to use in .net core project with version 2.x and later. After version 2.x, DatabaseFactory and QueryGeneratorFactory classes are no longer static classes. As a result, PBC version 2.x is not compatible with older versions, because you must inject DatabaseFactory and QueryGeneratorFactory classes or instantiate them with using new keyword.
First of all, in startup.js file or in a dependency injection container, injection must be defined:
In startup file, we write these codes in "ConfigureServices" function. After these declarations, we can use these services in controllers or middleware classes.
public class HomeController : Controller
{
private readonly IDatabaseFactory _databaseFactory;
private readonly IQueryGeneratorFactory _queryGeneratorFactory;
public HomeController(IDatabaseFactory databaseFactory, IQueryGeneratorFactory queryGeneratorFactory)
{
_databaseFactory = databaseFactory;
_queryGeneratorFactory = queryGeneratorFactory;
}
public IActionResult Index()
{
var db = _databaseFactory.GetDbObject();
var qg = _queryGeneratorFactory.GetDbObject();
qg.SelectText = "select * from product";
var dt = db.ExecuteQueryDataTable(qg.GetSelectCommandBasic());
return View();
}
}
I give an example of javascript implementation of support vector machines (SVM) and I explain SVM algorithm with hinge loss function in this article.
SVM algorithm aims to find a hyperplane that separates dataset in two classes:
For SVM, classes take values {1,-1}. Algorithm tries to find a hyperplane by maximizing margin between support vectors and hyperplane. We can describe support vectors as closest vectors to hyperplane. In 2 dimensional space, a hyperplane corresponds to a line.
So, to calculate a hyperplane, we must define hyperplane function:
f(x) = wx + b;
In this example, our space is 2 dimensional, so we have a coordinate point (x,y) and a class label (c).
As a result, we have a dataset that consists of javascript objects that includes {c,x,y} properties. Before going to optimization step, we must define SVM loss function. In this loss function, yi corresponds to c and xi corresponds to x,y for our case.
SVM algorithm uses hinge loss function. This loss function penalizes incorrect classifications. Max function is a convex function, so we can use gradient descent algorithm (GDA) as optimization algorithm. In 2 dimension, we have w1, w2 and b as optimization parameters. So we calculate partial derivatives:
d/dw1 Loss(w1,w2,c,x,y,b) = -1 * c * x
d/dw2 Loss(w1,w2,c,x,y,b) = -1 * c * y
d/b Loss(w1,w2,c,x,y,b) = -1 * c
While calculating loss, we calculate all losses for all points and take their mean value. As a result, we can calculate w1,w2 and b by using GDA. In our example, 1 labeled class and -1 labeled class are drawn red and blue respectively.
In this article, I explain how gradient descent algorithm (GDA) works. I use a quadratic function for explanation:
f(x) = ax^2+bx+c
As you know, gradient of a function is first derivative of function (f'(x)). First derivative of f(x):
f'(x) = 2ax + b;
GDA is a iterative algorithm that calculates gradient of function f(x) for x in each iteration, and calculates next point by substracting gradient from x. GDA uses a learning parameter (alfa) that regularizes changings of x. So in each iteration, GDA calculates next x value:
x(t+1) = x(t) - alfa*f'(x(t))
So, why does GDA use gradient of function?
Think yourself on a hill and you want to get down. If slope is steep, you take a big step, otherwise a small step. Because while coming to end of hill, slope will be smaller until it is zero.
If you think of gradient as a vector, gradient's direction always guide you to end of hill or top of hill.
Note that, we can use GDA to find minimum point of a convex function, and gradient ascent algorithm to find maximum point of a concave function.
I prepared a working javascript example. You can calculate minimum point of quadratic function and visualize calculated point and function with this code.
In each iteration, calculated point (x,y) is displayed as a red dot.
->x (starting value of x)
->alfa (learning parameter)
->maxIteration (maximum iteration count)
->a
->b
->c
Javascript Codes:
<script>
var x = 200;
var alfa = 0.01;
var maxIteration = 5000;
var a = 1;
var b = -5;
var c = 6;
var fx = (x) => a * x * x + b * x + c;
var dxfx = (x) => 2 * a * x + b;
function start() {
setValues();
drawCurve();
var canvas = document.getElementById("g");
let y = 0;
for (var i = 0; i < maxIteration; i++) {
x = x - alfa * dxfx(x);
y = fx(x);
let circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');;
circle.setAttributeNS(null, "cx", x);
circle.setAttributeNS(null, "cy", y);
circle.setAttributeNS(null, "r", 1);
circle.setAttributeNS(null, "fill", "red");
canvas.appendChild(circle);
}
let resultDiv = document.getElementById("resultDiv");
resultDiv.innerHTML = "x:" + x + ", y:" + y;
}
function setValues() {
x = parseFloat(document.getElementById("x").value);
alfa = parseFloat(document.getElementById("alfa").value);
maxIteration = parseFloat(document.getElementById("maxIteration").value);
a = parseFloat(document.getElementById("a").value);
b = parseFloat(document.getElementById("b").value);
c = parseFloat(document.getElementById("c").value);
}
function drawCurve() {
var canvas = document.getElementById("g");
for (var i = 5000; i >= -5000; i -= 1) {
let line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttributeNS(null, "x1", i);
line.setAttributeNS(null, "y1", fx(i));
line.setAttributeNS(null, "x2", i - 1);
line.setAttributeNS(null, "y2", fx(i - 1));
line.setAttributeNS(null, "style", "stroke: rgb(0, 255, 0); stroke-width:1");
canvas.appendChild(line);
}
}
</script>