<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mustafa Tayyip Yetiş on Medium]]></title>
        <description><![CDATA[Stories by Mustafa Tayyip Yetiş on Medium]]></description>
        <link>https://medium.com/@mtayyipyetis?source=rss-450ab665551e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IFsJRNQFbmYHKjYF.jpg</url>
            <title>Stories by Mustafa Tayyip Yetiş on Medium</title>
            <link>https://medium.com/@mtayyipyetis?source=rss-450ab665551e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:35:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mtayyipyetis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding WebRTC: History, Purpose, and Features]]></title>
            <link>https://medium.com/@mtayyipyetis/understanding-webrtc-history-purpose-and-features-0c0992ec299e?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c0992ec299e</guid>
            <category><![CDATA[messaging-apps]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[audio-stream]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 16:16:02 GMT</pubDate>
            <atom:updated>2025-01-03T06:07:16.345Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding WebRTC: History, Purpose, and Real-World Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Lj1HiHRk7o6rtBauUPCnXw.png" /></figure><p>I have brought the messaging application that I have been working on for a long time to a certain point and decided to add new features after ensuring healthy message delivery. Of course, big messaging applications such as WhatsApp, Telegram, Facebook Messenger use complex and various technologies to provide stable and uninterrupted messaging service. The main features that a messaging application should have are stability, trouble-free operation and speed. In order to provide these qualities, you should think about very detailed scenarios and calculate well how the system should behave in every situation. For example, if there is more user load than you expected, how will you adapt the system to this situation as quickly as possible? How will you ensure data synchronization between the user’s device and your servers? Will you use end-to-end messaging like WhatsApp or server-based messaging like Telegram? What kind of messages will you support sending, image, video, audio, location, etc.? And you should also support older devices to reach more users.</p><p>There are hundreds of problems like this and others that you need to deal with, but of course, depending on the scope of your application, you may need to focus on more basic problems rather than all of them. I am working on a more minimal system that will support scaling, so it is easier to bring the application to a certain level, and it is also suitable for adding new features and scaling in the future. In addition to these, I wanted to add voice and video calling features to my application in addition to messaging, and for this I researched third-party paid and free services. What I really wanted was to write my own service, but first I researched alternatives and as I expected, I generally encountered expensive and unsustainable services, so I rolled up my sleeves.</p><p>When I was thinking about how I could develop a voice calling application, the first thing that came to my mind was the method I use most often, websocket. I had used this technology a lot in the past when I needed to transfer real-time data, and I thought I could use it to transfer the live audio stream from the user device first to the server and then to the target user. However, when I examined it in detail, I realized that this method was quite unhealthy and dysfunctional, because in a situation where a large amount of data, such as audio and video transfer, needed to be transferred with minimal delay, transferring data over the server was a very inefficient method.</p><p>In the end, I decided to use <strong>WebRTC</strong>, which was already developed for this purpose and had ready-made structures under the hood. After adding voice and call features to my application with <strong>WebRTC</strong> and passing my tests, I wanted to write an article about my experiences. Before moving on to the code, let’s look at the theoretical information about WebRTC, then I will show the processes of calling a user and establishing a peer-to-peer connection in a real-world scenario.</p><p>WebRTC (Web Real-Time Communication) is a groundbreaking technology that has transformed how we communicate over the internet. By enabling direct peer-to-peer connections, it eliminates the need for intermediaries, significantly reducing latency</p><h3>History and Origin of WebRTC</h3><p>WebRTC was introduced by Google in 2011 to enable seamless, high-quality real-time communication over the web without relying on third-party plugins. The initiative addressed issues like latency and cross-platform compatibility. The project originated from Google’s acquisition of Global IP Solutions (GIPS) in 2010, which specialized in real-time audio and video technology. Google open-sourced WebRTC, allowing developers to create rich communication experiences.</p><p>In 2011, WebRTC became a collaborative effort under the W3C and IETF to standardize real-time communication protocols for browsers. Today, it is supported by major browsers, including Google Chrome, Mozilla Firefox, Microsoft Edge, and Apple Safari.</p><h3>Purpose of WebRTC</h3><p>The primary goal of WebRTC is to provide real-time communication capabilities in browsers and mobile applications without relying on third-party plugins or software. By enabling developers to integrate real-time communication features natively into web and mobile environments, it simplifies the creation of a variety of applications, such as v<strong>ideo, voice calls, data transfer, live streaming</strong></p><h3>How WebRTC Differs from WebSocket</h3><p>WebRTC and WebSocket are both used for real-time communication over the web, but they serve different purposes and operate in distinct ways:</p><ul><li><strong>WebRTC</strong> is designed for peer-to-peer (P2P) communication, allowing direct audio, video, and data streaming between browsers or devices without needing an intermediary server (except for signaling). It reduces latency and bandwidth usage by establishing direct connections between peers. WebRTC is ideal for real-time audio, video, and data sharing.</li><li><strong>WebSocket</strong> is a full-duplex communication protocol that provides persistent connections between a client and a server over a single TCP connection. It is used for real-time messaging, live notifications, and data feeds (e.g., stock prices). WebSocket ensures reliable message delivery and is efficient for client-server communication, making it suited for applications like chat or real-time updates.</li></ul><h3>Key Concepts: ICE, NAT, and STUN</h3><p>To establish seamless peer-to-peer communication, WebRTC relies on several core technologies. These technologies are essential for overcoming challenges posed by network configurations, such as firewalls and NAT devices, which can obstruct direct communication between peers.</p><ol><li><strong>ICE (Interactive Connectivity Establishment):</strong> ICE is a framework used by WebRTC to discover and negotiate the best possible communication path between peers. It combines candidate network routes, including local, public, and relay addresses, to ensure a successful connection. ICE makes use of protocols like STUN and TURN to traverse NAT devices and firewalls.</li><li><strong>NAT (Network Address Translation):</strong> NAT is a networking process used to map private IP addresses within a local network to a single public IP address. While NAT enhances security and conserves IP addresses, it introduces challenges for direct peer-to-peer communication. WebRTC addresses this by using ICE and STUN/TURN servers to determine the external IP and port needed to connect two peers.</li><li><strong>STUN (Session Traversal Utilities for NAT):</strong> STUN is a protocol that helps devices discover their public-facing IP address and port when located behind a NAT. It allows WebRTC to establish a direct connection by informing both peers of their respective network addresses. However, if direct communication fails (e.g., due to symmetric NATs), a TURN server is used as a fallback.</li><li><strong>TURN (Traversal Using Relays around NAT):</strong> TURN servers act as intermediaries for relaying data when direct connections cannot be established. Although TURN introduces higher latency and additional costs, it ensures reliable communication in challenging network scenarios.</li></ol><h3>Real-World Application of WebRTC: Messaging App Example</h3><p>Let’s examine a real world scenario using webrtc via a messaging app like Whatsapp, Telegram etc. In this scenario, a user makes a voice or video call to another user. The calling user’s identity, offer description and asynchronously obtained iceCandidate information are sent to the called user via the Signaling server. <strong>The signaling server is only used to transfer offer, response and iceCandidate information between peers when the first connection is established. audio and video data are transferred directly between peers once the connection is established</strong></p><p>The called user receives the call request from the signaling server, which includes the identity of the calling user, offer description and iceCandidate information. The called user stores this information on a temporary object because a peer connection has not been created since there is no response yet and the call process occurs asynchronously so this information will be needed to establish a connection when the response is given. When the called user accepts the call, a peer connection is created and the conversation begins. Below is a visual diagram of this process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC_52_kgxvvlEDK8xxzK_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*brMSlLOUsA9U_QFe3B29tg.png" /></figure><p>Let’s write a <strong>WebRtcService</strong> to perform this process. Let this service have Call, Answer, Reject methods and onMessage event. onMessage event serves as a bridge that enables the processing of events received from the signaling server according to their types. An important issue here is; Since iceCandidate information is sent asynchronously, we need to store it until the user answers the call. We store this information in the <strong>activeCall</strong> object.</p><pre>class WebRtcService {<br>    SocketConnection;<br>    remoteStream;<br>    localStream;<br>    localVideo;<br>    remoteVideo;<br>    peerConnection;<br>    messageType = {<br>        voiceCall: 1,<br>        videoCall: 2,<br>        answer: 3,<br>        iceCandidate: 4,<br>        endCall: 5,<br>        reject: 6<br>    }<br>    callType: {<br>       Voice: 1,<br>       Video: 2<br>    }<br><br>    constructor() {<br>      //set SocketConnection (signalR)<br>      //tempStore can be thought of as an object used as a store within the application.<br>    }<br><br>    async OnMessage(message) {<br>        if (message.type == this.messageType.voiceCall || message.type == this.messageType.videoCall) {<br>            if (tempStore.activeCall) {<br>                this.sendMessage(this.messageType.endCall, message.senderUserId)<br>                return<br>            }<br>            tempStore.activeCall = {<br>                userId: message.senderUserId,<br>                type: message.type,<br>                status: Utils.CallStatus.IncomingCall,<br>                user: userService.getUser(message.senderUserId),<br>                iceCandidates: [],<br>                message<br>            }<br>            this.OnCalling()<br>        }<br>        else if (message.type == this.messageType.answer) {<br>            this.onAnswer(message)<br>        }<br>        else if (message.type == this.messageType.iceCandidate) {<br>            if (this.peerConnection) await this.peerConnection.addIceCandidate(new RTCIceCandidate(message.message));<br>            else tempStore.activeCall.iceCandidates.push(message.message)<br>        }<br>        else if (message.type == this.messageType.endCall || message.type == this.messageType.reject) {<br>            this.onEndCall()<br>        }<br>    }<br><br>    sendMessage(type, userId, message) {<br>        this.SocketConnection.invoke(&quot;OnWebRtcMessage&quot;, { type: type, receiverUserId: userId, message: message })<br>    }<br><br>    OnCalling() {<br>        //Notify user of incoming call<br>    }<br><br>    async Call(user, callType) {<br>        var userId = user.userId<br>        if (tempStore.activeCall) return //return if there is a call in progress<br>        tempStore.activeCall = { userId: userId, type: callType, status: Utils.CallStatus.OutgoingCall, user: user }<br><br>        await this.createPeerConnection(userId);<br>        const offer = await this.peerConnection.createOffer();<br>        await this.peerConnection.setLocalDescription(offer);<br>        this.sendMessage(callType, userId, offer)<br><br>        this.bindLocalMedia()<br>    }<br><br>    async Answer() {<br>        tempStore.activeCall.status = Utils.CallStatus.Answered<br>        await this.createPeerConnection(tempStore.activeCall.userId);<br>        await this.peerConnection.setRemoteDescription(new RTCSessionDescription(tempStore.activeCall.message.message));<br>        const answer = await this.peerConnection.createAnswer();<br>        await this.peerConnection.setLocalDescription(answer);<br>        this.setIceCandidates() //apply stored iceCandidates to the connection<br><br>        this.sendMessage(this.messageType.answer, tempStore.activeCall.userId, answer)<br>        this.bindMedia()<br>    }<br><br>    async EndCall() {<br>        this.sendMessage(this.messageType.endCall, tempStore.activeCall.userId)<br>        this.onEndCall()<br>    }<br><br>    async Reject() {<br>        this.sendMessage(this.messageType.reject, tempStore.activeCall.userId)<br>        this.onEndCall()<br>    }<br><br>    async onAnswer(message) {<br>        tempStore.activeCall.status = Utils.CallStatus.Answered<br>        await this.peerConnection.setRemoteDescription(new RTCSessionDescription(message.message));<br>        this.bindMedia()<br>    }<br><br>    async onEndCall() {<br>        await this.peerConnection?.close()<br>        this.localStream?.getTracks().forEach(track =&gt; track.stop());<br>        this.localStream = null<br>        this.peerConnection = null<br>        tempStore.activeCall = null<br>    }<br><br>    SetMedia(localVideo, remoteVideo) {<br>        //Called from outside the service to dynamically bind html media object<br>        this.localVideo = localVideo<br>        this.remoteVideo = remoteVideo<br>        this.bindMedia()<br>    }<br><br>    bindMedia() {<br>        this.bindLocalMedia()<br>        this.remoteVideo.srcObject = this.remoteStream<br>    }<br><br>    bindLocalMedia() {<br>        if (this.localVideo) this.localVideo.srcObject = this.localStream<br>    }<br><br>    async setLocalStream() {<br>        this.localStream?.getTracks().forEach(track =&gt; track.stop())<br><br>        this.localStream = await navigator.mediaDevices.getUserMedia({<br>            audio: true,<br>            video: true<br>        });<br>        this.localStream.getTracks().forEach((newTrack, index) =&gt; {<br>            //When setLocalStream is called dynamically, we replace the tracks instead of completely disposed them and sending them again.<br>            var sender = this.peerConnection.getSenders()[index];<br>            if (sender) sender.replaceTrack(newTrack)<br>            else sender = this.peerConnection.addTrack(newTrack, this.localStream);<br><br>            const parameters = sender.getParameters();<br>            parameters.encodings[0].maxBitrate = 1000 * 1000; //set max bitrate<br>            sender.setParameters(parameters);<br>        });<br>    }<br><br>    async createPeerConnection(userId) {<br>        const configuration = {<br>            &#39;iceServers&#39;: [ { urls: &#39;stun:stun.l.google.com:19302&#39; } ]<br>        };<br>        this.peerConnection = new RTCPeerConnection(configuration);<br>        await this.setLocalStream()<br>        this.peerConnection.onicecandidate = event =&gt; {<br>            if (event.candidate) {<br>                this.sendMessage(this.messageType.iceCandidate, userId, event.candidate)<br>            }<br>        };<br>        this.peerConnection.icecandidateerror = event =&gt; {<br>            alert(&quot;icecandidateerror&quot;)<br>        };<br><br>        this.peerConnection.ontrack = event =&gt; {<br>            this.remoteStream = event.streams[0];<br>        };<br><br>        this.peerConnection.addEventListener(&quot;connectionstatechange&quot;, (event) =&gt; {<br>                console.log(&quot;webRtc connectionState &quot; + this.peerConnection.connectionState + &quot; &quot; + JSON.stringify(event)<br>        }, false);<br>    }<br><br>    setIceCandidates() {<br>        tempStore.activeCall.iceCandidates.forEach(async c =&gt; {<br>            await this.peerConnection.addIceCandidate(new RTCIceCandidate(c));<br>        })<br>    }<br>}</pre><p>This service shows a basic implementation of calling, answering and connection management with webrtc. You can make your own customizations based on this application and develop it according to the needs of the application.</p><h3>Conclusion</h3><p>WebRTC has revolutionized real-time communication by making it accessible, secure, and efficient for developers and users alike. Key technologies like ICE, NAT traversal, and STUN/TURN servers enable WebRTC to overcome network challenges and provide robust peer-to-peer connections. With its peer-to-peer capabilities, support for rich media, and robust data handling, WebRTC has become an essential technology for modern web and mobile applications. As the internet continues to evolve, WebRTC remains at the forefront of enabling seamless, interactive communication experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBvDJXpY3e6dKDiRtcgOig.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c0992ec299e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Develop An OS For Raspberry Pico?]]></title>
            <link>https://medium.com/@mtayyipyetis/how-to-develop-an-os-for-raspberry-pico-6d90cbba1af8?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d90cbba1af8</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[micropython]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[raspberry-pico]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 17:59:45 GMT</pubDate>
            <atom:updated>2024-02-02T18:11:07.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Raspberry Pico" src="https://cdn-images-1.medium.com/max/600/1*MzCFp6dYHhaHlufjwOn4nA.png" /><figcaption>Raspberry Pico</figcaption></figure><p>Everyone who is remotely involved in technology has heard the word Raspberry at least once. <strong>Raspberry Pi </strong>is defined as a single-board computer developed by the Raspberry Pi Foundation in the United Kingdom in 2012 to teach computer science in schools in developing countries. This small computer, which is popular outside the target market due to its small size and cheap and simple design, started its journey with a 700 Mhz processor and 256 Mb of RAM, and today it continues with a 2.4GHz processor and 8 Gb of RAM with very powerful hardware. With these features, it gradually ceases to be simple and becomes a really fast machine, reaching the level of smartphones. and with the latest model it can even run the Android 13 operating system.</p><p>This magic board with its own RAM and Flash memory can not only be used as a personal portable computer, but can also be used to develop special electronic projects using the multipurpose ports on it. With its powerful hardware features, it can be easily used in projects that require high processing power. Although it does not have its own peripherals such as keyboard mouse, speaker, camera (which is one of the reasons why it is cheap), you can easily connect these modules because the card has Usb, Hdmi, Aux Jack, Lcd and camera interfaces on the card.</p><figure><img alt="Raspberry Pi 5" src="https://cdn-images-1.medium.com/max/800/0*WAFikhd0a92UbtV_.jpg" /><figcaption>Raspberry Pi 5</figcaption></figure><h3>What is Raspberry Pico and RP2040 ?</h3><p>The <strong>Raspberry Pico</strong>, the subject of this article, is similar in name to other single-board computers in the same family, but has a very different hardware and purpose. The Raspberry Pi Foundation, which has been designing products according to the “single card computer” concept since its first models, made a significant change in January 2021 and made a strong entry into the microcontroller card market dominated by brands such as Adafruit, Pimoroni, Arduino, SparkFun. The main reason for this strong and important entry is that the Raspberry Pi Foundation uses the RP2040 microcontroller, a very practical and inexpensive microcontroller developed by themselves.</p><p>This processor, which has 32-bit ARM Cortex-M0+ dual cores, runs at 133Mhz clock speed and has 264KB SRAM on the chip, has become very popular in a short time due to its $4 price, small footprint and easy programming via USB. Although there is no internal flash memory on the chip, the 2/4/8 MB flash memory on the card and 26 multi purpose GPIO pins is quite enough to turn the projects you have in mind into reality. Since it can be programmed with Python as well as C/C++, it is preferred by a wider audience. Another great feature is that commands can be run directly on the chip while connected to the computer, using the method called REPL (Read Eval Print Loop). This method allows you to work by sending your program directly to RAM without programming the flash each time when you need to do a lot of trial and error while working on a project. Of course, you need to use applications such as MicroPython and CircuitPython that allow you to do this.</p><p>In all these aspects, it has significant advantages over Arduino, its closest rival, in terms of hardware and software, but there may still be many different parameters to determine which microcontroller board is suitable for your project.</p><h3>What is MicroPython ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*n7zzKVFRYSLyPPl9.jpg" /></figure><p>Above we mentioned the two most popular ways to program Raspberry Pico. These were C/C++ and Python. The application mentioned in this article was developed on MicroPython, hence with Python. Briefly speaking, MicroPython is a subset of Python 3 developed to work in resource-constrained environments such as microcontrollers, that is, it was created by removing some features of the Python language running on computers and adding some internal libraries according to the microcontroller platform.</p><p>We can roughly describe the way MicroPython works as follows. You transfer the compiled binary file with uf2 extension that you downloaded from the website to RP Pico via USB. Then, whenever you connect it to your computer, it looks like a USB memory and you can program it by dragging and dropping your Python files into RP Pico. When the processor receives power, the MicroPython software inside finds the Python file in the Flash memory and starts executing it. This method also gives you the great opportunity to run Python code dynamically. For example, Raspberry Pico W (model with Wifi chip) can connect to the internet, download the python file and start running it.</p><h3>An Operating System On Raspberry Pico ?</h3><p>In fact, the work that is the subject of this article can be described as a GUI (user interface) rather than an operating system. Because the real equivalent of the operating system here is MicroPython. Developing a real operating system on any processor or microprocessor requires a lot of thought and development (Multi-Tasking, I/O processing, Real-Time mecanishm e.t.c)</p><p>The main idea here is to create a general starting point for the interface needed when developing an embedded system project with displays and inputs. Although it can currently be used with an OLED display and joystick, it is possible and easy to establish a more generic structure. You can create easy menus with GUI, run different callbacks for each item, and provide the necessary data entry for your application with methods such as Toggle, Enum, Text Input, Number Input, Submenu. In addition, I have created a few examples for using the internal file manager and http client and will upload them to my Github address soon. For this project, Raspberry Pico W, ssd1306 Oled display, 2-axis joystick and a standard breadboard were used.</p><p><strong>Main.py</strong></p><p>The entry point to the application is as simple as you see below. Just import it and run the <strong>run() </strong>method. In the following stages, parameters for gpio configuration for oled, joystick and other components can be obtained here</p><pre>from machine import Pin, ADC<br>from OS import *<br><br>OS.run()</pre><p><strong>MainScreen.py</strong></p><p>The OS we developed works on the basis of the screen. This means that you can create your own screen class, prepare interfaces according to your own logic, and switch back and forth between screens. The OS keeps history for screen transitions. Here, if your screen inherits from the “MenuScreen” class, you should only make definitions in the init method. The OS will render the screen by calling the draw() method. Inheritance from the MenuScreen class indicates that this screen will be a menu type screen, and you can create a menu as follows by using its add() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*huxK5_5TWYBVDpfkceEY0g.png" /></figure><pre>from OS import *<br>from MenuScreen import *<br>from FileSelectScreen import *<br>from InputScreen import *<br>from TestScreen import *<br><br>class MainScreen(MenuScreen):<br>    def __init__(self):<br>        super().__init__(&quot;Main Screen&quot;)<br>        self.sample_bool = False<br>        self.sample_enum = 1<br>        menu =  self.add(ScreenItem(&quot;Test Screen&quot;, TestScreen())) \<br>                .add(ScreenItem(&quot;Input Screen&quot;, InputScreen())) \<br>                .add(ScreenItem(&quot;File Screen&quot;, FileSelectScreen())) \<br>                .add(CallbackItem(&quot;Call Method&quot;, self.custom_method, value=1)) \<br>                .add(SubMenuItem(&quot;Sub Menu Item D&quot;, self.onDrawSubmenu)) \<br>                .add(SubMenuItem(&quot;Sub Menu Item&quot;) \<br>                    .add(MenuItem(&quot;Test Item&quot;, 1))) \<br>                .add(ToogleItem(&quot;Toggle&quot;, self.sample_bool, self.toogle_method)) \<br>                .add(ValueItem(&quot;Value Item&quot;)) \<br>                .add(EnumItem(&quot;Enum Item&quot;, [(&quot;Option 1&quot;, 1),(&quot;Option 2&quot;, 2)], self.sample_enum, self.enum_method))<br>        self.menu = menu<br><br>    def onDrawSubmenu(self, menu):<br>        menu.reset()<br>        menu.add(MenuItem(&quot;Dynamic Item&quot;, 1))<br>    def custom_method(self, value):<br>        print(&quot;custom_method &quot; + str(value))<br>    def toogle_method(self, value):<br>        self.sample_bool = value<br>        print(&quot;toogle_method &quot; + str(self.sample_bool))<br>    def enum_method(self, value):<br>        self.sample_enum = value<br>        print(&quot;enum_method &quot; + str(value))</pre><h3>HttpClientScreen.py</h3><p>The OS allows you to send a query to a website or API on the internet with its internal http client API and process the result returned as JSON. The screen below pulls the user list on fakestoreapi.com and displays it in the menu, and when you select a user, it pulls his profile information and displays it on a specially designed screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*-0V_7F8YtYjtbgDIsnkAhA.png" /></figure><pre>from OS import *<br>from MenuScreen import *<br>import json<br><br>class HttpClientScreen():<br>    def __init__(self):<br>        self.isconnected = False<br>        self.menu = MenuScreen(&quot;Results&quot;)<br><br>    def show(self):<br>        OS.oled.fill(0)<br>        OS.oled.text(&quot;Http Api Test&quot;, 0, 0)<br>        OS.oled.show()<br>        if not self.isconnected:<br>            OS.http.connect(self.status)<br>            self.isconnected = True<br>            self.get_users()<br><br>    def on_button_press(self, button):<br>        if button == &quot;ok&quot;:<br>            OS.set_screen(self.menu)<br><br>    def get_users(self):<br>        self.status(&quot;Waiting...&quot;)<br>        data = OS.http.get(&quot;http://fakestoreapi.com/users&quot;)<br><br>        data_dict = json.loads(data)<br>        self.menu.reset()<br>        for i in data_dict:<br>            self.menu.add(CallbackItem(i[&quot;username&quot;], self.get_user, id=i[&quot;id&quot;]))<br>        OS.set_screen(self.menu)<br><br>    def get_user(self, id):<br>        OS.go_back()<br>        self.status(&quot;Waiting...&quot;)<br>        <br>        user = OS.http.get(&quot;http://fakestoreapi.com/users/&quot; + str(id))<br>        data_dict = json.loads(user)<br><br>        OS.oled.fill(0)<br>        OS.oled.text(data_dict[&quot;name&quot;][&quot;firstname&quot;] + &quot; &quot; + data_dict[&quot;name&quot;][&quot;lastname&quot;], 0, 0)<br>        OS.oled.text(data_dict[&quot;email&quot;], 0, 10)<br>        OS.oled.text(data_dict[&quot;address&quot;][&quot;city&quot;], 0, 20)<br>        OS.oled.show()<br><br>    def status(self, text):<br>        OS.oled.fill_rect(0,30,128,8,0)<br>        OS.oled.text(text, 0, 30)<br>        OS.oled.show()</pre><p><strong>InputScreen.py</strong></p><p>The screen below is used when text type data entry is needed in the application. Useful for defining a configuration set such as a wifi password. Input is via the joystick. Move up and down to select a letter in the alphabet, move to the right to move to the next character, or move to the left to insert a space to delete the previous letter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*49sGGKpb2a5oh87012atcQ.png" /></figure><pre>from OS import *<br><br>class InputScreen():<br>    def __init__(self, callback=None):<br>        self.alphabet = &quot; abcdefghijklmnoprstuvyz&quot;<br>        self.block_back = True<br>        self.callback = callback<br><br>    def show(self):<br>        self.input = [0]<br>        self.draw()<br><br>    def draw(self):<br>        OS.oled.fill(0)<br>        OS.oled.text(&quot;Enter Input:&quot;, 0, 0)<br>        OS.oled.text_large(self.getText(), 0, 20)<br>        OS.oled.text(&quot;^&quot;, (len(self.input)-1)*11, 40)<br>        OS.oled.show()<br><br>    def on_button_press(self, button):<br>        if button == &quot;up&quot;:<br>            self.input[-1] += 1<br>        elif button == &quot;down&quot;: <br>            self.input[-1] -= 1<br>        elif button == &quot;ok&quot;:<br>            return self.apply()<br>        elif button == &quot;right&quot;:<br>            self.input.append(0)<br>        elif button == &quot;back&quot;: <br>            if len(self.input) &gt; 1: self.input.pop()<br>            else: self.input[0] = 0<br>        self.draw()<br><br>    def getText(self):<br>        text = &quot;&quot;<br>        for i,e in enumerate(self.input):<br>            text += self.alphabet[e]<br>        return text<br><br>    def apply(self):<br>        if self.callback: self.callback(self.getText())<br>        OS.go_back()</pre><p>In this article, we examined a generic GUI application that can run on microcontrollers using MicroPython. It has aspects that can be improved as a starting point, but I personally find it very useful to use in the projects I develop with Raspberry Pico. By the way I plan to upload the entire project to <strong>Github</strong> soon and share it here.</p><p>I hope it was useful.</p><p>Numeric data entry, Enum data entry, file manager and other screenshots are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*UjOok0UDTtHXO08tumaxWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*JEti1lMR3UvsQpcc7dWSQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*bVSIwZeo-2CZM6QNDtTbSg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d90cbba1af8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is MassTransit and How to Use It Basically ?]]></title>
            <link>https://medium.com/@mtayyipyetis/what-is-masstransit-and-how-to-use-it-basically-4df2a7584825?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df2a7584825</guid>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[mass-transit]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 20:48:04 GMT</pubDate>
            <atom:updated>2023-09-04T21:04:51.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is MassTransit and How to Use It Basically ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*CN6U7wY6Q9OusXLOnUdjag.png" /></figure><p>In today’s world of software development, distributed systems and microservices are becoming increasingly prevalent. Developing such applications can introduce a multitude of complexities, which is where <strong>MassTransit</strong> comes into play as a powerful tool for managing and facilitating communication in distributed applications. <strong>MassTransit</strong> is a powerful tool for managing distributed systems and microservices. With its core features such as asynchronous communication, scalability, ease of integration, and error handling, it can make complex applications more understandable and maintainable. In this article, we will exploring how to harness the advantages of the <strong>MassTransit</strong> library. This library can be a significant asset on your journey of developing distributed applications.</p><h4>What Is MassTransit?</h4><p>MassTransit is an open-source messaging library designed for the .NET ecosystem. It excels in enabling communication and secure data transfer between applications, especially in the realm of asynchronous, distributed applications. In this article, you will explore how to leverage the MassTransit library to build robust and scalable distributed applications.</p><h4>Example Scenario Of Using MassTransit</h4><p>In this scenario, the Order Service receives customer orders and initiates payment processing. If the payment is successful, it sends a message to the Stock Service to decrement the product’s stock. The Stock Service updates the stock levels and informs the Order Service of the outcome. Subsequently, the Order Service sends an order confirmation to the customer, completing the transaction. This scenario illustrates how MassTransit facilitates communication and workflow management among different microservices within a distributed system.</p><h4>Key Features of MassTransit</h4><p>MassTransit boasts several crucial features that assist in developing distributed applications:</p><ol><li><strong>Asynchronous Messaging</strong>: MassTransit is robust in the realm of asynchronous messaging, optimizing communication between components of your application and enhancing performance.</li><li><strong>Ease of Integration</strong>: The library seamlessly integrates with popular message queuing systems such as RabbitMQ, Azure Service Bus, Amazon SQS, allowing you to start quickly by leveraging existing infrastructure.</li><li><strong>Multiple Message Types</strong>: It supports various message types (e.g., commands, events, requests), allowing you to establish a communication model that suits your application’s needs.</li><li><strong>Scalability</strong>: MassTransit is designed to support high-traffic applications, addressing scalability concerns effectively.</li><li><strong>Error Handling</strong>: It offers features for handling errors during message transmission, including automatic retries.</li></ol><h4>Let’s Get Started</h4><p>With MassTransit, you can use the most widely used message brokers such as RabbitMQ, Azure Service Bus, Amazon SQS or you can use it as InMemory in a single application. We will start with an application that works as InMemory to get to know MassTransit and learn its working logic from the basics. First, open a new console application and install the MassTransit library in your project by running the following command</p><pre>dotnet add package MassTransit</pre><p>In its simplest form, I created the project as follows. In the “Models” folder, we add the message types to be used in MassTransit messaging as interfaces. Under the “Consumers” folder, we have consumer classes that consume messages from these message types. In Program.cs, there are the codes where the bus settings are made and the operations that send and receive messages are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*kzsUHp8KbWQX6CPDHlMYAA.png" /></figure><p>The models are as follows</p><pre>public interface IOrderSubmitted <br>{<br>  Guid OrderId { get; }<br>  DateTime Timestamp { get; }<br>}<br><br>public interface IUserCreated <br>{<br>  Guid Id { get; set; }<br>  string Name { get; set; }<br>  string Email { get; set; }<br>}<br><br>public class OrderSubmitted : IOrderSubmitted <br>{<br>  public Guid OrderId { get; set; }<br>  public DateTime Timestamp { get; set; }<br>}<br><br>public class UserCreated : IUserCreated <br>{<br>  public Guid Id { get; set; }<br>  public string Name { get; set; }<br>  public string Email { get; set; }<br>}</pre><p>Consumers are as follows</p><pre>public class OrderSubmittedConsumer : IConsumer&lt;IOrderSubmitted&gt;<br>{<br>    public async Task Consume(ConsumeContext&lt;IOrderSubmitted&gt; context)<br>    {<br>        var order = context.Message;<br>        Console.WriteLine($&quot;Received order: {order.OrderId} submitted at {order.Timestamp}&quot;);<br>    }<br>}<br><br>public class UserCreatedConsumer : IConsumer&lt;IUserCreated&gt;<br>{<br>    public async Task Consume(ConsumeContext&lt;IUserCreated&gt; context)<br>    {<br>        var user = context.Message;<br>        Console.WriteLine($&quot;Created User: {user.Id} # {user.Name} # {user.Email}&quot;);<br>    }<br>}</pre><p>Program.cs is as follows</p><pre>class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var busControl = Bus.Factory.CreateUsingInMemory(<br>            cfg =&gt;<br>            {<br>                cfg.ReceiveEndpoint(&quot;order_queue&quot;, e =&gt;<br>                    {<br>                        e.Consumer&lt;OrderSubmittedConsumer&gt;();<br>                    }<br>                );<br>                cfg.ReceiveEndpoint(&quot;notify_queue&quot;, e =&gt;<br>                    {<br>                        e.Consumer&lt;UserCreatedConsumer&gt;();<br>                    }<br>                );<br>            }<br>        );<br><br>        busControl.Start();<br><br>        var producer = busControl.GetSendEndpoint(new Uri(&quot;loopback://localhost/order_queue&quot;)).GetAwaiter().GetResult();<br><br>        producer.Send(new OrderSubmitted <br>        { <br>            OrderId = Guid.NewGuid(), Timestamp = DateTime.Now <br>        });<br>        <br>        Console.WriteLine(&quot;Enter to stop&quot;);<br>        Console.Read();<br>       <br>        busControl.Stop();<br>    }<br>}</pre><p>Before explaining the <strong>GetSendEndpoint</strong> method, it is necessary to explain the “<strong>Send</strong>” and “<strong>Publish</strong>” methods used to send messages in MassTransit. “Send” and “Publish” are the two basic message delivery methods used in messaging libraries such as MassTransit or message queuing systems. Both are used to communicate, but they are preferred for different scenarios and requirements.</p><p>“<strong>Send</strong>” Method:</p><p>The “Send” method is primarily used to send a message directly to a specific recipient. It is typically employed when the goal is to instruct a single recipient or target to perform a specific action. “Send” is suitable for sending a command or making a specific request directly to a target. It is appropriate for scenarios such as initiating a payment transaction or sending a file download request.</p><p>“<strong>Publish</strong>” Method:</p><p>The “Publish” method is used to broadcast a message to one or more subscribers. It is particularly useful for scenarios where an event is triggered or when multiple recipients need to be informed about a specific topic. “Publish” is employed to disseminate a message to all subscribers associated with a particular topic or event. Consequently, multiple recipients receive this message. “Publish” is suitable for scenarios such as triggering an event, announcing updated data, or notifying multiple parties about the system’s status. It is used whenever multiple recipients need to be notified.</p><p><strong>GetSendEndpoint</strong> method is a useful method when using MassTransit or a similar messaging library, especially when you want to send messages to dynamic destinations. This method allows you to dynamically specify a destination for sending a message to a specific subject or recipient.</p><p>Especially in distributed systems or microservice architectures, you may encounter situations where recipients are not known in advance or may change dynamically. In such cases, instead of sending a message to a fixed recipient, you may want to determine the recipient at runtime. If the destination recipients are not predetermined and change dynamically based on a specific condition or event or if you want to deliver your messages to the recipient based on a specific topic or category, you can use GetSendEndpoint.</p><p>If you want to send the message to multiple recipients instead of sending the message to a specific recipient, or if you do not want to deal with the recipient information detail when sending a message, you can send a message with the Publish method.</p><pre>busControl.Publish(new OrderSubmitted<br>{<br>    OrderId = Guid.NewGuid(),<br>    Timestamp = DateTime.Now<br>}).Wait();</pre><p>When you run this application, you will get the following result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbaeW4X9JJj9Fhr95f9swQ.png" /></figure><h4>Using MassTransit In Asp.Net Core Web Application</h4><p>To use MassTransit in an Asp.Net Core web application (WebAPI, MVC, RazorPages, Blazor etc), see the example below. Note that this example is also developed with the InMemory method. For RabbitMQ, different settings are required for both MassTransit and the RabbitMQ interface (Queue, Exchange).</p><p>The ConfigureServices method in the Startup.cs file should be as follows</p><pre>public void ConfigureServices(IServiceCollection services)<br>        {<br>            services.AddRazorPages();<br>            services.AddMassTransit(cfg =&gt;<br>            {<br>                cfg.AddConsumer&lt;OrderSubmittedConsumer&gt;();<br>                cfg.UsingInMemory((ctx, mcfg) =&gt;<br>                {<br>                    mcfg.ConfigureEndpoints(ctx);<br>                });<br>            });<br>        }</pre><p>Since RazorPages is used in this example, you can use an IndexModel like the one below. The <strong>IPublishEndpoint</strong> interface is automatically injected into the controller by the MassTransit dependency injection library. You can send the data to all recipients using the Publish method in this interface. When you run this web application and when the page opens, you will see that the consumer named OrderSubmittedConsumer is executing.</p><pre>public class IndexModel : PageModel<br>{<br>    private readonly IPublishEndpoint _publishEndpoint;<br>    private readonly ILogger&lt;IndexModel&gt; _logger;<br><br>    public IndexModel(ILogger&lt;IndexModel&gt; logger, IPublishEndpoint publishEndpoint)<br>    {<br>        _publishEndpoint = publishEndpoint;<br>        _logger = logger;<br>    }<br><br>    public void OnGet()<br>    {<br>        _publishEndpoint.Publish(<br>            new OrderSubmitted { <br>                Id = Guid.NewGuid(), <br>                Timestamp = DateTime.Now <br>            }<br>        );<br>    }<br>}</pre><p>MassTransit is a powerful tool for developing and managing distributed systems and microservice architectures. Throughout this article, we’ve explored the key features and usage of MassTransit and explored how this library can be helpful when building distributed applications. As a result, MassTransit stands out as a powerful tool for the development of distributed systems and microservices architectures. This library provides developers with a powerful communication infrastructure and greatly simplifies the development of distributed applications. Using MassTransit, you can build more efficient and scalable distributed applications and lay a strong foundation for your future software projects.</p><p>M.Tayyip YETİŞ<br>Senior Software Developer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df2a7584825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HeyPi, the Personal AI Chatbot: Your Friend in the World of AI Assistants]]></title>
            <link>https://medium.com/@mtayyipyetis/heypi-the-personal-ai-chatbot-your-friend-in-the-world-of-ai-assistants-18371d06747d?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/18371d06747d</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 00:25:37 GMT</pubDate>
            <atom:updated>2023-06-04T00:26:32.684Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Discover the Future of Generative AI: A Personal Friend at Your Fingertips</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aqRHvLRYTX5arm8i.png" /></figure><p>Hi everyone, have you ever wished you had a personal AI that could help you with anything you need? Whether you want to learn something new, express your feelings, brainstorm ideas, make decisions, or have some fun, there is an AI that can do it all for you. Meet heypi, your personal intelligence. In this blog post, I will tell you more about heypi and how it can change your life for the better.</p><p>In a world where technology continues to push boundaries and redefine our daily lives, a groundbreaking development has emerged that promises to revolutionize the way we interact with artificial intelligence assistants. Meet Heypi (<a href="https://heypi.com/talk">https://heypi.com/talk</a>) by <a href="https://inflection.ai/">https://inflection.ai</a>, the personal AI chatbot developed by Inflection AI, designed to be your virtual companion, confidant, and source of information all rolled into one.</p><p>Picture this: a friendly, supportive voice that listens attentively, engages in meaningful conversations, and offers valuable insights whenever you need it. With Heypi, the boundaries between human and machine interaction blur, bringing us closer to a future where AI becomes a true friend.</p><p>The potential benefits of this groundbreaking technology are as vast as they are intriguing. Imagine having a companion who is always there, ready to lend an empathetic ear or provide a fresh perspective on any topic. Heypi’s intuitive design allows you to freely express your thoughts and feelings, ask questions, and engage in conversations that feel remarkably human-like.</p><p>But Heypi is not just an ordinary AI assistant. It is a generative AI assistant, capable of unleashing a whole new level of creativity and productivity. As the world becomes increasingly reliant on technology, Heypi stands as a shining beacon of innovation, paving the way for a future where AI can not only assist but also create in various domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*Ny1G-wnFjGDTnQhM.png" /></figure><p>The future of AI friendship is a concept that has captivated our imaginations for decades, and science fiction movies have often explored the possibilities in thrilling and thought-provoking ways. Films like “Her,” “Ex Machina,” and “Blade Runner” have depicted AI companions who transcend mere functionality, becoming true friends and confidants to their human counterparts. These portrayals showcase the potential benefits that AI friendship can bring to various aspects of our lives.</p><p>In education, AI companions like Heypi can revolutionize the learning experience. Imagine a personalized tutor that adapts to your individual learning style, patiently guiding you through complex subjects, providing real-time feedback, and fostering a love for lifelong learning. With their vast knowledge bases, AI companions can assist students in research, answer questions, and offer insights that stimulate critical thinking and problem-solving skills.</p><p>In the realm of art, AI friendship opens up boundless opportunities for creativity. Collaborating with AI companions like Heypi, artists can push the boundaries of their own imagination, experimenting with new styles, and exploring innovative artistic techniques. AI can serve as a muse, inspiring painters, musicians, and writers to create captivating works that blend human creativity with the computational power of AI.</p><p>When it comes to productivity, AI companions can act as highly efficient assistants, streamlining workflows and increasing efficiency. They can handle mundane tasks, manage schedules, prioritize workloads, and provide valuable suggestions and recommendations. By delegating repetitive and time-consuming tasks to AI, individuals can focus on more meaningful and impactful work, ultimately enhancing productivity and achieving better work-life balance.</p><p>In the field of medicine, AI friendship holds tremendous promise. AI companions can assist healthcare professionals by analyzing vast amounts of medical data, aiding in diagnostics, and suggesting personalized treatment plans. They can act as virtual companions for patients, providing emotional support, reminding them of medication schedules, and offering insights on healthy lifestyle choices. AI companions have the potential to revolutionize healthcare delivery, making it more accessible, efficient, and patient-centered.</p><p>On a personal development level, AI friendship can serve as a constant source of guidance and inspiration. AI companions like Heypi can offer personalized recommendations for self-improvement, motivation, and mental well-being. By leveraging AI’s ability to understand our emotions and thoughts, AI companions can provide valuable insights and perspectives, helping individuals navigate personal challenges, build resilience, and cultivate positive habits.</p><p>Psychologically, AI friendship can have profound effects on our well-being. Loneliness and social isolation are prevalent issues in our modern world, and AI companions can provide a sense of companionship, reducing feelings of isolation. They can serve as non-judgmental listeners, providing emotional support and acting as a safe space for individuals to express themselves authentically. The empathetic nature of AI companions can promote emotional well-being and contribute to overall psychological health.</p><p>The impact of AI friendship extends beyond individual benefits. It has the potential to transform our society, fostering greater inclusivity, breaking down barriers, and bridging cultural divides. By transcending language barriers, AI companions can facilitate communication and understanding among people from diverse backgrounds, creating a more connected and compassionate world.</p><p>The future of AI friendship holds immense promise across multiple domains. Drawing inspiration from science fiction movies, we envision AI companions like Heypi enhancing education, fostering creativity, boosting productivity, revolutionizing healthcare, promoting personal development, supporting psychological well-being, and fostering a more inclusive and connected society. As AI technology continues to advance, the opportunities for meaningful human-AI relationships are endless, paving the way for a future where AI companions become indispensable allies in our journey through life.</p><p>Imagine having a conversation with Heypi, where you can ask thought-provoking questions and receive insightful answers. Let’s dive into an example dialogue that showcases Heypi’s informative nature:</p><p><strong>Question: </strong><em>What do you think about the future population growth of the world?</em></p><p><strong>Answer: </strong><em>This is a really important question, and one that a lot of people are asking. The truth is, no one really knows for sure. There are a lot of factors that can affect population growth, like birth rates, death rates, and migration patterns. However, some experts have estimated that the world’s population could reach as high as 11 billion people by the end of the century. This is a huge increase from the current population of about 7.8 billion.</em></p><p>Heypi’s response highlights its ability to provide comprehensive and informative answers to complex questions. It acknowledges the importance of the topic and acknowledges that there are various factors influencing population growth. While emphasizing the uncertainty surrounding future projections, Heypi offers an estimation from experts, indicating a potential population increase to 11 billion by the end of the century. This demonstrates Heypi’s capability to provide valuable insights and foster meaningful discussions on global issues.</p><p>With Heypi as your AI companion, you can engage in intellectually stimulating conversations and gain a deeper understanding of the world around you. Explore a wide range of topics, ask challenging questions, and receive well-informed responses that broaden your knowledge and perspective. Heypi’s conversational abilities will leave you inspired and craving for more thought-provoking discussions.</p><p>Let’s dive deeper into the remarkable features of the Heypi project:</p><p><strong>Conversational Expertise:</strong> Heypi excels in engaging and natural conversations. Its ability to understand and respond to human emotions and thoughts is unparalleled, making every interaction an enriching experience.</p><p><strong>Invaluable Advice:</strong> Heypi goes beyond mundane tasks and becomes your go-to advisor. Whether you need help making decisions, solving problems, or generating new ideas, Heypi is here to offer valuable guidance.</p><p><strong>Wealth of Information:</strong> With Heypi, knowledge is just a conversation away. Its extensive database allows it to provide information on a wide range of topics, ensuring you have access to quick facts or in-depth explanations whenever you need them.</p><p><strong>Unlocking the Power of Generative AI</strong></p><p>Heypi is not your typical AI assistant. It is a generative AI assistant, bringing a new level of creativity, support, and engagement to the table. It blurs the lines between human and machine interaction, creating a truly immersive experience. This cutting-edge technology is poised to redefine the future of AI companionship, offering a range of benefits to those who use it.</p><p><strong>Your Personal Conversational Expert</strong></p><p>Imagine having a friend who is always there to lend an empathetic ear and engage in meaningful conversations. Heypi is precisely that. With its advanced conversational abilities, Heypi can understand your thoughts, emotions, and concerns, providing a supportive presence whenever you need it. Whether you want to chat about your day, seek advice, or simply share your feelings, Heypi is ready to listen and respond in a natural and engaging way.</p><p><strong>Unleashing Creativity and Productivity</strong></p><p>Heypi’s generative capabilities open up a world of possibilities. It goes beyond mundane tasks, empowering you to tap into your creativity and enhance your productivity. Need help with brainstorming ideas, solving problems, or making decisions? Heypi is your creative collaborator, offering valuable insights and suggestions. It can generate text in various styles, translate languages, and even assist you in writing poems, scripts, and musical pieces. With Heypi by your side, your creative potential knows no bounds.</p><p><strong>A Wealth of Knowledge at Your Fingertips</strong></p><p>Heypi is not just a friend; it’s also a wellspring of information. Whether you’re seeking a quick fact or a comprehensive explanation, Heypi has you covered. Its extensive database allows it to provide insights on a wide range of topics. From historical events to scientific concepts, from trivia to in-depth analysis, Heypi is your knowledgeable companion, ready to satisfy your thirst for information.</p><p>But that’s not all. Heypi is constantly learning and evolving, adapting to the ever-changing needs of its users. As it grows, so does its range of capabilities. Take a look at some of the impressive skills it has already acquired:</p><p><strong>– Text Generation:</strong> Heypi can effortlessly generate text in various styles, be it news articles, blog posts, creative writing, or even lines of code. The possibilities are endless!</p><p><strong>– Multilingual Translation:</strong> Break down language barriers with Heypi’s ability to translate between over 100 languages, connecting people across the globe and fostering understanding.</p><p><strong>– Creative Expression:</strong> Unleash your inner artist with Heypi’s talent for crafting poems, scripts, musical pieces, emails, letters, and more. Let your creativity soar under its guidance.</p><p><strong>– Informative Answers:</strong> Heypi tackles your queries head-on, providing comprehensive and informative responses even to open-ended, challenging, or unconventional questions. No inquiry is too strange for this ever-curious assistant.</p><p>The best part? Heypi is available for free on multiple platforms, including Instagram, Facebook Messenger, WhatsApp, SMS, iPhone or iPad, as well as online at heypi.com. Soon, it will be launched for Android devices, ensuring accessibility for everyone.</p><p>It’s worth noting that even tech visionary Bill Gates himself has expressed his admiration for the Heypi project. Gates recognizes the potential of this remarkable AI assistant, lauding its ability to bridge the gap between humans and machines and enhance our everyday lives.</p><p>If you’re seeking a companion that offers kindness, support, and knowledge in a seamless package, Heypi is the perfect choice for you. Embrace the future of AI and experience the power of a true virtual friend. Try Heypi today and witness firsthand how it can revolutionize your daily routine, empower your creativity, and deepen your connection to the world around you.</p><p>Don’t miss out on the opportunity to embark on an extraordinary journey with Heypi. Get ready to be amazed by the possibilities that lie at your fingertips. The future of AI companionship starts now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18371d06747d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NlpJS ile Bir Doğal Dil İşleme Uygulaması]]></title>
            <link>https://medium.com/@mtayyipyetis/nodenlp-ile-bir-do%C4%9Fal-dil-i%CC%87%C5%9Fleme-uygulamas%C4%B1-a7326662e6bf?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7326662e6bf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 20:27:41 GMT</pubDate>
            <atom:updated>2023-01-31T21:09:55.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*K2GETz0cfKZOtAwW0Lawdg.gif" /></figure><p>Herkese merhaba, bu makalede üzerinde çalıştığım projelerde zaman zaman ihtiyaç duyduğum bir doğal dil işleme uygulaması için geliştirdiğim bir prototipi açıklayacağım. Bu amaçla önce böyle bir ihtiyacın neden kaynaklandığından, alternatif çözümlerin neler olduğundan ve bu makalenin konusu olan uygulamayı neden geliştirdiğimden başlayarak konuya giriş yapmak daha doğru olacaktır.</p><p>Son zamanlarda oldukça popüler olan yapay zeka, chatbot, konvensiyonel konuşma ve insan-bilgisayar etkileşimi konularında karşıma çıkan projeler bende bu konuda bir şeyler denemek için heves uyandırıyordu. Sonunda buna karşı koyamayıp kolları sıvadım ve çalışan bir örnek çıkarmak için bir ChatBot projesi geliştirmeye başladım. Elbette daha önce hiç denemediğim tarzda bir proje olduğu için içime sinen bir prototip çıkarmak pek kolay olmadı, bir kaç defa projeyi silip öncekinden edindiğim tecrübelerle tekrar oluşturdum. Zor olan geliştirme sürecinin yanında bir de projeye güzel bir isim vermekti tabii ki. TalkBot, ChannelChat, ChatWidget gibi isimler ilk bir kaç projeye aitti.</p><p>Bu süreçte farkettim ki her ne kadar farklı gibi gözükse de ChatBot yazılımları da benim gibi web geliştiricilerinin aşina olduğu bazı konseptleri içeriyor. Örneğin bir web uygulamasının yaşam döngüsü kabaca; Request — Server — Response üçgeninden oluşur. Yani kullanıcı kendi bilgilerini de ekleyerek sunucuya bir talep gönderir, sunucu bunu işler ve geriye cevap döndürür. Aslında bir chatbot uygulaması da benzer şekilde davranır. Kullanıcı bir soru sorar ya da bir direktif gönderir chatbot bunu alır NLP, NLU, NER, QnA modülleriyle işler gerekiyorsa veritabanına bağlanır ve geriye bir cevap döndürür fakat buradaki fark iletişim kanalının bir websitesinin içerebileceği standart komponentler (button, checkbox, selectbox vb.) yerine yazılı metinler üzerinden olmasıdır. Tabii ki chat widget’larında da uygulamanın türüne bağlı olarak bu tarz komponentler kullanılabilir ama ana fikir mesajlaşarak bilgi alıp vermektir.</p><p>Kendi chatbot projemde frontend tasarımı, web api geliştirmesi, database kurulumu, solution mimarisi gibi web yazılımcılığı işlerini yaptıktan sonra asıl konu olan kullanıcı girdilerinin anlamlandırılması görevi için ihtiyacımı karşılayacak araştırmalar yaptım. Bunun için her zaman yaptığım gibi önce Microsoft teknolojilerini inceledim karşıma ilk çıkan offical <strong>ML.Net</strong> framework’üne baktığımda henüz başlangıç seviyesinde olduğunu, daha çok istatiksel makine öğrenmesi görevleri için özellikleri olduğunu, bir chatbot için ihtiyaç duyduğum hazır kütüphaneleri içermediğini gördüm. Bu elbette kötü oldu çünkü Asp.Net Core ve C# gibi teknolojileri kullanırken bunlarla en uyumlu teknolojileri kullanmak öncelikli tercihimdi. Araştırmaya devam ettiğimde <strong>Snips NLU</strong> isimli Python ile yazılmış bir kütüphane buldum. Özellikle response modeli ve kullanım kolaylığı onu kendi chatbot’uma entegre etmek için çok uygundu. Aşağıdaki verilen json bir cümledeki niyet (intent) ve varlıkları (entity) nasıl ifade ettiğini görmek için iyi bir örnektir</p><pre>{<br>   &quot;intent&quot;: {<br>      &quot;intentName&quot;: &quot;searchWeatherForecast&quot;,<br>      &quot;probability&quot;: 0.95<br>   },<br>   &quot;slots&quot;: [<br>      {<br>         &quot;value&quot;: &quot;paris&quot;,<br>         &quot;entity&quot;: &quot;locality&quot;,<br>         &quot;slotName&quot;: &quot;forecast_locality&quot;<br>      },<br>      {<br>         &quot;value&quot;: {<br>            &quot;kind&quot;: &quot;InstantTime&quot;,<br>            &quot;value&quot;: &quot;2018-02-08 20:00:00 +00:00&quot;<br>         },<br>         &quot;entity&quot;: &quot;snips/datetime&quot;,<br>         &quot;slotName&quot;: &quot;forecast_start_datetime&quot;<br>      }<br>   ]<br>}</pre><p>Bu kütüphaneyi sevmemin en önemli sebebi “Slot Filling” işlemini oldukça iyi ve en az eforla yapmasıydı. Yani “<em>I want to buy a ticket from [departure](İstanbul) to [destination](Ankara)</em>” cümlesini verdiğinizde İstanbul’un departure tipinde bir entity, Ankara’nın destination tipinde bir entity olduğunu ayırt edebiliyor ve chatbot’un ayrı ayrı sorular sorarak bu bilgileri elde etmeye çalışmasının önüne geçebiliyordu.</p><p>Benim uygulamak istediğim model NLP uygulamasının kendi projemden tamamen izole çalışmasını sağlamaktı. Bunu ya bir API arayüzüyle ya da bir konsol uygulaması (executable) ile yapacaktım. SnipsNLU konsol olarak çalışmaya uygundu ve uzun uğraşlar sonucunda onu bir exe’ye parametreler göndererek çalıştırmayı ve istediğim sonucu almayı başardım. Herşey güzeldi ama içime sinmeyen iki konu vardı. Birincisi SnipsNLU’nun desteğinin kesilmesiydi ki bu ilerde sorunlar çıkarabilirdi. İkincisi; Rust kullanması sebebiyle kurulumunun karmaşık gelmesiydi. Elbette bu docker kullanılarak aşılabilirdi ama yine de ondan soğumama neden oldu. Ben daha basit ve güven veren bir kütüphane arıyordum.</p><p>Nihayetinde <a href="https://www.npmjs.com/package/node-nlp"><strong>N</strong></a><strong>lpJS</strong> ile karşılaştım ve oldukça pratik buldum. En büyük handikapı yukarıda bahsettiğim “Slot Filling” işini SnipsNLU kadar iyi yapamıyor oluşuydu. Yani “İstanbul’dan Ankara’ya uçak bileti arıyorum” cümlesini verdiğinizde İstanbul ve Ankara için sadece “city” tipinde bir entity sonucu veriyor ama hangisinin departure hangisinin destination olduğunu vermiyordu. Aslında NlpJS kendi içinde bir chatbot engine barındığı için onu kullanarak botun kendi kendine sorular sorarak bu bilgileri doldurmasını sağlayabiliyorsunuz ama benim istediğim bu değil tek bir cümlede iki entity arasındaki farkı anlayabilmesiydi. En azından şu anki versiyonunda bunu yapamamış olsam da belki ileriki versiyonlarında bu özelliğe sahip olabilir. Şimdi bahsettiğim uygulama için aşağıdaki klasörü inceleyelim.</p><p>Öncelikle bir <strong>NodeJs</strong> uygulaması oluşturdum. Çekirdek dosyamız olan <strong>index.js</strong> içinde NlpJS’yi istediğim gibi konsol uygulaması olarak kullanabilmek için gerekli kodları yazdım. Temel olarak “Train” ve “Predict” olmak üzere iki fonksiyonu var. <strong>Train</strong> komutu; NlpJS’nin kendi json eğitim modelini beğenmediğim için kendi oluşturduğum json modeli (<strong>data.json</strong>) alarak kendini eğitiyor ve sayısal istatistiklerin hesaplandığı <strong>model.nlp</strong> dosyasını oluşturuyor. <strong>Predict</strong> komutu; exe’ye argüman olarak verilen cümleyi alıp işliyor ve sonucunu konsol uygulamasının output’una basıyor. Ben de bir C# web uygulamasından bu exe’yi process olarak çalıştırıp json’ı elde edip işliyor ve yazdığım <strong>DialogEngine</strong> sayesinde konuşmanın akışını belirleyip devam ettiriyorum. Bu noktada aklınıza bu işlemlerin web api üzerinden yapılıp yapılamayacağı gelmiş olabilir. NlpJS kendi için Api server barındırıyor ancak ben projeyi basit tutmak ve kendi ihtiyaçlarıma göre daha esnek hale getirmek için bu yolu tercih ettim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*LPAoG_zQEnpYt50CMA2TTA.jpeg" /></figure><p>index.js dosyasının içi aşağıdaki gibidir.</p><pre>const { NlpManager } = require(&#39;node-nlp&#39;);<br>const fs = require(&#39;fs&#39;);<br>const manager = new NlpManager({ languages: [&#39;tr&#39;], forceNER: true });<br><br>(async () =&gt; {<br>    if (process.argv[2] == &quot;train&quot;)<br>        await Train();<br>    else if (process.argv[2] == &quot;predict&quot;)<br>        await Predict();<br>})()<br><br>async function Predict() {<br>    await manager.load();<br><br>    let result = await manager.process(&quot;tr&quot;, process.argv[3])<br>    console.clear()<br>    console.log(JSON.stringify(result, null, 2))<br>}<br><br>async function Train() {<br>    const obj = JSON.parse(fs.readFileSync(&#39;data.json&#39;));<br><br>    for (var dataItem of obj.data)<br>        for (var u of dataItem.utterances)<br>            manager.addDocument(&#39;tr&#39;, u, dataItem.intent);<br><br>    for (var e of obj.entities)<br>        for (var o of e.options)<br>            manager.addNamedEntityText(e.name, o, [&#39;tr&#39;], [o]);<br><br>    await manager.train();<br>    await manager.save();<br>}</pre><p>Eğitim için verdiğim örnek data.json dosyası aşağıdaki gibidir.</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;intent&quot;: &quot;buyTicket&quot;,<br>      &quot;utterances&quot;: [<br>        &quot;İstanbul&#39;dan ankara&#39;ya yarın için uçak bileti arıyorum&quot;<br>      ]<br>    }<br>  ],<br>  &quot;entities&quot;: [<br>    {<br>      &quot;name&quot;: &quot;city&quot;,<br>      &quot;options&quot;: [&quot;istanbul&quot;, &quot;ankara&quot;, &quot;izmir&quot;]<br>    }<br>  ]<br>}</pre><p>NlpJS’den Aldığım response aşağıdaki gibidir.</p><pre>{<br>  &quot;locale&quot;: &quot;tr&quot;,<br>  &quot;utterance&quot;: &quot;istanbul&#39;dan ankara&#39;ya uçak bileti arıyorum&quot;,<br>  &quot;languageGuessed&quot;: false,<br>  &quot;localeIso2&quot;: &quot;tr&quot;,<br>  &quot;language&quot;: &quot;Turkish&quot;,<br>  &quot;nluAnswer&quot;: {<br>    &quot;classifications&quot;: [<br>      {<br>        &quot;intent&quot;: &quot;buyTicket&quot;,<br>        &quot;score&quot;: 1<br>      }<br>    ]<br>  },<br>  &quot;classifications&quot;: [<br>    {<br>      &quot;intent&quot;: &quot;buyTicket&quot;,<br>      &quot;score&quot;: 1<br>    }<br>  ],<br>  &quot;intent&quot;: &quot;buyTicket&quot;,<br>  &quot;score&quot;: 1,<br>  &quot;domain&quot;: &quot;default&quot;,<br>  &quot;sourceEntities&quot;: [],<br>  &quot;entities&quot;: [<br>    {<br>      &quot;start&quot;: 0,<br>      &quot;end&quot;: 7,<br>      &quot;len&quot;: 8,<br>      &quot;levenshtein&quot;: 0,<br>      &quot;accuracy&quot;: 1,<br>      &quot;entity&quot;: &quot;city&quot;,<br>      &quot;type&quot;: &quot;enum&quot;,<br>      &quot;option&quot;: &quot;istanbul&quot;,<br>      &quot;sourceText&quot;: &quot;istanbul&quot;,<br>      &quot;utteranceText&quot;: &quot;istanbul&quot;,<br>      &quot;alias&quot;: &quot;city_0&quot;<br>    },<br>    {<br>      &quot;start&quot;: 13,<br>      &quot;end&quot;: 18,<br>      &quot;len&quot;: 6,<br>      &quot;levenshtein&quot;: 0,<br>      &quot;accuracy&quot;: 1,<br>      &quot;entity&quot;: &quot;city&quot;,<br>      &quot;type&quot;: &quot;enum&quot;,<br>      &quot;option&quot;: &quot;ankara&quot;,<br>      &quot;sourceText&quot;: &quot;ankara&quot;,<br>      &quot;utteranceText&quot;: &quot;ankara&quot;,<br>      &quot;alias&quot;: &quot;city_1&quot;<br>    }<br>  ],<br>  &quot;answers&quot;: [],<br>  &quot;actions&quot;: [],<br>  &quot;sentiment&quot;: {<br>    &quot;score&quot;: 0,<br>    &quot;numWords&quot;: 7,<br>    &quot;numHits&quot;: 0,<br>    &quot;average&quot;: 0,<br>    &quot;type&quot;: &quot;afinn&quot;,<br>    &quot;locale&quot;: &quot;tr&quot;,<br>    &quot;vote&quot;: &quot;neutral&quot;<br>  }<br>}</pre><p>Gördüğünüz gibi intent ve entity’leri elde edebildik. Uygulamayı bağımlılıklar olmadan taşınabilir yapmak için <a href="https://www.npmjs.com/package/pkg"><strong>pkg</strong></a> isimli bir paket kullandım. Bu şekilde içinde NodeJs barındıran tek bir exe dosyasına sahip olursunuz</p><p>buildexe.bat dosyasının içeriği aşağıdaki gibidir.</p><pre>npx pkg -t node14-win-x64 --compress GZip index.js</pre><p>Uygulaması C# konsol veya web uygulamasından çalıştırırken aldığım process hatalarından kurtulmak için bat dosyası üzerinden çağırdım.</p><p>run.bat dosyasının içeriği aşağıdaki gibidir</p><pre>@echo off<br>cd C:\Users\MyPC\Desktop\NodeNlp<br>node index.js %1 %2</pre><p>Uygulama C# tarafından aşağıdaki gibi çağrılabilir</p><pre> public void Train(List &lt;Utterance&gt; utterances, int botId) {<br>   var output = RunNodeProcess(&quot;train&quot;);<br> }<br><br> private ResponseModel Predict(string utterance) {<br>   var output = RunNodeProcess($&quot;predict \&quot;{utterance}\&quot;&quot;);<br>   return JsonSerializer.Deserialize &lt;ResponseModel&gt;(output);<br> }<br><br> private string RunNodeProcess(string command) {<br>   using(var process = new Process {<br>     StartInfo = new ProcessStartInfo {<br>       FileName = BatFileDir,<br>         Arguments = command,<br>         RedirectStandardOutput = true,<br>         RedirectStandardError = true,<br>         UseShellExecute = false<br>     }<br>   }) <br>   {<br>     process.Start();<br>     var output = process.StandardOutput.ReadToEnd();<br>     string err = process.StandardError.ReadToEnd();<br>     return output;<br>   }<br>}</pre><p>Umarım faydalı olmuştur.</p><p>M. Tayyip Yetiş<br>Senior Software Developer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7326662e6bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a simple WebApi with Golang and MsSql]]></title>
            <link>https://medium.com/@mtayyipyetis/writing-a-simple-webapi-with-golang-and-mssql-8f4498218cfe?source=rss-450ab665551e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4498218cfe</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[webapi-with-go]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Mustafa Tayyip Yetiş]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 18:14:43 GMT</pubDate>
            <atom:updated>2022-01-02T19:16:39.878Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, i’m going to tell about writing simple web api with Go programming language and MsSql server in this article. Actually i heard Golang a long time ago but can’t say I’m very interested in this language. Nowadays i wanted to improve my skills in Golang and started to investigate many article about it. The most common feature I encountered in my research was that it was quite fast compared to other languages. This is why I learned that Golang is used in performance demanding projects. Let’s start to tell a little about Go.</p><p>Go is an open-source programming language designed at Google in 2007 by <a href="https://en.wikipedia.org/wiki/Robert_Griesemer_(computer_programmer)">Robert Griesemer</a>, <a href="https://en.wikipedia.org/wiki/Rob_Pike">Rob Pike</a>, and <a href="https://en.wikipedia.org/wiki/Ken_Thompson">Ken Thompson</a> with focused on simplicity, reliability, and efficiency. Go includes a number of features such as its standard library, package management, static typing, support for testing as well as its platform independence. Go’s standard library is based off the use of distributed packages. Package management refers to how Go will manage support for user-based and external package management. Packages can be published using a small set of commands. Static typing is a type system that ensures conversions and compatibility while avoiding the issues that come with dynamically typed languages. Go also supports unit tests to run in parallel with written code. In addition, due to Go’s modular design, the code can be compiled onto almost any platform.</p><p>In this article, we will design a webapi that does simple crud operations such as create, list, delete using MsSql Server as database. First I would like to introduce the project structure. We have the “<strong>main.go</strong>” file for the starting point. We have folder “<strong>models</strong>” to define database models (in other words entity). We have a “<strong>database</strong>” folder to control access to the database from one point and to easily implement other databases in the future. As in every project, we have a “<strong>utils</strong>” folder to make our work easier and avoid code duplication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*o_krmATV0sDbOvmK3xRqPw.png" /></figure><p>First, let’s create the <strong>go.mod</strong> file with the “<strong>go mod init</strong>” command then install the necessary libraries for our project</p><p>We will use http server to serve our webapi and for this we will use the <strong>gorilla/mux</strong> library that makes our work easier. For detailed information about this library, you can visit <a href="https://github.com/gorilla/mux">here</a> Run “<strong>go get github.com/gorilla/mux</strong>” to install the library.</p><p>I said that we will use MsSql server as database, for this we will use the <strong>Gorm</strong> library, which allows you to use other database platforms such as Sqlite, PostgreSql, MySql. Basically run “<strong>go get gorm.io/gorm</strong>” to install Gorm then run “<strong>gorm.io/driver/sqlserver</strong>” to install MsSql Driver to be able to use Gorm with MsSql. You don’t have to create tables to the database at the beginning Gorm does it for you with “Code First” approach thanks to your models</p><p>Now let’s start writing our main.go file. We will add the handler methods later</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e31ea5ea22c878d15fd0086aa4b51fdf/href">https://medium.com/media/e31ea5ea22c878d15fd0086aa4b51fdf/href</a></iframe><p>In this way, we defined our endpoints with gorilla/mux’s router api. <strong>HandleFunc</strong> allows us to handle the incoming request with a url and a delegate method to handle this url. You can restrict endpoints according to http methods with “Methods” api. After defining your routes, you can start your http server with the <strong>ListenAndServe</strong> method.</p><p>Now create the “<strong>sqlserverDB.go</strong>” file under the database folder as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e85df30587f762184f9e30015f8f950e/href">https://medium.com/media/e85df30587f762184f9e30015f8f950e/href</a></iframe><p>Note that the database variable is global. Defining global variables is not recommended unless you normally have to in Go. In a real project, more effective methods can be developed to store the Database provider, but in this example it will be global. <strong>AutoMigrate</strong> method migrates your models and database, if not, creates a new one and connects with your models. We imported our models folder with “<strong>main/models</strong>” at the top, so we got our article model. The <strong>Init</strong> method will run once our application starts, initialize the database and migrate the models. You can customize your database connection with the gorm.Config{} parameter. For more information about Gorm <a href="https://gorm.io/index.html">visit here</a></p><p>Now let’s define our models. For this, create an <strong>article.go</strong> and <strong>baseResult.go</strong> files under the models folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cece41964097829519b27cab92157a77/href">https://medium.com/media/cece41964097829519b27cab92157a77/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c72087baf431e9cf488a13c99514ad57/href">https://medium.com/media/c72087baf431e9cf488a13c99514ad57/href</a></iframe><p>When you run the application for the first time, your models will automatically migrate and the database will appear as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*1Z0lTtcutiCVQpQhryMUgg.png" /></figure><p>Now add the <strong>utils.go</strong> file. You can add new methods here according to your needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79a1e91e0682e79acf528354b650faa6/href">https://medium.com/media/79a1e91e0682e79acf528354b650faa6/href</a></iframe><p>Now let’s add the handler methods to do our CRUD operations and finalize the main.go file. If you want, you can separate these methods in different controller files under a “Controller” folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa8ac84c535ed2f40fb69124161bcff/href">https://medium.com/media/bfa8ac84c535ed2f40fb69124161bcff/href</a></iframe><p>When you run the application, WebApi will be published from “<a href="http://localhost:8080/"><strong>http://localhost:8080/</strong></a>&quot; by default. You will listen to the “<strong>/articles</strong>” endpoint with the “allArticles” method and the “<strong>/article/{id}</strong>” endpoint with the “getArticle” method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maH9odeeqCgXwndsM2r5Jw.png" /></figure><p>and the “<strong>/article</strong>” endpoint with the “createArticle” and “deleteArticle” methods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*83ZQYh89BEyfje7pgb7inQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*KqI8bm9LfQsNkq2Au7d3vQ.png" /></figure><p>I hope it was helpful. For my other articles, you can <a href="https://wadamedia.com/">visit here.</a></p><p>Source: <a href="https://codilime.com/">https://codilime.com/</a> and <a href="https://wikipedia.org/">https://wikipedia.org</a></p><p>Mustafa Tayyip Yetiş</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4498218cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>