Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,134
» Latest member: jax9090nnn
» Forum threads: 21,936
» Forum posts: 22,806

Full Statistics

Online Users
There are currently 3201 online users.
» 0 Member(s) | 3196 Guest(s)
Applebot, Baidu, Bing, Google, Yandex

 
  [Tut] (Fixed) Python TypeError ‘bool’ object is not subscriptable
Posted by: xSicKxBot - 10-02-2022, 12:23 PM - Forum: Python - No Replies

(Fixed) Python TypeError ‘bool’ object is not subscriptable

5/5 – (1 vote)

Problem Formulation


Consider the following minimal example where a TypeError: 'bool' object is not subscriptable occurs:

boo = True
boo[0]
# or:
boo[3:6]

This yields the following output:

Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> boo[0]
TypeError: 'bool' object is not subscriptable

Solution Overview


Python raises the TypeError: 'bool' object is not subscriptable if you use indexing or slicing with the square bracket notation on a Boolean variable. However, the Boolean type is not indexable and you cannot slice it—it’s not iterable!

In other words, the Boolean class doesn’t define the __getitem__() method.

boo = True
boo[0] # Error!
boo[3:6] # Error!
boo[-1] # Error!
boo[:] # Error!

You can fix this error by

  1. converting the Boolean to a string using the str() function because strings are subscriptable,
  2. removing the indexing or slicing call,
  3. defining a dummy __getitem__() method for a custom “Boolean wrapper class”.

? Related Tutorials: Check out our tutorials on indexing and slicing on the Finxter blog to improve your skills!

Method 1: Convert Boolean to a String


If you want to access individual characters of the “Boolean” strings "True" and "False", consider converting the Boolean to a string using the str() built-in function. A string is subscriptable so the error will not occur when trying to index or slice the converted string.

boo = True
boo_string = str(boo) print(boo_string[0])
# T
print(boo_string[1:-1])
# ru

Method 2: Put Boolean Into List


A simple way to resolve this error is to put the Boolean into a list that is subscriptable—that is you can use indexing or slicing on lists that define the __getitem__() magic method.

bools = [True, True, True, False, False, False, True, False]
print(bools[-1])
# False print(bools[3:-3])
# [False, False]

Method 3: Define the __getitem__() Magic Method


You can also define your own wrapper type around the Boolean variable that defines a dunder method for __getitem__() so that every indexing or slicing operation returns a specified value as defined in the dunder method.

class MyBool: def __init__(self, boo): self.boo = boo def __getitem__(self, index): return self.boo my_boolean = MyBool(True) print(my_boolean[0])
# True print(my_boolean[:-1])
# True

This hack is generally not recommended, I included it just for comprehensibility and to teach you something new. ?

Summary


The error message “TypeError: 'boolean' object is not subscriptable” happens if you access a boolean boo like a list such as boo[0] or boo[1:4]. To solve this error, avoid using slicing or indexing on a Boolean or use a subscriptable object such as lists or strings.



https://www.sickgaming.net/blog/2022/10/...criptable/

Print this item

  (Indie Deal) Destiny 2: Lightfall Pre-Order is ready
Posted by: xSicKxBot - 10-02-2022, 12:23 PM - Forum: Deals or Specials - No Replies

Destiny 2: Lightfall Pre-Order is ready

Final day, to check out the encore weekend freebies
[freebies.indiegala.com]
"Encore, encore" we've been hearing and we listened. We've brought back for this weekend a few of your favorites. Keep an eye on for more.

https://www.youtube.com/watch?v=LxBOlbnM1yg

Bungie Sale, UP TO 66% OFF
[www.indiegala.com]
https://www.youtube.com/watch?v=lfoeZLp5A7k
Destiny 2: Lightfall + Annual Pass[www.indiegala.com] | 16%
Destiny 2: Lightfall[www.indiegala.com] | 16%

Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...4563466729

Print this item

  PC - Lost Judgment
Posted by: xSicKxBot - 10-02-2022, 12:22 PM - Forum: New Game Releases - No Replies

Lost Judgment



