It's time to start working towards that ultimate goal of enlightenment, faith and money... lots and lots of money. Create, customise, expand and manage your own cult whilst listening to funky music in Honey, I Joined a Cult!
Posted by: xSicKxBot - 11-18-2022, 10:38 AM - Forum: Python
- No Replies
Python decode()
5/5 – (1 vote)
This tutorial explains the Python decode() method with arguments and examples. Before we dive into the Python decode() method, let’s first build some background knowledge about encoding and decoding so you can better understand its purpose.
Encoding and Decoding – What Does It Mean?
Programs must handle various characters in several languages. Application developers often internationalize programs to display messages and error outputs in various languages, be it English, Russian, Japanese, French, or Hebrew.
Python’s string type uses the Unicode Standard to represent characters, which lets Python programs work with all possible characters.
Unicode aims to list every character used by human languages and gives each character its unique code. The Unicode Consortium specifications regularly update its specifications for new languages and symbols.
A character is the smallest component of the text. For example, ’a, ‘B’, ‘c’, ‘È’ and ‘Í’ are different characters. Characters vary depending on language or context. For example, the character for “Roman Numeral One” is ‘Ⅰ’, separate from the uppercase letter ‘I’. Though they look the same, these are two different characters that have different meanings.
The Unicode standard describes how code points represent characters. A code point value is an integer from 0 to 0x10FFFF. [1]
What are Encodings?
A sequence of code points forms a Unicode String represented in memory as a set of code units. These code units are mapped to 8-bit bytes. Character Encoding is the set of rules to translate a Unicode string to a byte sequence.
UTF-8 is the most commonly used encoding, and Python defaults to it. UTF stands for “Unicode Transformation Format”, and the ‘8’ refers to 8-bit values used in the encoding. [2]
Python decode()
Encoders and decoders convert text between different representations, and specifically, the Python bytesdecode() function converts bytes to string objects.
The decode() method converts/decodes from one encoding scheme for the argument string to the desired encoding scheme. It is the opposite of the Python encode() method.
decode() accepts the encoding of the encoded string, decodes it, and returns the original string.
Specifies the encoding to decode. Standard Encodings has a list of all encodings.
errors (optional)
Decides how to handle the errors:
'strict'[default], meaning encoding errors raise a UnicodeError.
Other possible values are:
'ignore' – Ignore the character and continue with the next
'replace' – Replace with a suitable replacement character
'xmlcharrefreplace' – Inserts an XML character reference
'backslashreplace' – Inserts a backslash escape sequence (\uNNNN) instead of un-encodable Unicode characters
'namereplace' – Inserts a \N{...} escape sequence and any other name registered via codecs.register_error()
Example 1
text = "Python Decode converts text string from one encoding scheme to the desired one."
encoded_text = text.encode('ubtf8', 'strict')
print("Encoded String: ", encoded_text)
print("Decoded String: ", encoded_text.decode('utf8', 'strict'))
Encoded String: b'Python Decode converts text from one encoding scheme to desired encoding scheme.'
Decoded String: Python Decode converts text from one encoding scheme to desired encoding scheme.
Example 2
>>> b'\x81abc'.decode("utf-8", "strict")
Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> b'\x81abc'.decode("utf-8", "strict")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte
>>> b'\x80abc'.decode("utf-8", "backslashreplace") '\\x80abc'
>>> b'\x80abc'.decode("utf-8", "ignore") 'abc'
Tales Deals, Fear Fighters Bundle, Mile Morales Pre-Order
Fear Fighters Bundle | 8 Steam Games | 96% OFF
[www.indiegala.com] The scary season is gone, but we'll still fight fear with fun! A new indie collection brought to you by the Fear Fighters Bundle at only $0.99 in the first 24 hours!
A global squad of iconic veterans and new legends of yet untold clandestine missions, these Operators are set to deliver a new era of Call of Duty when Modern Warfare II releases on October 28, 2022.
Initial asset intel brings revelations about key members of Task Force 141, including Team leader Captain John Price, Sergeant Kyle "Gaz" Garrick, Sergeant "Soap" MacTavish, lone-wolf Simon "Ghost" Riley, and Colonel Alejandro Vargas of the Mexican Special Forces.
Solidity Ether Units, Time Units, and Global Variables
5/5 – (1 vote)
With this article, we’re opening a new area of our study, that of units and globally available variables in Solidity.
To begin with, we’ll learn about ether units and time units. After that, we’ll start with a block of subsections on special variables and functions, stretching through this and the next two articles.
It’s part of our long-standing tradition to make this (and other) articles a faithful companion, or a supplement to the official Solidity documentation.
Ether Units
When mentioning Ether units of currency, we can express them with a literal number and a suffix of wei, gwei or ether.
These suffixes specify a sub-denomination of Ether. We assume amounts written without a suffix as Wei.
The purpose and effect of using sub-denomination is a multiplication of the denomination by a power (exponent) of ten.
Note: There can be found denominations, such as finney and szabo, but they were deprecated in Solidity v0.7.0.
Time Units
Solidity has a nice and natural way of expressing time units with suffixes, such as seconds, minutes, hours, days, and weeks.
Seconds are the base unit, and units are considered to correspond to:
1 == 1 seconds
1 minutes == 60 seconds
1 hours == 60 minutes
1 days == 24 hours
1 weeks == 7 days
When working with calendar calculations using these units, we should take extra care, because only some years have 365 days, and because of leap seconds, not even every day has 24 hours.
Since leap seconds are unpredictable, an exact calendar always has to be updated by an external source (oracle), which motivated Solidity authors to remove the suffix years in Solidity v0.5.0.
We should remember that these suffixes cannot be applied to variables, meaning if we want to interpret a function parameter expressed in days, we can easily do so like in the example below:
function f(uint start, uint daysAfter) public { if (block.timestamp >= start + daysAfter * 1 days) { // ... }
}
Special Variables and Functions
The global namespace contains special variables and functions primarily used to provide us with information about the blockchain. They are also available utility functions for general use.
Block and Transaction Properties
The following is a list of block and transaction properties, as shown in the official Solidity documentation. Parentheses next to each block/transaction property define the member type:
blockhash(uint blockNumber) returns (bytes32): hash of the given block when blocknumber is one of the 256 most recent blocks; otherwise returns zero
block.basefee (uint): current block’s base fee (as defined in Ethereum Improvement Proposals EIP-3198 and EIP-1559)
block.chainid (uint): current chain id
block.coinbase (address payable): current block miner’s address
block.difficulty (uint): current block difficulty
block.gaslimit (uint): current block gas limit
block.number (uint): current block number
block.timestamp (uint): current block timestamp as seconds since Unix epoch
gasleft() returns (uint256): remaining gas
msg.data (bytes calldata): complete calldata
msg.sender (address): the sender of the message (current call)
msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier)
msg.value (uint): number of Wei sent with the message
tx.gasprice (uint): the gas price of the transaction
tx.origin (address): the sender of the transaction (full call chain)
Note: We should expect the values of all members of msg, including msg.sender and msg.value will change with every external function call. This expectation also applies to library functions.
Info: Off-chain computation is simply a computation that takes place outside a blockchain. Oracle networks can provide a trust-minimized form of off-chain computation to extend the capabilities of blockchains – this is known as oracle computation. (Chainlink)
Contracts can be evaluated both off-chain and on-chain, i.e. in the context of a transaction included in a block.
If a contract is evaluated off-chain, we should assume that block.* and tx.* members don’t refer to a specific block or transaction. Instead, the values we’d find in these members are provided by the EVM implementation executing the contract, and therefore, they can be completely arbitrary.
Note: It is suggested to avoid block.timestamp or blockhash member values as sources of randomness. The reason for this suggestion lies in the fact that, in some instances, miners can manipulate both the timestamp and the block hash. The timestamp of the current block must be strictly larger than the timestamp of the last block, and the only thing we can know for sure is that it will be between the timestamps of two neighboring blocks in the canonical chain; how far it will be from any particular block timestamp is not known.
Info: “The word canonical is used to indicate a particular choice from a number of possible conventions. This convention allows a mathematical object or class of objects to be uniquely identified or standardized.” (Wolfram.com)
Only the recent 256 blocks’ hashes are available, due to scalability reasons. A hash of any older block will be zero.
In Solidity versions prior to 0.5, the current blockhash(...) function was previously known and available as block.blockhash(...); the current gasleft(...) function was previously known and available as msg.gas(...).
In Solidity v0.7.0 the now alias (for block.timestamp) was removed.
ABI Encoding and Decoding Functions
The following list contains ABI-appropriate functions for low-level interactions with EVM, as laid out in the official Solidity documentation:
abi.decode(bytes memory encodedData, (...)) returns (...): ABI-decodes the given data, while the types are given in parentheses as second argument. Example: (uint a, uint[2] memory b, bytes memory c) = abi.decode(data, (uint, uint[2], bytes))
abi.encode(...) returns (bytes memory): ABI-encodes the given arguments
abi.encodePacked(...) returns (bytes memory): Performs packed encoding of the given arguments. Note that packed encoding can be ambiguous!
abi.encodeWithSelector(bytes4 selector, ...) returns (bytes memory): ABI-encodes the given arguments starting from the second and prepends the given four-byte selector
abi.encodeCall(function functionPointer, (...)) returns (bytes memory): ABI-encodes a call to functionPointer with the arguments found in the tuple. Performs a full type-check, ensuring the types match the function signature. Equivalent to abi.encodeWithSelector(functionPointer.selector, (...))
Note: “These encoding functions can be used to craft data for external function calls without actually calling an external function. Furthermore, keccak256(abi.encodePacked(a, b)) is a way to compute the hash of structured data (although be aware that it is possible to craft a “hash collision” using different function parameter types).” (docs)
Conclusion
In this article, we learned about ether and time units, followed by special variables and functions.
First, we introduced ether units and discussed the use of the main unit and its sub-denominations.
Second, we introduced time units and discussed the possibilities of expressing time in different time units.
Third, we took a closer look at the block and transaction properties, but also listed many of them with descriptions and notes on specific behaviors for a more thorough understanding.
Fourth, we also touched on the topic of ABI encoding and decoding functions, described them, and gave a usage hint in a form of a note.
What’s Next?
This tutorial is part of our extended Solidity documentation with videos and more accessible examples and explanations. You can navigate the series here (all links open in a new tab):
OG Warzone Goes Offline Today As Warzone 2.0 Launches
[UPDATE] The original Call of Duty: Warzone is now officially offline. GameSpot attempted to play the original Warzone on Xbox today and we were not able to. The game instead directs players to Warzone 2.0, which launched today, November 16.
Goodbye, Warzone
Activision is marking the end of Warzone, too, with a Twitter post asking fans to press F to pay respects, leaning into the popular meme. Warzone will be offline for 12 days, returning November 28, if all goes to plan. Activision will continue to support the game, but the extent to which it will do so is unknown.
The end of an era, but the start of a great new one in #Warzone2
The games are free to keep if claimed by Thursday, 24th November 2022 16:00 UTC
Next weeks freebies: Star Wars Squadrons
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.
- Third Person Mode - Allows you to enjoy the main game from a third-person perspective.
- The Mercenaries Additional Orders - Adds new playable characters and stages.
- Shadows of Rose - Introduces a new story with Ethan's daughter Rose as the protagonist.
16 years have passed since that incident... Ethan's beloved daughter, Rosemary Winters, is living a healthy life. But struggling to come to terms with her innate special powers, she decides to dive into the world of the Megamycete's consciousness, or the "realm of consciousness," to seal them.
What she discovers is an extraordinary world far from the reality of the past. A collection of memories of "that village" absorbed by the Megamycete.
Posted by: xSicKxBot - 11-16-2022, 11:10 AM - Forum: Python
- No Replies
Getting To Know Your Basic UCTRONICS Raspberry Pi Pico Kit
5/5 – (1 vote)
Now that we’ve covered Thonny and MicroPython, it’s time to get to know the components in your basic Raspberry Pi Pico kit.
Note: There is more than one kit out there, but it is this author’s opinion that the best value for beginners is the one from UCTRONICS. Most of them have similar components, but this one just happens to be my go-to and is the subject of this installment.
*If you have not yet read our previous installments on learning MicroPython for the Raspberry Pi Pico or Thonny, be sure you review those before moving beyond this short tutorial.
Alright, let’s jump in! Here’s what the kit looks like:
First things first, though. We’re going to start with the Pico itself. The main thing you’ll need to know about it (at least for the purposes of doing experiments) is its pins.
Your Pico and Its Pins
Your Pico talks to hardware through a series of pins along both its edges. Most of these pins work as a general-purpose input/output (GPIO) pin, meaning they can be programmed to act as either an input or an output and have no fixed purpose of their own.
Some pins have extra features and alternative modes for communicating with more complicated hardware;
Others have a fixed purpose, providing connections for things like power.
Raspberry Pi Pico’s 40 pins are labeled on the underside of the board, with three also labeled with their numbers on the top of the board: Pin 1, Pin 2, and Pin 39.
These top labels help you remember how the numbering works: Pin 1 is at the top left as you look at the board from above with the micro USB port to the upper side, Pin 20 is the bottom left, Pin 21 the bottom right, and Pin 39 one below the top right with the unlabeled Pin 40 above it.
While you will generally use actual pin numbers when writing your code, we may reference some of them by their functions, as well.
As you can see, there are several different kinds of pins with different functions. Here’s a quick reference guide to help you remember:
You’ll learn more about these functions in later tutorials as we get into projects. For now, all you need to focus on is the basics. This is not meant to be an exhaustive electronics course.
Other Electronic Components
Obviously, your Pico isn’t the only thing you’re going to need if you’re going to be conducting any experiments.
The other things are the components that your Pico’s pins will be controlling. There are tons of components out there, but the cool thing about this kit is that these are useful regardless of how complicated your projects ultimately get – and if you have fun with these, I guarantee you’ll start coming up with your own.
Breadboard
Anyway, let’s start with the second most important component (well, besides the micro USB cord that connects the Pico to your computer) – your breadboard.
This little beauty makes life a WHOLE lot easier. This unit eliminates the need for a circuit board and soldering. Instead, you can just shove – ok, maybe not shove, but insert – wires and pins into the right spots and remove them as needed to do new projects. Hard to beat that!
Jumper Wires
Next are your jumper wires, which connect components to circuits on your breadboard and take the place of those little “wire trails” you see on circuit boards.
That way, they aren’t permanent and can be moved as you see fit. They can also be used to lengthen wires or pins as needed.
To accomplish this, they come in 3 types – male-to-male (M2M), male-to-female (M2F), and of course F2F (can you guess?).
Momentary Switch
Next up, we have a push-button switch, or momentary switch. This doodad is exactly what it looks like – a button.
However, in this case, it’s not the same as a latching switch, which stays depressed once you click it. This one only has to be held down to make it keep working.
Now this one’s going to shock you. It’s called… a light-emitting diode, or LED! I know, I know, you’ve never heard of it, right?
I don’t think I have to say much of anything about these, but I will make two points.
First, not all LEDs are going to work with your Pico. 5V and 12V aren’t good, so if you decide to buy more, make sure you keep that in mind.
Second, the two legs are different lengths. The long one is positive, and the short is negative.
When we’re running a current through stuff, we can sometimes run the risk of blowing them out, especially the LEDs. So how do we prevent that from happening?
Resistor
With resistors, of course! Now, there are a lot of resistors out there with different stripes on them to tell you the level of resistance they provide in a unit called ohms(?). I’m not going to get into that kind of detail here because it isn’t necessary for Pico jobs.
Suffice it to say that if you run out of resistors and want more, you’ll be using little 330? guys.
Just one little note – yours might not be the same color, but the stripes will be. The ones I got in my kit are blue, but that doesn’t matter; 330? is 330?.
Piezoelectric Buzzer
Everyone’s favorite component to play with – well, as long as you have people in your place to annoy – is the piezoelectric buzzer. Oh, boy, this one’s fun! It does exactly what its name indicates, and it does it by vibrating two metal plates together when a current is run through it. Heh, heh.
I’m an avid guitar player, and I LOVE the electric guitar the most. I’m the heaviest of metal heads! Ok, maybe not that heavy. I only clock in at 5’7” and 140lb. Sorry – if you’re not an American reader, that ain’t big. Martial arts has done me a lot of good in life.
Aaaaaaaanyway, there are at least two knobs on an electric guitar – one for volume, and one for tone.
Potentiometer
These both use potentiometers that can be used either as a variable resistor (with two legs connected) or a voltage divider (with all three wired up). In other words, one hookup controls ohms and the other controls volts. I’ll let you guess which version controls which function on the guitar.
Motion Detector
Ever tried to break into somebody’s house, but they had one of those pesky motion detectors that lit up the whole property and nearly got you busted? No? I guess that’s just… a friend…
Well, you get one of those pesky… I mean… cool motion detectors, too. It’s actually called a passive infrared sensor (PIR), and it makes things happen when you wave your hand in front of it. Better than a button? You be the judge.
Screen and Display
Last but not least (I love overused, trite cliches, don’t you?), we have a screen. It’s actually called an inter-integrated circuit or I2C display. It can show all kinds of nifty stuff from text to pictures. There are some fun things to do with this baby!
Obviously, there are other components you can get like motors, current sensors, reverse-LEDs, and a whole host of things. Some of them require special drivers and such, though, so they wouldn’t be considered basic. For the purposes of this series, we will be focusing on more basic components and projects before graduating to higher-level (and more expensive) experiments.
Keep Learning!
Next time, we’ll get into our first project. It’s pretty easy, but it’s fun and totally worth it. I can’t wait to get started, so I’ll talk to you soon. Until then, try some more of the MicroPython I taught you before. Happy coding!