AutoComplete is a feature to suggest relevant results on typing into a textbox. For example, Google search textbox autosuggest search phrases on keypress.
It can be enabled using client-side tools and attributes. The data for the autosuggest textbox can be static or dynamic.
For loading remote data dynamically, the source possibility is either files or databases. This article uses the database as a source to have dynamic results at the backend.
The below example has an idea for a quick script for enabling the autocomplete feature. It uses JavaScript jQuery and jQuery UI libraries to implement this easily.
The jQuery autocomplete() uses the PHP endpoint autocomplete.php script. Then, load the remote data into the textbox on the UI.
This PHP endpoint script reads the database results and forms the output JSON for the autocomplete textbox.
It receives the searched term from the UI and looks into the database for relevant suggestions.
autocomplete.php
<?php
$name = $_GET['term'];
$name = "%$name%";
$conn = mysqli_connect('localhost', 'root', '', 'phppot_autocomplete');
$sql = "SELECT * FROM tbl_post WHERE title LIKE ?";
$statement = $conn->prepare($sql);
$statement->bind_param('s', $name);
$statement->execute();
$result = $statement->get_result();
$autocompleteResult = array();
if (! empty($result)) { while ($row = $result->fetch_assoc()) { $autocompleteResult[] = $row["title"]; }
}
print json_encode($autocompleteResult);
?>
This database is for setting up the database created for this quick example. The next example also needs this database for displaying the autosuggest values.
Run the below database queries for getting a good experience with the above code execution.
CREATE TABLE `tbl_post` ( `id` int(11) UNSIGNED NOT NULL, `title` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --
-- Dumping data for table `tbl_post`
-- INSERT INTO `tbl_post` (`id`, `title`) VALUES
(1, 'Button on click event capture.'),
(2, 'On key press action.'),
(3, 'Overlay dialog window.);
Example 2: Load autocomplete with ID
The AutoComplete function sends an additional parameter with the default term argument. That is to limit the number of results shown in the autocomplete textbox.
It returns the database results based on the searched term as a key-value pair. A JavaScript callback iterates the result and maps the key-value as label-value pair.
It is helpful when the result id is required while selecting a particular item from the autosuggest list.
The below screenshot shows the item value and id is populated. This data is put into the textbox on selecting the autocomplete list item.
The below JavaScript code has two textboxes. One textbox is enabled with the autocomplete feature.
On typing into that textbox, the JavaScript autocomplete calls the server-side PHP script. The callback gets the JSON output returned by the PHP script.
This JSON data contains an association of dynamic results with their corresponding id. On selecting the autocomplete result item, the select callback function access the UI.item object.
Using this object, it gets the id and post title from the JSON data bundle. Then this JavaScript callback function targets the UI textboxes to populate the title and id of the selected item.
This example shows the autocomplete box with text and image data. The database for this example contains additional details like description and featured_image for the posts.
If you want a sleek and straightforward autocomplete solution with text, then use the above two examples.
This example uses BootStrap and plain JavaScript without jQuery. It displays recent searches on focusing the autocomplete textbox.
Create AutoComplete UI with Bootstrap and JavaScript Includes
See this HTML loads the autocomplete textbox and required JavaScript and CSS assets for the UI. The autocomplete.js handles the autosuggest request raised from the UI.
The autocomplete textbox has the onKeyPress and onFocus attributes. The onKeyPress attribute calls JavaScript to show an autosuggest list. The other attribute is for displaying recent searches on the focus event of the textbox.
Get the autosuggest list from the tbl_post database table
The below JavaScript function is called on the keypress event of the autocomplete field. In the previous examples, it receives a JSON response to load the dynamic suggestion.
In this script, it receives the HTML response from the endpoint. This HTML is with an unordered list of autosuggest items.
function showSuggestionList(searchInput) { if (searchInput.length > 1) { var xhttp = new XMLHttpRequest(); xhttp.open('POST', 'ajax-endpoint/get-auto-suggestion.php', true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("formData=" + searchInput); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById('auto-suggestion-box').innerHTML = xhttp.responseText; } } } else { document.getElementById('auto-suggestion-box').innerHTML = ''; }
}
ajax-endpoint/get-auto-suggestion.php
<?php
require_once __DIR__ . '/../lib/DataSource.php';
$dataSource = new DataSource(); if (isset($_POST["formData"])) { $searchInput = filter_var($_POST["formData"], FILTER_SANITIZE_STRING); $highlight = '<b>' . $searchInput . '</b>'; $query = "SELECT * FROM tbl_post WHERE title LIKE ? OR description LIKE ? ORDER BY id DESC LIMIT 15"; $result = $dataSource->select($query, 'ss', array( "%" . $searchInput . "%", "%" . $searchInput . "%" )); if (! empty($result)) { ?>
<ul class="list-group">
<?php foreach ($result as $row) { ?> <li class="list-group-item text-muted" data-post-id="<?php echo $row["id"]; ?>" onClick="addToHistory(this)" role="button"><img class="post-icon" src="<?php echo $row["featured_image"]; ?>" /><span> <?php echo str_ireplace($searchInput, $highlight, $row["title"]); ?> </span></li>
<?php } ?>
</ul>
<?php }
}
?>
Add to search history
When selecting the suggested list item, it triggers this JavaScript function on click.
This function reads the post id and title added to the HTML5 data attribute. Then passes these details to the server-side PHP script.
This PHP code removes the search instances stored in the tbl_search_history database. The delete request posts the record id to fire the delete action.
Posted by: xSicKxBot - 08-09-2022, 04:41 AM - Forum: Python
- No Replies
How to Read and Convert a Binary File to CSV in Python?
5/5 – (1 vote)
To read a binary file, use the open('rb') function within a context manager (with keyword) and read its content into a string variable using f.readlines(). You can then convert the string to a CSV using various approaches such as the csv module.
Here’s an example to read the binary file 'my_file.man' into your Python script:
with open('my_file.man', 'rb') as f: content = f.readlines() print(content)
Per default, Python’s built-in open() function opens a text file. If you want to open a binary file, you need to add the 'b' character to the optional mode string argument.
To open a file for reading in binary format, use mode='rb'.
To open a file for writing in binary format, use mode='rb'.
Now that the content is in your Python script, you can convert it to a CSV using the various methods outlined in this article:
After you’ve converted the data to the comma-separated values (CSV) format demanded by your application, you can write the string to a file using either the print() function with file argument or the standard file.write() approach.
Cartel Tycoon is a survival business sim inspired by the ‘80s narco trade. Expand and conquer, fight off rival cartels and evade the authorities. Earn people's loyalty and strive to overcome the doomed fate of a power-hungry drug lord.
Posted by: xSicKxBot - 08-09-2022, 04:41 AM - Forum: Lounge
- No Replies
Madden 23 - Indianapolis Colts Roster And Ratings
Madden 23 is here, and that means virtual football fans once more have a full season's worth of debates to have, first downs to pick up, and hopefully, more than a few touchdown dances to choreograph. We're breaking down the Madden 23 rosters for all 32 teams, and in this guide, we'll be taking a look at the Indianapolis Colts. The Colts have an interesting year ahead of them, as they return many of their starters from the 2022 season. The big question surrounds their huge offseason acquisition of quarterback Matt Ryan. However, in the world of Madden, Indy will still be a desirable to team to play as due to the sheer power of running back Jonathan Taylor and their dominant offensive line. If you're curious who the Colts' best players are, where they stack up in the league as a whole, or which roster spots may need to be improved in Franchise mode, here's everything you need to know about the Madden 23 Colts roster.
Indianapolis Colts' best and worst players
The Colts are the 19th best team in the league according to the launch list of the best teams in Madden 23. At launch, they have an overall team rating of 82. The Colts have five players rated 90 or above in Madden 23, including the following players:
Quenton Nelson - 95 OVR
Jonathan Taylor - 95 OVR
Stephon Gilmore - 91 OVR
DeForest Buckner - 90 OVR
Darius Leonard - 90 OVR
The worst players on the Raiders are Luke Rhodes (27 OVR) at tight end (long snapper), Wesley French (56 OVR) at center, and Jack Coan (56 OVR) at quarterback. Below you can see a table of the complete starting roster for the Raiders at launch in Madden 23, including 11 players on offense, 11 on defense, plus the team's kicker and punter.
Posted by: xSicKxBot - 08-08-2022, 07:24 AM - Forum: Python
- No Replies
How to Convert Epoch Time to Date Time in Python
5/5 – (1 vote)
Problem Formulation and Solution Overview
In this article, you’ll learn how to convert Epoch Time to a Date Time representation using Python.
On January 1st, 1970, Epoch Time, aka Time 0 for UNIX systems, started as a date in history to remember. This date is relevant, not only due to this event but because it redefined how dates are calculated!
To make it more fun, we will calculate the time elapsed in Epoch Time from its inception on January 1, 1970, to January 1, 1985, when the first mobile phone call was made in Britain by Ernie Wise to Vodafone. This will then be converted to a Date Time representation.
Question: How would we write code to convert an Epoch Date to a Date Time representation?
We can accomplish this task by one of the following options:
Above, imports the datetime library. This allows the conversion of an Epoch Time integer to a readable Local Date Time format.
The following line declares an Epoch Time integer and saves it to epoch_time.
Next, the highlighted line converts the Epoch Time into a Local Date Time representation and saves it to date_conv. If output to the terminal at this point, it would display as follows:
1985-01-01 00:00:00
Finally, date_conv converts into a string using strftime() and outputs the formatted date to the terminal.
01-01-1985
Method 2: Use time.localtime()
This method imports the time library and calls the associated time.localtime() function to convert Epoch Time into a Local Date Time representation.
import time epoch_time = 473398200
date_conv = time.localtime(epoch_time)
print(date_conv)
Above, imports the timelibrary. This allows the conversion of an Epoch Time to a readable Local Date Time format.
The following line declares an Epoch Time integer and saves it to epoch_time.
Next, the highlighted line converts the Epoch Time into a Local Date Time representation and saves it to date_conv as a Tuple as shown below:
Above, imports the timelibrary. This allows the conversion of an Epoch Time to a readable Local Date Time format.
The following line declares an Epoch Time integer and saves it to epoch_time.
Next, the highlighted line converts the Epoch Time into a Local Date Time representation, converts to a string (strftime()) format and saves it to date_conv.
The output is sent to the terminal.
Formatted Date: Tue Jan 1 00:00:00 1985
Summary
These four (4) methods of converting an Epoch Time to a Date Time representation should give you enough information to select the best one for your coding requirements.
Good Luck & Happy Coding!
Programmer Humor – Blockchain
“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.”source – xkcd
In MultiVersus, the Multiverse is at your fingertips as you battle it out in intense 2v2 matches. Up against Batman & Shaggy? Try using Bugs Bunny & Arya Stark! This platform fighter lets you play out your fantasy matchups in a fun co-op or head-to-head fight for supremacy.
Posted by: xSicKxBot - 08-08-2022, 07:23 AM - Forum: Lounge
- No Replies
NBA 2K23 Brings Giannis-Like Power To The Paint, Promises Dev
In NBA 2K23, the court is bigger than just the three-point arc. That should be obvious, but with last year's game, Visual Concepts admitted shooters had too much of an advantage. Talented shooters made shots consistently and with less-than-lifelike effort, while even lesser-skilled players could drain long jumpers and three-pointers if they only got an open look. Among a host of other gameplay changes in NBA 2K23, the focus in this fall's game is about bringing balance back to the offensive game, and empowering players to work in the paint and attack the rim.
"We looked at how virtual games were playing out compared to the real-life NBA," said NBA 2K gameplay director Mike Wang. "And it was clear that we needed to give more love to slashers who love to finish at the rim. This meant expanding the tools for attacking the basket." With that in mind, NBA 2K23 starts with an improved Pro Stick, meant to give players more maneuverability in the paint.
New gesture combos, such as double throws and switchbacks, are meant to provide shooting windows in tight quarters, when the defense is bearing down on you. Double-throw gestures are used for hop-step layups, while switchback gestures are used for Euro-step and cradle layups.
Posted by: xSicKxBot - 08-07-2022, 07:55 AM - Forum: Python
- No Replies
Blockchain Basics of Smart Contracts and Solidity
5/5 – (1 vote)
This article will give you an overview of the blockchain basics, transactions, and blocks.
In the previous article of this series, we looked at how to create your own token using Solidity and, specifically, events for transactions.
Blockchain Basics
Blockchain technology enables us to write programs without having to think about the details of the underlying communication infrastructure.
However, just to be aware of some of the keywords which are commonly used when studying the infrastructure, we’ll name just a few among others (borrowed from the Solidity documentation):
mining,
elliptic-curve cryptography,
peer-to-peer network.
Although it’s interesting to see how these technologies work “under the blockchain’s hood”, the beneficial fact is that you don’t have to be closely familiar with them. You can just implicitly utilize them and maybe even forget they’re there. However, they represent some of the key elements which make up Web3.
Note: Here, we need to establish a firm distinction between the terms Web3 in the blockchain context that is the subject of our interest when discussing Solidity, and the Semantic Web, sometimes known as Web 3.0, which is an extension of the World Wide Web, intended to make Internet data machine-readable.
Transactions
One of the main roles of a blockchain is to preserve the data and make it temper-resistant. In that sense, we can easily consider a blockchain as a globally shared, transactional database.
A blockchain network is globally shared because any party in the network can access and read its contents.
It is transactional because any change to the blockchain has to be accepted by almost all, or at least the majority of other members, depending on the blockchain implementation.
In database theory and practice having a transactional property means two things: the change to the database is either applied completely or not at all (see here); no other transaction can modify the effect of a transaction being executed.
We regularly ensure the equivalent behavior of our smart contracts by using error handling and control structures available in Solidity (docs).
Blockchain Security
There is also a strong security property that is inherent in the way how blockchain works: each new block header includes the hash of the previous block.
To alter a block in a blockchain, an attacker would have to re-mine the targeted block and all the following blocks, therefore creating a chain fork.
Also, an attacker would need to invest more total work than was invested in the original chain segment to get his chain fork accepted by the rest of the network (source).
The latter would require immense computing power and energy, making the entire effort unfeasible in theory.
However, there have been successful attacks on blockchain networks, mostly due to the smaller scale of a particular network, where a fraudulent consensus (the verification process) was less difficult to fabricate, block creation errors, or insufficient security measures (source).
Example Application
An example to the story above is already given in part by the example we did in the previous article: a smart contract for (simulated) currency transfer between any two parties.
There was a list of accounts holding balances in a cryptocurrency, Wei, and our smart contract supported transfers of a given amount of currency from the sender to the receiver.
What’s important in the context of such transactions is that the same amount of currency should always be “simultaneously” deducted from the sender’s account and added to the receiver’s account.
What we mean by “simultaneously” is not a matter of happening at the same moment, but happening with the same, but the opposite consequence, i.e. if the amount gets successfully deducted from the sender’s account, it has to be added to the receiver’s account.
If an error occurs after the amount is decreased from the sender’s account, but before the amount is added to the receiver’s account, the operation should revert to the smart contract’s previous state, as it was before the transaction started.
This way, the blockchain behaves in a consistent, transactional manner and warrants that the transaction will be done entirely or not at all.
In the context of everything said so far, with our subcurrency example in mind, we may ask ourselves:
Question: How would we enable an account owner to transfer the currency only from the account in his ownership?
The answer to the question is relatively simple:
Answer: A transaction always bears the sender’s cryptographic signature, which serves as a seal in granting access to precisely defined modifications of (operations on) the database, such as currency transfer from the account owner originally holding the currency, to the account owner – receiver of the currency.
Blocks
There is no story about blockchain without actually mentioning the block itself. We will definitively return to talk about a block from some other angles, but with a security perspective in mind, we will focus on overcoming a significant obstacle known (in Bitcoin terms) a “double-spend attack” (source).
Some paragraphs ago, we mentioned a blockchain attack implying the majority of the network members’ acceptance, popularly known as the “51% attack”.
Let’s assume there are two transactions in the blockchain network, and each of them attempts to transfer all the account’s currency to another account, i.e. they will both attempt to empty the account.
Since there can be only one accepted, confirmed transaction (in contrast to two or more possible unconfirmed transactions), the transaction that gets confirmed first will end up bundled in a block. It is not under our control or, for that matter, not even a subject of our concern which block will be the first one.
What matters is that the second block will be rejected and the contention between the blocks/transactions will be resolved automatically, and the likelihood of the double-spend attack problem will decrease with each additional confirmation (source).
Blocks are sequentially added to a blockchain, ordered by the time of their arrival. Adding a block to the blockchain is mostly done in regular intervals, which last about 17 seconds for the Ethereum network.
Nonetheless, the blockchain tip can sometimes be reverted during the order selection mechanism. In that case, a confirmed block will get discarded and become a stale block, and the stale block’s successor blocks just get returned to the memory pool.
Note: discarded or stale blocks are popularly and wrongly called orphan blocks. (source)
For block reversal to happen, two conditions should occur.
(1) First, multiple blocks should get created from the same parent block P simultaneously (by different miners) and get confirmed by the network, forming a fork with multiple subchains/branches at the tip (block) P of the blockchain.
As there are multiple successor block candidates (e.g. we will assume three blocks, A, B, and C), each block has an equal chance of becoming a permanent part of the blockchain.
Because blocks propagate through the blockchain network differently, miners will receive one of the blocks (A, B, or C) before the other blocks and start mining a new block on the block they received first.
(2) Second, one of the miners will mine and broadcast a new block, e.g. C1 to the network before the other miners mine blocks A1 or B1 (these don’t exist as yet).
Since the fastest miner first received block C and then produced C1, it will extend the branch P-C, effectively making the branch P-C-C1 the longest one. Once the network detects there is a chain longer than the chains P-A and P-B, it will disqualify the candidate blocks A and B as stale blocks, thus resolving the contention.
All the miners who chose a different blockchain from the fork, e.g. P-A or P-B, and started building their blockchains on them, will experience a block reversal, as their chains will also get updated by the network with the blockchain P-C-C1 as the longest one.
The blockchain tip reversal gets less likely to happen as more blocks are confirmed and added to the blockchain. A common number of confirmations after we can be virtually certain that our block became a permanent part of a blockchain is six confirmations (source).
Conclusion
In this article, we first shortly made a short detour (sorry about that) to a missing part about Solidity events, and then boldly stepped into the direction of blockchain basics, transactions, and blocks.
First, we made friends with an event listener example based on web3.js library.
Second, we glanced at the blockchain basics. You already know the works: some basic terms, dry notes, etc. It’s just a scratch, really.
Third, we learned about how blockchain treats transactions and how it makes them feel secure, shared and cared for. That’s why we mentioned some properties that make blockchain look like a database.
Fourth, we went into some light details on what a block is, what is its role in the blockchain ecosystem and what are some of the risks present in a blockchain network.
Solidity is the programming language of the future.
It gives you the rare and sought-after superpower to program against the “Internet Computer”, i.e., against decentralized Blockchains such as Ethereum, Binance Smart Chain, Ethereum Classic, Tron, and Avalanche – to mention just a few Blockchain infrastructures that support Solidity.
In particular, Solidity allows you to create smart contracts, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own decentralized autonomous organizations (DAOs) that run on Blockchains without being subject to centralized control.
NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.
This course is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet – without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.
[www.indiegala.com] Tackle the summer heat with an even hotter Match3 treat! A selection of casual match3 puzzle games with distinctive elements are waiting to be solved: Gaslamp Cases 2, 100 Days without delays, Funny Pets, Halloween Trouble 2, Catherine Ragnor and the Legend of the Flying Dutchman, Rorys Restaurant Deluxe, Suddenly Meow, Save the Planet, The lost Labyrinth