December 2021, Tokyo district court. Akihiro Ehara stands accused of groping a woman on a crowded train. A bystander's video footage of his attempt to flee the scene and subsequent apprehension is all over the news, and public outcry demands a maximum sentence.

"Three days ago, a dead body was found in an abandoned building in Yokohama. Have you identified it yet?" he proclaims as confusion cuts through the court room. His defense lawyer, Saori Shirosaki , has no doubt that crucial details of the situation have been overlooked, as Ehara was not even tried for the murder. She contacts detective Takayuki Yagami to investigate this further.

How could Ehara have committed two crimes at once? Was the sexual battery just a cover up? Has Ehara gamed the entire justice system? As victims surface and Yagami digs farther into the truth, he is faced with a question: Defend the law, or enact justice? From just a single stumble, one can become a monster...

Publisher: SegaSoft

Release Date: Sep 15, 2022




https://www.metacritic.com/game/pc/lost-judgment

Print this item

  RetroArch - How to Add New Images to Thumbnails/Box-Art
Posted by: SickProdigy - 10-01-2022, 12:01 PM - Forum: PC Discussion - No Replies

Hello everyone, looking to add thumbnails to your Retro Arch media? This works for generally all versions. Been done this way for quite some time.

First, let's check this directory for file that might already be there. (So you can get an idea how files should be named, hoping auto-update at least found something in your list)
RetroArch-1.10.3-64bit\thumbnails\ 
If you don't see anything, just continue with tutorial, we will be explaining everything that should be there.
Also, this works for just about every version of Retro Arch. Not just 1.10.3 but even the newest now 1.11.0

Find the box art you want by searching google "boxart {game name}"

Inside of the directory above, should be different consoles you have downloaded. You can see the image below for an example. Also check the github link below for massive lists already built up.

Inside each console folder is >> "Named_Boxarts", "Named_Snaps", and "Named_Titles"

Add the corresponding png in there and name it exactly as you have the game named in RA, and it will load up

It just scans the folders for corresponding images that match game title names.
If you add the wrong one, just changing the name will remove it, or removing it works normal. Pretty hard to mess this up.

Everything is CASE SENSITIVE. If it isn't name exactly the same as it shows in RA, the image WILL NOT SHOW UP.

[Image: h2epwXm.png]

Your Playlist name should look exactly the same in the RetroArch1.10.3>>thumbnails location. Make sure there isn't a missing dash between console creator - and the version.

Note**
If you check online
https://github.com/libretro-thumbnails/l...thumbnails
They tend to name theirs like this also. So it's best practice to have the same.
If you want your thumbnails to auto grab, the names must match the github libretro link above.

Remember, everything is case-sensitive, so if you don't capitalize the right letters, nothing will pickup. Or forget a comma, not gonna work.

Checkout the image below for BAD EXAMPLES
[Image: Zw7I4F4.png]

[Image: EMnhcMy.png]

Here is an example of a properly named and managed library.
The above is just examples showing you what to watch out for.

[Image: NnCu375.png]
This library has everything right for auto-update to grab thumbnails, and the side images you see to the left. The pic of the console shows properly.

A lot of people tend to ask how to do this, so I have created a short tutorial to explain how.

Print this item

  [Tut] Aave for DeFi Developers – A Simple Guide with Video
Posted by: xSicKxBot - 10-01-2022, 09:43 AM - Forum: Python - No Replies

Aave for DeFi Developers – A Simple Guide with Video

5/5 – (2 votes)
YouTube Video

This is in continuation of our DeFi series. In this post, we look at yet another decentralized lending and borrowing platform Aave.

? Full DeFi Course: Click the link to access our free full DeFi course that’ll show you the ins and outs of decentralized finance (DeFi).

Aave



Aave launched in 2017 is a DeFi protocol similar to Compound with a lot of upgrades.

Beyond what Compound provides, Aave gives several extra tokens for supply and borrowing. As of now, Compound offered nine different tokens (various ERC- 20 Ethereum- based assets).

Aave provides these nine besides an additional 13 that Compound does not.

Depositors give the market liquidity to generate a passive income, while borrowers can borrow if they have an over-collateralized token or can avail flash loans for under-collateralized (one-block liquidity).

