Postingan

Menampilkan postingan dari 2023

Node.js Telegram Bot API send an image with text

To send an image with text using the Telegram Bot API in Node.js, you can use the node-fetch library to make HTTP requests and the FormData module to handle multipart/form-data requests for uploading images. First, install the required modules: npm install node-fetch Here's an example code snippet to send an image with text using the Telegram Bot API: const fetch = require('node-fetch'); const FormData = require('form-data'); const BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'; const CHAT_ID = 'TARGET_CHAT_ID'; async function sendImageWithText() { const photoUrl = 'URL_TO_YOUR_IMAGE'; // Replace with the URL of your image const form = new FormData(); form.append('chat_id', CHAT_ID); form.append('photo', photoUrl); form.append('caption', 'Your text caption goes here'); try { const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendPhoto`, { method: 'POST', ...

Node.js schedule

To use node-schedule to execute a task every day at a specific time, you can create a schedule rule using the library's syntax. Here's an example that schedules a task to run every day at 2:30 PM: First, install node-schedule if you haven't already: npm install node-schedule Now, you can use the following code: const schedule = require('node-schedule'); // Schedule a task to run every day at 2:30 PM const dailyJob = schedule.scheduleJob('30 14 * * *', () => { // Your code here console.log('Task executed every day at 2:30 PM'); }); In the above code: '30 14 * * *' is a cron-like syntax specifying the schedule. It means the task will run when the minute is 30 and the hour is 14 (2 PM). The * in the other positions means "any" for the day of the month, month, day of the week, and year. Adjust the cron expression based on your preferred time. The first part represents the minute (0-59), the second part represent...

Node.js API from PHP

To call a Node.js API from PHP, you can use various methods such as cURL or Guzzle. Here's an example of how you can call a Node.js API from PHP using cURL: // URL of the Node.js API endpoint $url = 'http://localhost:3000/api'; // Replace this with your Node.js API URL // Data to be sent to the Node.js API $data = array( 'key1' => 'value1', 'key2' => 'value2' ); // Initialize cURL session $ch = curl_init($url); // Set the request method to POST curl_setopt($ch, CURLOPT_POST, 1); // Set the POST data curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set the return transfer to true curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); // Close the cURL session curl_close($ch); // Output the response echo $response; Make sure to replace the URL with the actual endpoint of your Node.js API and modify the $data array as per your API's requirements. Additionally, you can u...

Node.js select a MySQL database

To select a MySQL database and insert data into a table within that database using Node.js, you need to modify the previous code by specifying the database in the connection and using the selected database in the SQL query. Here's an example: const mysql = require('mysql'); // Create a connection to the database const connection = mysql.createConnection({ host: 'localhost', // Replace with your host name user: 'yourusername', // Replace with your database username password: 'yourpassword', // Replace with your database password database: 'yourdatabase', // Replace with your database name }); // Connect to the database connection.connect((err) => { if (err) { console.error('Error connecting to the database: ' + err.stack); return; } console.log('Connected to the database as id ' + connection.threadId); // Select the database connection.query('USE yourdatabase', (error) => { if ...

Node.js web service using Express

To create a Node.js web service using Express that handles POST requests with parameters, you can follow these steps: 1. Initialize a new Node.js project: mkdir myWebService cd myWebService npm init -y 2. Install Express and Body-Parser: npm install express body-parser 3. Create an index.js file with the following code: // index.js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; // Use body-parser middleware app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Handling POST request with parameters app.post('/api', (req, res) => { const { param1, param2 } = req.body; res.send(`Received POST data - Parameter 1: ${param1}, Parameter 2: ${param2}`); }); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); 4. Run the service using the following command: node index.js...

OTP (One Time Password) functionality in PHP with an expiration time

To implement OTP (One Time Password) functionality in PHP with an expiration time, you can use the $_SESSION variable to store the OTP and its creation time. Here's an example of how to generate an OTP with an expiration time: // Function to generate a random OTP function generateOTP($length = 6) { $characters = '0123456789'; $otp = ''; $max = strlen($characters) - 1; for ($i = 0; $i In this example, the generateOTP function generates a 6-digit random OTP. The isOTPValid function checks whether the provided OTP matches the stored OTP and whether the expiration time has passed. Adjust the expirationTime variable as needed, and make sure to handle the expiration logic according to your application's requirements.

Node.js Telegram BOT retrieve data from API

To retrieve data from an API and send it via a Telegram bot using Node.js, you can combine the axios library for API requests with the node-telegram-bot-api library for sending messages. Below is an example that fetches data from an API and then sends it as a message using a Telegram bot: const TelegramBot = require('node-telegram-bot-api'); const axios = require('axios'); // Telegram Bot API token (replace this with your own token) const token = 'YOUR_TELEGRAM_BOT_API_TOKEN'; const bot = new TelegramBot(token, { polling: true }); // API endpoint to fetch data from const apiUrl = 'YOUR_API_ENDPOINT'; // Replace with your API endpoint // Client ID and Client Secret for authentication const clientId = 'YOUR_CLIENT_ID'; const clientSecret = 'YOUR_CLIENT_SECRET'; // Function to fetch data from the API const fetchDataFromAPI = async () => { try { const response = await axios.get(apiUrl, { headers: { 'Client-...

Node.js Telegram BOT

To send a message to a user or a group chat using the Telegram Bot API in Node.js, you can use the node-telegram-bot-api library. Below is an example of how to send a message to a specific chat using the library: const TelegramBot = require('node-telegram-bot-api'); // Telegram Bot API token (replace this with your own token) const token = 'YOUR_TELEGRAM_BOT_API_TOKEN'; // ID of the chat you want to send a message to const chatId = 'CHAT_ID'; // Replace with the actual chat ID // Create a bot that uses 'polling' to fetch new updates const bot = new TelegramBot(token, { polling: true }); // Function to send a message const sendMessage = (chatId, message) => { bot.sendMessage(chatId, message) .then(() => { console.log('Message sent successfully'); }) .catch((error) => { console.error('Error sending message:', error.message); }); }; // Example of sending a message sendMessage(chatId, 'Hello...

Integrate TCPDF into a Yii2 Advanced application

To integrate TCPDF into a Yii2 Advanced application, follow these steps: Step 1: Install TCPDF via Composer: In the root directory of your Yii2 Advanced application, run the following command: composer require tecnickcom/tcpdf Step 2: Create a new php file or use an existing one to generate PDFs. Here is an example of how to use TCPDF in a Yii2: $rootPath = Yii::getAlias('@vendor'); require_once $rootPath . '/autoload.php'; require_once $rootPath . '/tecnickcom/tcpdf/tcpdf.php'; $pdf = new TCPDF(); $pdf->SetCreator('Your Name'); $pdf->SetAuthor('Your Name'); $pdf->SetTitle('Sample PDF'); $pdf->SetSubject('Sample PDF'); $pdf->SetKeywords('TCPDF, PDF, Sample'); $pdf->AddPage(); $pdf->SetFont('times', 'B', 16); $pdf->Cell(40, 10, 'Hello World!'); header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="example.p...

How to download an image from a URL using file_get_contents in PHP, resize the image using the GD library, and then encode the resized image as BASE64.

Here's an example of how to download an image from a URL using file_get_contents in PHP, resize the image using the GD library, and then encode the resized image as BASE64.php // URL of the image you want to download and resize $imageUrl = 'https://example.com/path/to/your/image.jpg'; // Download the image using file_get_contents $imageData = file_get_contents($imageUrl); if ($imageData === false) { echo 'Failed to download the image.'; exit; } // Create an image resource from the downloaded image data $originalImage = imagecreatefromstring($imageData); if ($originalImage === false) { echo 'Failed to create image resource.'; exit; } // Get the original image dimensions $originalWidth = imagesx($originalImage); $originalHeight = imagesy($originalImage); // Calculate the new dimensions for the resized image $newWidth = 200; // Replace with the desired width for the resized image $newHeight = ($originalHeight / $originalWidth) * $newWi...

Create token using JSON Web Tokens (JWT)

To create a web token using JSON Web Tokens (JWT) in a web application, you can use libraries available in your programming language. Here, I'll demonstrate how to create a JWT in PHP using the "firebase/php-jwt" library. 1. Install the "firebase/php-jwt" library: Use Composer to install the PHP-JWT library. If you don't have Composer installed, you can download it from https://getcomposer.org/. Run the following command in your project's root directory to install the library: composer require firebase/php-jwt 2. Create a PHP script to generate a JWT: Create a new PHP file (e.g., generate_jwt.php) and add the following code: require __DIR__ . '/vendor/autoload.php'; // Include the composer autoloader use \Firebase\JWT\JWT; use \Firebase\JWT\Key; // Replace these values with your own secret key and any other claims you want to include in the token $secretKey = 'your_secret_key'; $issuedAt = time(); $expirationTime = $issued...

Add these security headers to your website

The X-Frame-Options, Strict-Transport-Security, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, and Content-Security-Policy headers are security-related HTTP headers that help enhance the security of web applications. To add these security headers to your website, you can use the .htaccess file for Apache web servers or the server configuration for other web servers. Here's how to set each header: 1. X-Frame-Options: The X-Frame-Options header helps prevent clickjacking attacks by controlling whether your website can be embedded in an iframe on another domain. For Apache (using .htaccess): Header always set X-Frame-Options "SAMEORIGIN" 1. Strict-Transport-Security (HSTS): The Strict-Transport-Security header enforces the use of HTTPS by instructing the browser to only access the website over a secure (HTTPS) connection. For Apache (using .htaccess): Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" ...

WhatsApp Web login QR code in an HTML page using whatsapp-web.js

Gambar
To display the WhatsApp Web login QR code in an HTML page using whatsapp-web.js in Windows, you can follow these steps: 1. Install the required dependencies: npm install express qrcode whatsapp-web.js 2. Create a new file named api-browser.js and add the following code: const express = require('express'); const qrcode = require('qrcode'); const { Client } = require('whatsapp-web.js'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.get('/qrcode', async (req, res) => { const client = new Client(); client.on('qr', (qr) => { qrcode.toDataURL(qr, (err, url) => { if (err) { console.error('Error generating QR code:', err); res.sendStatus(500); } else { res.send(` `); } }); }); await client.initialize(); }); app.listen(port, () => { console.log(`Server is running on ht...

Run a Node.js script as a background process

To run a Node.js script as a background process, you can use various methods depending on your specific requirements and the operating system you are using. Here are a few options: 1. Using a process manager (e.g., PM2): - Install PM2 globally by running npm install -g pm2 . - Start your Node.js script as a background process using PM2: pm2 start your_script.js - PM2 provides additional features like process monitoring, automatic restarts, and log management. 2. Using the nohup command: - Open a terminal and navigate to the directory where your Node.js script is located. - Run the following command: nohup node your_script.js & The nohup command ensures that the script continues running even if the terminal session is closed. 3. Using the screen command: - Install screen if it is not already installed by running sudo apt install screen . - Open a terminal and run the following command to start a new screen session: screen -S session_name - With...

Whatsapp-web.js On Ubuntu Server

If you are encountering issues with launching the browser while trying to load the QR code using whatsapp-web.js on an Ubuntu server, you can try the following approach: First, make sure you have installed the necessary dependencies, including whatsapp-web.js, qrcode-terminal, and a headless browser like puppeteer: npm install whatsapp-web.js qrcode-terminal puppeteer Next, create a file called index.js and paste the following code: const qrcode = require('qrcode-terminal'); const { Client } = require('whatsapp-web.js'); const puppeteer = require('puppeteer'); // Path to store session data const SESSION_FILE_PATH = './session.json'; // Initialize the WhatsApp client const client = new Client({ session: require(SESSION_FILE_PATH), puppeteer: { executablePath: '/usr/bin/chromium-browser', // Change this path to your Chromium executable headless: true, args: ['--no-sandbox', '--disable-setuid...

Convert a PDF file to a Word document on Node.js

To convert a PDF file to a Word document on Node.js, you can use a package like pdf-to-word. Here's an example code snippet that shows how to use pdf-to-word to convert a PDF file to a Word document: const fs = require('fs'); const pdf2docx = require('pdf-to-word'); const pdfFilePath = 'path/to/pdf/file.pdf'; const outputFilePath = 'path/to/word/file.docx'; pdf2docx.convert(fs.readFileSync(pdfFilePath)).then(function (result) { fs.writeFileSync(outputFilePath, result); console.log('PDF converted to Word document successfully.'); }).catch(function (error) { console.error('Error converting PDF to Word document:', error); }); In this example, we first require the fs module to read and write files, and the pdf-to-word package to convert the PDF to Word. Then, we specify the paths to the input PDF file and the output Word file. Next, we call pdf2docx.convert() and pass in the contents of the PDF file using fs.readFile...

Read text from an image in Node.js

To use Tesseract.js on Node.js, you first need to install it as a dependency in your Node.js project using npm or yarn. Here are the steps to install and use Tesseract.js on Node.js: 1. Install Tesseract.js and its dependencies using npm or yarn: npm install tesseract.js or yarn add tesseract.js 2. Once installed, you can import and use Tesseract.js in your Node.js application. Here is an example that uses Tesseract.js to recognize text from an image file: const Tesseract = require('tesseract.js'); // Provide the path to the image file const imagePath = '/path/to/image.jpg'; // Use Tesseract.js to recognize text from the image Tesseract.recognize(imagePath, 'eng', { logger: m => console.log(m) }) .then(({ data: { text } }) => { console.log(`Recognized text: ${text}`); }) .catch(error => { console.log(`Error recognizing text: ${error}`); }); In this example, we first import Tesseract.js and then provide the path to...

Reset the values of a form using jQuery

To reset the values of a form using jQuery, you can use the reset method. This method resets the form fields to their default values. Here is an example: HTML: <form id="myForm"> <input type="text" name="name" value="John"> <input type="text" name="email" value="john@example.com"> <button type="button" id="resetBtn">Reset</button> </form> JavaScript: $(document).ready(function() { $('#resetBtn').click(function() { $('#myForm')[0].reset(); }); }); In the above example, when the user clicks the "Reset" button, the values of the input fields with name="name" and name="email" will be reset to their default values. The reset method is called on the form element with id myForm. Note that the reset method only works on form elements, not on individual input fields.

Save data input from a datatable as a array

To save input form data from a DataTable, you can use the DataTable rows().data() method to get the data from the table, and then send it to the server via an AJAX request. Here is an example code snippet that demonstrates how to save input form data from a DataTable using jQuery and AJAX: // Get the DataTable instance var table = $('#example').DataTable(); // Handle form submission $('#form').submit(function(event) { event.preventDefault(); // Get the data from the DataTable var data = table.rows().data().toArray(); // Send the data to the server $.ajax({ url: 'save.php', method: 'POST', data: { data: data }, success: function(response) { alert('Data saved successfully!'); }, error: function(xhr, status, error) { console.error(error); alert('Error saving data!'); } }); }); In this example, the #example element represents the DataTable, and the #form element represents t...

Save data input from a datatable as a JSON object

To save data input from a datatable as a JSON object, you can use the rows().data() method of the datatable object to retrieve all the rows in the table, and then loop through them to extract the data from the input fields. Here's an example: // get the datatable object var table = $('#example').DataTable(); // get all the data in the table var data = table.rows().data(); // create an array to store the data var dataArray = []; // loop through the rows and extract the data data.each(function (value, index) { var row = {}; row['name'] = value[0]; // assuming the first column contains the name row['email'] = value[1]; // assuming the second column contains the email row['phone'] = value[2]; // assuming the third column contains the phone dataArray.push(row); }); // convert the array to a JSON object var jsonData = JSON.stringify(dataArray); // send the JSON object to the server using AJAX $.ajax({ url: 'save-data.ph...

Add highlight on hover for a datatable

To add highlight on hover for a datatable, you can use the rowCallback option in the DataTables initialization. Here is an example code snippet: $(document).ready(function() { $('#example').DataTable({ "rowCallback": function( row, data ) { $(row).hover(function(){ $(this).addClass('highlight'); }, function(){ $(this).removeClass('highlight'); }); } }); }); In this code, we're using jQuery's hover method to add or remove the class highlight to the row based on mouse enter or leave events. Then, we define the rowCallback function to handle this behavior for each row in the table. Note that in this example, we assume that you have defined a CSS class named highlight to style the hovered row. You can define this class in your stylesheet as follows: .highlight { background-color: yellow; } This will give the rows a yellow background when they are hovered over. You can change the styles ...

Enable multiple row selection in a DataTable

To enable multiple row selection in a DataTable, you can set the select option to 'multi' when initializing the DataTable, like this: $(document).ready(function() { $('#myTable').DataTable({ select: 'multi' }); }); This will enable multiple row selection using the standard click and shift-click behavior. You can then get the selected rows using the rows({selected: true}) method. For example, to get the data for all selected rows, you could use: var table = $('#myTable').DataTable(); var data = table.rows({selected: true}).data().toArray(); This would give you an array of objects, where each object represents a selected row and contains the row's data. You can also listen for the select and deselect events to perform actions when rows are selected or deselected. For example, to log the selected rows to the console whenever a row is selected or deselected, you could use: $('#myTable').on('select deselect...

Server-side paging in DataTables

Server-side paging in DataTables allows for large amounts of data to be loaded and displayed on a page without having to load the entire dataset. This is done by sending an Ajax request to the server for each new page of data, instead of loading all the data at once. Here are the basic steps to implement server-side paging in DataTables: 1. Configure the server-side script to return the appropriate subset of data based on the page number and page size. 2. Initialize DataTables with the server-side processing option set to true, and configure the Ajax settings to point to the server-side script and send the necessary parameters. 3. Set the paging options in DataTables to display the desired number of rows per page, and configure any additional options as needed. Here is an example of how to implement server-side paging in DataTables using PHP and MySQL: PHP script (server-side script to retrieve data): <?php // MySQL database connection details $host = 'localhost'; ...

Generate an input form in a jQuery datatable

To generate an input form in a jQuery datatable, you can use the render function of a column definition to return an HTML string that contains the input element. Here's an example: HTML: <div class="col-md-12"> <button type="button" class="btn btn-sm btn-primary" id="mct_btn_tambah"><span class="fa fa-plus"></span> Tambah Tindakan</button> <table id="mct_table" class="table" style="width:100%;"></table> </div> JAVASCRIPT: <script type="text/javascript"> var mct = function () { this.table = ''; var self = this; this.init = function () { self.table = $('#mct_table').DataTable({ info: false, paging:false, sorting:false, searching:false, orderCellsTop: true, columns: [ {data: null, title:'No.', name: 'no', width: '2...

Check if the FTP service is running on an Ubuntu server with PHP

You can use the exec() function in PHP to execute a shell command to check the status of the FTP service on a remote server. Here's an example code that uses the systemctl command to check if the FTP service is running on an Ubuntu server: $server = '192.168.1.100'; // Replace with your server IP $username = 'username'; // Replace with your server username $password = 'password'; // Replace with your server password // SSH connection $connection = ssh2_connect($server, 22); ssh2_auth_password($connection, $username, $password); // Execute systemctl command to check FTP service status $stream = ssh2_exec($connection, 'systemctl status vsftpd.service'); stream_set_blocking($stream, true); // Get command output $output = stream_get_contents($stream); // Check if FTP service is active if (strpos($output, 'Active: active (running)') !== false) { echo 'FTP service is running.'; } else { echo 'FTP service is not running....

Fix the header of a DataTable,

To fix the header of a DataTable, you can use the fixedHeader extension provided by DataTables. This extension will fix the header of the table in place while allowing the rest of the table to scroll. Here's how you can use it: 1. First, include the datatables.fixedHeader.min.js file in your HTML document. You can download this file from the DataTables website or use a CDN link. <script src="https://cdn.datatables.net/fixedheader/3.1.9/js/dataTables.fixedHeader.min.js"/></script/> 2. Then, initialize your DataTable with the fixedHeader option set to true. $(document).ready(function() { $('#example').DataTable({ fixedHeader: true }); }); This will fix the header of your table in place while allowing the rest of the table to scroll. You can also customize the behavior of the fixed header by passing in additional options to the fixedHeader option. For example, you can change the offset of the header from the top of the viewp...

Add a row to a DataTable using jQuery

To add a row to a DataTable using jQuery, you can use the row.add() method. Here's an example: var table = $('#myTable').DataTable(); var data = ['John', 'Doe', 'johndoe@example.com']; table.row.add(data).draw(); In this example, myTable is the ID of the DataTable, data is an array containing the data for the new row, and draw() is called to redraw the table with the new row added. You can also add a row using an object instead of an array. Here's an example: var table = $('#myTable').DataTable(); var data = { first_name: 'John', last_name: 'Doe', email: 'johndoe@example.com' }; table.row.add(data).draw(); In this example, data is an object containing the data for the new row, and the keys correspond to the column names in the table.

Convert JSON data to input text on a datatable using jQuery

To convert JSON data to input text on a datatable using jQuery, you can use the render option of the columns configuration to specify a function that returns the HTML markup for the input text. Here's an example: // Assuming JSON data in the format [{ "name": "John", "age": 30 }, ...] $(document).ready(function() { $('#myTable').DataTable({ data: myData, // myData is the JSON data columns: [ { data: 'name', title: 'Name' }, { data: 'age', title: 'Age' }, { data: null, title: 'Input', render: function(data, type, row, meta) { return '<input type="text" value="' + data.name + '" />'; } } ] }); }); In this example, the data parameter of the render function is the object containing the data for the current row. We extract the name property from this object and use it as the initia...

Check if an IP address is active or not with PHP

To check if an IP address is active or not with PHP, you can use various approaches. Here are a few examples: 1. Using ping command with exec() function: $ip = '192.168.1.1'; if (exec(sprintf("ping -c 1 -W 2 %s", escapeshellarg($ip))) == true) { echo "IP is active"; } else { echo "IP is not active"; } This code sends a single ping request with a timeout of 2 seconds. If the IP address responds, the exec() function will return a non-empty result, and the code will output "IP is active". Otherwise, it will output "IP is not active". 2. Using fsockopen() function to check if a port is open: $ip = '192.168.1.1'; $port = 80; if($fp = fsockopen($ip,$port,$errCode,$errStr,1)){ echo "IP is active"; fclose($fp); } else { echo "IP is not active"; } This code checks if port 80 is open on the IP address using the fsockopen() function. If the connection is successful, the code w...

Send image URL using whatsapp-web.js

To send an image with a URL using whatsapp-web.js, you can use the Client.sendImage method with the url parameter. Here is an example code: const fs = require('fs'); const path = require('path'); const axios = require('axios'); const qrcode = require('qrcode-terminal'); const { Client , MessageMedia } = require('whatsapp-web.js'); const client = new Client(); const folderPath = 'D:/xampp/htdocs/api-whatsapp/downloads'; function sendFileFromUrl(chatId, message, fileUrl) { const filename = path.basename(fileUrl); const filePath = path.join(folderPath, filename); axios({ url: fileUrl, responseType: 'stream' }).then(response => { response.data.pipe(fs.createWriteStream(filePath)); response.data.on('error', err => { console.error(err); }); response.data.on('end', () => { console.log('File downloaded successfully!'); const...

Replication MySQL 5.7 Ubuntu 20.04

SERVER MASTER 192.168.2.10 mysql user : root mysql password : password_master$ mysql user : user_replikasi$ mysql password : password_replikasi$ SERVER SLAVE 192.168.2.20 mysql user : root mysql password : password_replikasi$ Setting on server master 1. Update Ubuntu sudo apt update sudo apt list --upgradable sudo apt upgrade sudo reboot 2. Create a Sudo User on Ubuntu adduser example_user adduser example_user sudo su - example_user 3. Install MySQL wget https://dev.mysql.com/get/mysql-apt-config_0.8.12-1_all.deb sudo dpkg -i mysql-apt-config_0.8.12-1_all.de sudo apt update sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 467B942D3A79BD29 sudo apt update sudo apt-cache policy mysql-server sudo apt install -f mysql-client=5.7* mysql-community-server=5.7* mysql-server=5.7* sudo mysql_secure_installation mysql -u root -p SELECT VERSION(); 4. Masuk ke file sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf: bind-address = 192.168.2.10 server-id ...

Download a file on Node.js

To download a file on Node.js, you can use the built-in fs module and the https or http module to make a request to the server and save the response to a file. Here's an example of how you can download a file using https module: const https = require('https'); const fs = require('fs'); const fileUrl = 'https://example.com/file.pdf'; const filePath = './downloads/file.pdf'; const file = fs.createWriteStream(filePath); https.get(fileUrl, (response) => { response.pipe(file); file.on('finish', () => { file.close(); console.log('File downloaded successfully.'); }); }).on('error', (err) => { fs.unlink(filePath, () => { console.error(`Error downloading file: ${err}`); }); }); In the above example, we first define the URL of the file we want to download and the path where we want to save the file. We then create a write stream to the file using the fs module. Next, we make a https.get() re...

Check the status of a WhatsApp account using whatsapp-web.js

To check if a phone is registered on WhatsApp, you will need to create a WhatsApp Web session using the whatsapp-web.js library. Once you have created a session, you can use the isRegisteredUser method of the WWebJS object to check if the phone number is registered on WhatsApp. Here is an example code snippet that demonstrates how to check if a phone number is registered on WhatsApp using the whatsapp-web.js library: const { Client } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const client = new Client(); client.on('qr', (qr) => { qrcode.generate(qr, {small: true}); }); client.on('ready', () => { console.log('Client is ready!'); // Check if phone number is registered on WhatsApp const phoneNumber = '62123456789'; // Replace with phone number to check client.isRegisteredUser(phoneNumber + '@c.us').then((isRegistered) => { if (isRegistered) { cons...

Install FTP server on VPS

To install and configure an FTP server on your VPS digital ocean, you can follow these steps: 1. Log in to your VPS using SSH. 2. Update the package list by running the following command: sudo apt-get update 3. Install the FTP server package, vsftpd: sudo apt-get install vsftpd 4. Once the installation is complete, you need to configure the FTP server. Open the configuration file for vsftpd: sudo nano /etc/vsftpd.conf 5. Make the following changes to the configuration file: anonymous_enable=NO local_enable=YES write_enable=YES chroot_local_user=YES user_sub_token=$USER local_root=/home/$USER/ftp pasv_min_port=40000 pasv_max_port=50000 listen_ipv6=YES Here, you are disabling anonymous login, enabling local users, allowing write access, setting the local root directory to the user's home directory plus an ftp directory, and enabling passive mode. 6. Save the configuration file and exit. 7. Restart the vsftpd service to apply the changes: sudo systemctl...

Add the ability to select rows in a jQuery DataTable

To add the ability to select rows in a jQuery DataTable, you can use the select option provided by the DataTables library. Here's an example of how to add row selection to a DataTable: $('#myTable').DataTable({ select: true }); This will enable row selection for the table with the ID myTable. Once you've added row selection, you can access the selected rows using the rows({selected:true}) method: var selectedRows = $('#myTable').DataTable().rows({selected:true}).data(); This will return an array of data objects for the selected rows. You can also handle the select event to perform custom actions when a row is selected: $('#myTable').on('select.dt', function(e, dt, type, indexes) { var selectedRows = dt.rows({selected:true}).data(); // do something with the selected rows });

JWT authentication in Yii2

1. Install the firebase/php-jwt package using composer: composer require firebase/php-jwt 2. Create a JwtHelper class that will handle the JWT authentication: namespace app\components; use Firebase\JWT\JWT; use yii\base\Component; class JwtHelper extends Component { private $key = 'YOUR_SECRET_KEY'; private $algorithm = 'HS256'; private $expire = 3600; public function generateToken($payload) { $payload['exp'] = time() + $this->expire; return JWT::encode($payload, $this->key, $this->algorithm); } public function validateToken($token) { try { $decoded = JWT::decode($token, $this->key, [$this->algorithm]); return (array) $decoded; } catch (\Exception $e) { return false; } } } This class contains two methods: generateToken() for generating a JWT token and validateToken() for validating the token. 3. In your Yii2 appl...

Send image message(path) with whatsapp-web.js

To send an image using the WhatsApp Web API and Node.js, you need to first convert the image file into a base64-encoded string. You can do this using the Node.js built-in fs module and the readFileSync() function to read the file contents, and the encoding function to convert it to a base64: const fs = require('fs'); const path = require('path'); const filePath = '/path/to/image.jpg'; const image = fs.readFileSync(filePath, { encoding: 'base64' }); Once you have the image encoded as a base64 string, you can use the sendImage method of the Client object in whatsapp-web.js to send it to a contact or group: const {Client , MessageMedia} = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const client = new Client(); async function sendFileFromPath(chatId, filePath, messag...

Send text messages with whatsapp-web.js

To send a text message using the whatsapp-web.js library, you can use the sendMessage function provided by the Chat class. Here's an example code snippet: const {Client} = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const express = require('express'); const app = express(); const client = new Client(); client.on('qr', qr => { qrcode.generate(qr, {small: true}); }); client.on('ready', () => { const phone_no = '62123456789@c.us'; const message = 'send message'; client.sendMessage(phone_no, message).then(() => { console.log('succeed'); }).catch((err) => { console.log('fail'); }); }); client.initialize(); app.listen(3000, () => { console.log('system is running'); });

Get row id on datatable.row on each javascript

To get the row id on each DataTable row, you can use the each() function in jQuery to iterate through each row and retrieve its id attribute. Here's an example code snippet: var table = $('#myDataTable').DataTable(); table.rows().every(function() { var data = this.data(); var rowId = $(this.node()).attr('id'); }); In the example above, myDataTable is the ID of the DataTable. rows().every() iterates through each row in the table, and $(this.node()).attr('id') retrieves the id attribute of the current row. You can replace console.log with your own code to handle each row.

Login qrcode whatsapp-web.js on terminal

To log in with WhatsApp Web using whatsapp-web.js on the terminal, you can follow these steps: 1. First, you need to install whatsapp-web.js using npm. Open your terminal and navigate to your project folder. Then, run the following command: npm install whatsapp-web.js 2.Once whatsapp-web.js is installed, you can create a new JavaScript file (for example, index.js) and add the following code: const qrcode = require('qrcode-terminal'); const { Client } = require('whatsapp-web.js'); const client = new Client(); client.on('qr', (qr) => { qrcode.generate(qr, { small: true }); }); client.on('ready', () => { console.log('Client is ready!'); }); client.initialize(); 3. In the code above, we first import qrcode-terminal and whatsapp-web.js. Then, we create a new Client object and attach two event listeners to it: one for the QR code and another for when the client is ready. 4. To display the QR code in the terminal, we use the...

Get baseurl on nodejs

In Node.js, you can get the base URL of your project using the __dirname global variable, which holds the absolute path of the directory that contains the currently executing JavaScript file. Here's an example code snippet that demonstrates how to get the base URL of your Node.js project: const path = require('path'); const baseDir = path.resolve(__dirname); console.log('Base URL:', baseDir); This code will output the base URL of your project, which is the absolute path to the directory that contains your main JavaScript file. You can use this base URL to reference other files in your project.

Whatsapp-web.js install

To install whatsapp-web.js version 1.19.4, you can follow these steps: 1. Open your terminal or command prompt. 2. Navigate to your project directory. 3. Type the following command: npm install whatsapp-web.js@1.19.4 4. Wait for the installation process to complete. That's it! The whatsapp-web.js version 1.19.4 should now be installed in your project.

Call function javascript from other window browser

To call a JavaScript function from another window in Yii2, you can use the window.opener property to get a reference to the parent window and then call the function using that reference. Assuming that you have a function named myFunction in the parent window, you can call it from the child window like this: In the parent window: function myFunction() { // Your code here } In the child window: window.opener.myFunction(); You can also pass arguments to the function by including them in the parentheses, like this: window.opener.myFunction(arg1, arg2, ...); Note that this method will only work if the child window was opened using window.open() from the parent window. If the child window was opened in a different way, you may need to use a different method to communicate between the windows, such as using window.postMessage().