Currently, we can see two major markets on Aave.

  • The first is for ERC-20 tokens that are more frequently used, like those of Compound, and their underlying assets, such as ETH, DAI and USDC.
  • The latter is only available with Uniswap LP tokens.

For instance, a user receives an LP token signifying market ownership when they deposit collateral into a liquidity pool on the Uniswap platform. To provide additional benefits, the LP tokens can be sold on the Uniswap market of Aave.

As per DeFi pulse, Aave has a TVL (Total Value Locked) of $4.09B as of today.

Fig: Defi Pulse for Aave

Aave Versions


Aave has released three versions (v1, v2 and v3) as of now and the Governance token of Aave is ‘AAVE’. Version 1 or v1 is the base version launched in 2017 and then there have been upgrades with multiple new features added. Below is a short comparison of when to use v2 or v3.

You should use Aave V2 when:

  • You won’t need to borrow many tokens.
  • Little profit
  • You borrow important tokens like WETH, USDC, etc.

You should use Aave V3 when:

  • Many tokens must be borrowed
  • High profit margin
  • You borrow mid-cap tokens like LINK, etc.

Borrow and Lending in Aave


Fig: Aave borrow and lend (pic credit: https://docs.aave.com)

Borrow


You must deposit any asset to be used as collateral before borrowing.

? The amount you can borrow up to depends on the value you have deposited and the readily available liquidity.

For instance, if there isn’t enough liquidity or if your health factor (minimum threshold of the collateral = 1, below this value, liquidation of your collateral is triggered) prevents it, you can’t borrow an asset.

? The loan is repaid with the same asset that you borrowed.

For instance, if you borrow 1 ETH, you’ll need to pay back 1 ETH plus interest.

In the updated Version 2 of the Aave Protocol, you can also use your collateral to make payments. You can borrow any of the stable coins like USDC, DAI, USDT, etc. if you want to repay the loan based on the price of the USD.

Stable vs Variable Interest Rate


In the short-term, stable rates function as a fixed rate, but they can be rebalanced in the long run in reaction to alterations in the market environment. Depending on supply and demand in Aave, the variable rate can change.

The stable rate is the better choice for forecasting how much interest you will have to pay because, as its name suggests, it will remain fairly stable. The variable rate changes over time and, depending on market conditions, could be the optimal rate.

Through your dashboard, you can switch between the stable and variable rate at any time.

Deposit/Lending


Lenders share the interest payments made by borrowers based on the utilization rate multiplied by the average borrowing rate. The yield for depositors increases as reserve utilization increases.

Lenders are also entitled to a portion of the Flash Loan fees, equal to .09% of the Flash Loan volume.

There is no minimum or maximum deposit amount; you may deposit any amount you choose.

Flash Loans in Aave


Flash Loans are unique business agreements that let you borrow an asset as long as you repay the borrowed money (plus a fee) before the deal expires (also called One Block Borrows). Users are not required to provide collateral for these transactions in order to proceed.

Flash Loans have no counterpart in the real world, so understanding how state is controlled within blocks in blockchains is a prerequisite.

? Flash-loan enables users to access pool liquidity for a single transaction as long as the amount borrowed plus fees are returned or (if permitted) a debt position is opened by the end of the transaction.

For flash loans, Aave V3 provides two choices:

(1) “flashLoan”: enables borrowers to access the liquidity of several reserves in a single flash loan transaction. In this situation, the borrower also has the choice to open a fixed or variable-rate loan position secured by provided collateral.

? The fee for flashloan is waived for approved flash borrowers.

(2) “flashLoanSimple”: enables the borrower to access a single reserve’s liquidity for the transaction. For individuals looking to take advantage of a straightforward flash loan with a single reserve asset, this approach is gas-efficient.

? The fee for flashloanSimple is not waived for the flash borrowers. The Flashloan fee on Aave V3 is 0.05%.

Let’s Code a Simple Flash Loan


Let’s code a simple flash loan in Aave, where we buy and repay the asset in the same transaction without having to provide any collateral. First, we set up the environment for writing the code.

▶ Note: It is recommended to follow the video along for a better understanding.

$npm install -g truffle # in case truffle not installed
$mkdir aave_flashloan $cd aave_flashloan
$truffle init
$npm install @aave/core-v3
$npm install @openzeppelin/contracts
$npm install @openzeppelin/test-helpers

Note: Aave3 is currently available on Polygon, Arbitrum, Avalanche, and other L2 chains. As of now, it is not available on the Ethereum mainnet. Thus, we will fork the Polygon mainnet for our tests.

Set up a new app in Alchemy with the chain as Polygon mainnet and note down the API key.

Create a new file .env and enter the below info.

$WEB3_ALCHEMY_POLYGON_ID=<API key noted above>
$USDC_WHALE=0x075e72a5eDf65F0A5f44699c7654C1a76941Ddc8

? Recommended Tutorial: Solidity Crash Course — Your First Smart Contract

Simple Flash Loan Contract


The contract code (FlashLoanPolygon.sol) in the contracts folder.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@aave/core-v3/contracts/interfaces/IPool.sol";
import "@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol"; contract AaveFlashloan is FlashLoanSimpleReceiverBase { using SafeMath for uint256; using SafeERC20 for IERC20; event Log(string message, uint256 val); constructor(IPoolAddressesProvider provider) FlashLoanSimpleReceiverBase(provider) {} function aaveFlashloan(address loanToken, uint256 loanAmount) external { IPool(address(POOL)).flashLoanSimple( address(this), loanToken, loanAmount, "0x", 0 ); } function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes memory ) public override returns (bool) { require( amount <= IERC20(asset).balanceOf(address(this)), "Invalid balance for the contract" ); // pay back the loan amount and the premium (flashloan fee) uint256 amountToReturn = amount.add(premium); require( IERC20(asset).balanceOf(address(this)) >= amountToReturn, "Not enough amount to return loan" ); approveToken(asset, address(POOL), amountToReturn); emit Log("borrowed amount", amount); emit Log("flashloan fee", premium); emit Log("amountToReturn", amountToReturn); return true; }
}

The contract code contains two important functions.

  • aaveFlashloan() which calls the pools function flashLoanSimple(). Our test code must call this function to initiate a flash loan.
  • executeOperation() is a callback function of the pool which pays the loan + interest back to the pool.

Testing Contract


In the test folder, create a JavaScript file config.js with the following content:

const USDC = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"; const aavePoolAddressesProvider = "0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb"; const USDC_WHALE = process.env.USDC_WHALE; module.exports = { USDC, USDC_WHALE, aavePoolAddressesProvider,
}

In the test folder, create another file testAaveFlashLoanSimple.js:

const BN = require("bn.js");
const IERC20 = artifacts.require("IERC20");
const AaveFlashLoan = artifacts.require("AaveFlashloan");
const {USDC,aavePoolAddressesProvider,USDC_WHALE} = require("./config"); function sendEther(web3, from, to, amount) { return web3.eth.sendTransaction({ from, to, value: web3.utils.toWei(amount.toString(), "ether"), });
} contract("AaveFlashLoan", (accounts) => { const WHALE = USDC_WHALE const TOKEN_BORROW = USDC const DECIMALS = 6 // USDC uses 6 decimal places and not 18 like other ERC20 // We fund more because we need to pay back along with the fees during Flash loan. // So let us fund extra (2 million round figure to the calculations simple) const FUND_AMOUNT = new BN(10).pow(new BN(DECIMALS)).mul(new BN(500)); 500 USDC const BORROW_AMOUNT = new BN(10).pow(new BN(DECIMALS)).mul(new BN(1000000)); // 1 million USDC let aaveFlashLoanInstance let token beforeEach(async () => { token = await IERC20.at(TOKEN_BORROW) // USDC token aaveFlashLoanInstance = await AaveFlashLoan.new(aavePoolAddressesProvider) // send ether to USDC WHALE contract to cover tx fees await sendEther(web3, accounts[0], WHALE, 1) // send enough token to cover fee const bal = await token.balanceOf(WHALE) assert(bal.gte(FUND_AMOUNT), "balance < FUND") // Send USDC tokens to AaveFlashLoan contract await token.transfer(aaveFlashLoanInstance.address, FUND_AMOUNT, { from: WHALE, }) console.log("balance of USDC in AAveFlashLoan contract:", bal2.toString()) }) it("aave simple flash loan", async () => { const tx = await aaveFlashLoanInstance.aaveFlashloan(token.address, BORROW_AMOUNT) console.log("token address:",token.address) for (const log of tx.logs) { console.log(log.args.message, log.args.val.toString()) } }) });

Again, feel free to watch the video at the beginning of this tutorial to understand the testing process.

Open two terminals.

In terminal 1:

$source .env
$npx ganache-cli i – fork https://polygon-mainnet.g.alchemy.com/v2/$WEB3_ALCHEMY_POLYGON_ID \
--unlock $USDC_WHALE \
--networkId 999

This should start a local fork of the Polygon mainnet.

In terminal 2:

$ source .env
$ env $(cat .env) npx truffle test – network polygon_main_fork test/testAaveFlashLoanSimple.js

This should run the flash loan test case, and it must pass.

Conclusion


This tutorial discussed Aave, a leading Dapp lending and borrowing provider.

It covered some basic functionalities supported in Aave, such as lending, borrowing, and flash loans.

There are many other features Aave supports and it is not possible to cover it in one post, such as governance, liquidation, and advanced features such as Siloed Borrowing, Credit Delegation, and many more.

The post also examined a simple flash loan contract using Aave API.

You can explore more about borrowing and lending with Aave in this link. It has a full stack Defi Aave dapp with frontend to perform borrowing and lending.

? Recommended Tutorial: Crypto Trading Bot Developer — Income and Opportunity



https://www.sickgaming.net/blog/2022/09/...ith-video/

Print this item

  (Free Game Key) Runbow and The Drone Racing League Simulator - Free on Epic Games
Posted by: xSicKxBot - 10-01-2022, 09:43 AM - Forum: Deals or Specials - No Replies

Runbow and The Drone Racing League Simulator - Free on Epic Games

Grab these games on the Epic Games Store

❤️ Runbow
Store Page[store.epicgames.com]

❤️ The Drone Racing League Simulator
Store Page[store.epicgames.com]

The games is free to keep until Thursday, September 22nd, 2022 15:00 UTC.



There is another game on GOG dont forget to claim it


We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: HumbleBundle Partner[www.humblebundle.com] Fanatical Affiliate[www.fanatical.com]


https://steamcommunity.com/groups/GrabFr...9931434246

Print this item

  News - Horror And Romance Come Together In Bones And All First Trailer
Posted by: xSicKxBot - 10-01-2022, 09:43 AM - Forum: Lounge - No Replies

Horror And Romance Come Together In Bones And All First Trailer

Camille DeAngelis' 2015 novel Bones and All tells a romantic horror story between Lee and Marlene as they make their way through a road trip in Reagan-era America. Timothée Chalamet and Taylor Russell star in the adaptation as the bloody lovers, directed by Luca Guadagnino (2018's Suspiria). The first teaser was released Thursday and didn't give too much of the plot away, but will leave viewers with some visceral imagery.

Bones and All had its world premiere at the 79th Venice International Film Festival in early September, receiving a 10-minute standing ovation. You can check out the teaser below.

While it's a quick teaser, we can see Maren struggle with her appetite and desires and Lee's rage throughout it, and something very different from what we've seen from Chalamet in past years. Joining Russell and Chalamet are Mark Rylance, Michael Stuhlbarg, André Holland, Chloë Sevigny, Jessica Harper, and David Gordon Green. Chalamet is co-producing the feature.

Continue Reading at GameSpot

https://www.gamespot.com/articles/horror...01-10abi2f

Print this item

  PC - Judgment
Posted by: xSicKxBot - 10-01-2022, 09:43 AM - Forum: New Game Releases - No Replies

Judgment



From the makers of the acclaimed Yakuza series, Ryu Ga Gotoku Studio, Judgment is the dramatic tale of a disgraced lawyer seeking redemption in a world rife with corruption and despair. Investigate the seedy Red Light District of Kamurocho by stepping into the mind of private detective Takayuki Yagami and utilize innovative investigation systems to uncover the secrets that lie deep within Kamurocho's corrupt underbelly. Experience visceral combat with two unique combat styles. Take down groups of thugs with sweeping blows in Crane Style, then switch to Tiger to overwhelm a single foe with a series of powerful strikes. Practice mixing-and-matching styles in combat in conjunction with a wide variety of skills, weapons, and powerful (and hilarious) EX Actions to unlock a whole new dimension in combat.

Publisher: SegaSoft

Release Date: Sep 15, 2022




https://www.metacritic.com/game/pc/judgment

Print this item

  [Tut] How to Retrieve a Single Element from a Python Generator
Posted by: xSicKxBot - 09-30-2022, 11:20 AM - Forum: Python - No Replies

How to Retrieve a Single Element from a Python Generator

5/5 – (2 votes)

This article will show you how to retrieve a single generator element in Python. Before moving forward, let’s review what a generator does.

Quick Recap Generators


? Definition Generator: A generator is commonly used when processing vast amounts of data. This function uses minimal memory and produces results in less time than a standard function.

? Definition yield: The yield keyword returns a generator object instead of a value.

? Definition next(): This function takes an iterator and an optional default value. Each time this function is called, it returns the next iterator item until all items are exhausted. Once exhausted, it returns the default value passed or a StopIteration Error.

Problem Formulation and Solution Overview


? Question: How would we write code to retrieve and return a single element from a Generator?

We can accomplish this task by one of the following options:


Method 1: Use a Generator and random.randint()


This example uses a Generator and the random.randint() function to return a random single element.

Let’s say we want to start a weekly in-house lottery called LottoOne (yeah — the lottery naming doesn’t care about Python’s naming conventions ?).

The code below will generate and return one (1) random element (an integer): the winning number for the week.

import random def LottoOne(): num = random.randint(1, 50) yield print(f'The Winning Number for the Week is: {num}!') gen = LottoOne()
next(gen)

The first line in the above code imports the random library. This library allows the generation of random numbers using the random.randint() function.

On the following line, an instance of LottoOne is instantiated and saved to the variable gen. If output to the terminal, an object similar to that shown below will display.


<generator object LottoOne at 0x00000236B9686880>

Since we only want the first randomly generated number, the code calls the next() function once and passes it one (1) argument, the object gen. The results are output to the terminal.


The Winning Number for the Week is: 44

YouTube Video

? Recommended Tutorial: An Introduction to Python Classes


Method 2: Use a Generator and islice()


This example uses a generator and the itertools.islice() function to return a single element.

If you know what number you need to return from a generator, it can be referenced directly, as shown in the code below.

import itertools
from itertools import islice gen = (x for x in range(1, 50))
res = next(itertools.islice(gen, 2, None))
print(res)

The first two (2) lines in the above code import the itertools library and its associated function islice() needed to achieve the desired result.

The following line creates a generator comprehension using the range() function and passing it a start and stop position (1, 50-1). The results save to gen as an object.

If output to the terminal, an object similar to that shown below will display.


<generator object at 0x00000285D4DB68F0>

Then, the next() function is called and passed one (1) argument, itertools.islice().

This function is then passed three (3) arguments:

  1. An iterator. In this case, gen.
  2. The value to return, idx.
  3. The default value. In this case, the keyword None. Passing a default value prevents a StopIteration error from occurring when the end of the iterator has been reached.

The results save to res and are output to the terminal.


3

The value of 3 can be found at index 2 in gen.

YouTube Video


Method 3: Use a List, Generator Comprehension and slicing


This example uses a list, generator comprehension and slicing to return a single element.

gen = (i for i in range(1, 50))
res = list(gen)[3]
print(res)

The first line in the above code creates a Generator Comprehension using the range() function and passing it a start and stop position (1, 50-1). The results save to gen as an object.

If output to the terminal, an object similar to that shown below will display.


<generator object at 0x00000295D4DB78F0>

The following line converts the object to a list. Slicing is then applied to retrieve the list element at position three (3).

The results save to res and are output to the terminal.


4

The value of 4 can be found at index 3 in gen.

YouTube Video


Method 4: Use a Generator and a For Loop


This example creates a Generator whose content is output to the terminal until a specific number is found.

def my_func(): yield 10 yield 20 yield 30 gen = my_func() for item in gen: if item == 20: print(item) break

This first line of the above code declares the function my_func(). This function will return, via a yield statement, a number (one/iteration).

Next, an object is declared and saved to gen.

If output to the terminal, an object similar to that shown below will display.


<generator object my_func at 0x0000022DE93D59A0>

The following line instantiates a for loop. This loop iterates through each yield statement in gen until the item contains a value of 20.

This value is output to the terminal, and the loop terminates via the break statement.


20


Summary


This article has provided four (4) ways to retrieve a single element from a Generator to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor – Python


“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd



https://www.sickgaming.net/blog/2022/09/...generator/

Print this item

  [Tut] Amazon like Product Category Tree
Posted by: xSicKxBot - 09-30-2022, 11:19 AM - Forum: PHP Development - No Replies

Amazon like Product Category Tree

by Vincy. Last modified on September 29th, 2022.

This PHP script will help if you want to display an Amazon-like product category tree. It will be useful for displaying the category menu in a hierarchical order, just like a tree.

The specialty of this PHP code is that it builds a multi-level category tree with infinite depth. It uses the recursion method to obtain this.

In a previous tutorial, we have to see a multi-level dropdown menu with a fixed depth.

Let’s look into the upcoming sections to see how the code is built to display the category tree in a page.

category tree

Category Database


This script contains the category database with data. The insert query creates category records which are mapped with its parent appropriately.

The category records containing parent=0 are known as the main category. Each record has the sort order to set the display priority on the UI.

structure.sql

CREATE TABLE `category` ( `id` int(10) UNSIGNED NOT NULL, `category_name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `parent` int(10) UNSIGNED NOT NULL DEFAULT 0, `sort_order` int(11) NOT NULL DEFAULT 0
); --
-- Dumping data for table `category`
-- INSERT INTO `category` (`id`, `category_name`, `parent`, `sort_order`) VALUES
(1, 'Features', 0, 0),
(2, 'Domain', 0, 1),
(3, 'Digital', 0, 2),
(4, 'Gift cards', 1, 0),
(5, 'International', 1, 1),
(6, 'Popular', 1, 2),
(7, 'e-Gift cards', 4, 0),
(8, 'Business gift cards', 4, 1),
(9, 'In offer', 5, 0),
(10, 'Shipping', 5, 1),
(11, 'Celebrity favourites', 6, 0),
(12, 'Current year hits', 6, 1),
(13, 'Electronics', 2, 0),
(14, 'Arts', 2, 1),
(15, 'Gadgets', 2, 2),
(16, 'Camera', 13, 0),
(17, 'Car electronic accessories', 13, 1),
(18, 'GPS', 13, 2),
(19, 'Handcrafted', 14, 0),
(20, 'Gold enameled', 14, 1),
(21, 'Jewelry', 14, 2),
(22, 'Fabric', 19, 0),
(23, 'Needle work', 19, 1),
(24, 'PSP', 15, 0),
(25, 'Smart phones', 15, 1),
(26, 'Apps', 3, 0),
(27, 'Music', 3, 1),
(28, 'Movies', 3, 2),
(29, 'Dev apps', 26, 0),
(30, 'App Hardwares', 26, 1),
(31, 'Podcasts', 27, 0),
(32, 'Live', 27, 1),
(33, 'Recently viewed', 28, 0),
(34, 'You may like', 28, 1),
(35, 'Blockbusters', 28, 2); --
-- Indexes for dumped tables
-- --
-- Indexes for table `category`
--
ALTER TABLE `category` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;

Category menu rendering in HTML


This is an initiator that calls the PHP recursive parsing to get the Category Tree HTML. In the PHP ZipArchive post, we used the same recursion concept to compress the contents of the enclosed directories.

Also, it has a UI holder to render the HTML hierarchical category menu.

A PHP class CategoryTree is created to read and parse the category array from the database.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
require_once __DIR__ . '/CategoryTree.php';
$categoryTree = new CategoryTree();
$categoryResult = $categoryTree->getCategoryResult();
?>
<h1>Choose category</h1> <div class="category-menu">
<?php
echo $categoryTree->getCategoryTreeHTML($categoryResult);
?>
</div>
</body>
</html>

This styles gives the category tree a pleasing look. Since it displays an infinite level of child categories, this CSS will help to rectify the default UI constraints.

body { font-family: Arial; margin-left: 10px; margin-right: 20px;
} ul.category-container li { list-style: none; padding-left: 10px; width: 100%;
} .category-container a { text-decoration: none; color: #000;
} .parent-depth-0 { font-size: 22px; font-weight: bold; border-bottom: #ccc 1px solid; padding: 15px 0px 15px 0px;
} .parent-depth-all { font-size: 16px; padding-top: 15px; font-weight: normal;
} .no-child { font-size: 16px; font-weight: normal; padding: 15px 0px 0px 0px;
} .category-menu { width: 270px; overflow-y: scroll; max-height: 800px; background: #fffcf2; padding: 0px;
} ul.category-container { padding: 10px;
}

Read category data and build in tree format


This is the main PHP class that reads the dynamic categories from the database.

The getCategoryTreeHTML the function parses the category result array. It recursively calls and parses the levels of category by its parent.

In WordPress, there is a category walker to parse the terms and taxonomies. We have created a custom WordPress walker to parse categories efficiently.

It sets the argument parent=0 to build parent-level category menu items.

The resultant category tree HTML will be a nested UL-LI list to show the multi-level menu.

CategoryTree.php

<?php class CategoryTree
{ private $connection; function __construct() { $this->connection = mysqli_connect('localhost', 'root', '', 'db_category_tree'); } function getCategoryTreeHTML($category, $parent = 0) { $html = ""; if (isset($category['parentId'][$parent])) { $html .= "<ul class='category-container'>\n"; foreach ($category['parentId'][$parent] as $cat_id) { if (! isset($category['parentId'][$cat_id])) { $child = ""; if ($category['categoryResult'][$cat_id]['parent'] != 0) { $child = "no-child"; } $html .= "<li class= '$child " . "parent-" . $category['categoryResult'][$cat_id]['parent'] . "' >\n" . $category['categoryResult'][$cat_id]['category_name'] . "</li> \n"; } if (isset($category['parentId'][$cat_id])) { $parentDepth0 = "parent-depth-all"; if ($category['categoryResult'][$cat_id]['parent'] == 0) { $parentDepth0 = "parent-depth-0"; } $html .= "<li class= '$parentDepth0 " . 'parent-' . $category['categoryResult'][$cat_id]['parent'] . "'>\n " . $category['categoryResult'][$cat_id]['category_name'] . " \n"; $html .= $this->getCategoryTreeHTML($category, $cat_id); $html .= "</li> \n"; } } $html .= "</ul> \n"; } return $html; } function getCategoryResult() { $query = "SELECT * FROM category ORDER BY parent, sort_order"; $result = mysqli_query($this->connection, $query); $category = array(); while ($row = mysqli_fetch_assoc($result)) { $category['categoryResult'][$row['id']] = $row; $category['parentId'][$row['parent']][] = $row['id']; } return $category; }
}
?>

Where category tree code can be used?


The category tree is used in many places. For example, most shopping cart websites have a category filter or menu to classify the showcase products.

The Amazon shop’s category menu ads value to the end user to narrow down the vast area to find their area of interest.

Also, tutorial websites display the table of contents in the form of a tree order.

Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/09/...gory-tree/

Print this item

 
Latest Threads
௹©Ukraine Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©Morocco Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©USA Shein COUPON Code ...
Last Post: udwivedi923
4 hours ago
௹©Armenia Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©Brazil Shein COUPON Cod...
Last Post: udwivedi923
4 hours ago
௹©South Africa Shein COUP...
Last Post: udwivedi923
4 hours ago
௹©Moldova Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©Malta Shein COUPON Code...
Last Post: udwivedi923
4 hours ago
௹©Luxembourg Shein COUPON...
Last Post: udwivedi923
4 hours ago
௹©Kazakhstan Shein COUPON...
Last Post: udwivedi923
4 hours ago

Forum software by © MyBB Theme © iAndrew 2016