Formatting | Type-safe , functional string formatting in Swift | Code Quality library
kandi X-RAY | Formatting Summary
kandi X-RAY | Formatting Summary
Traditional string formatting methods (interpolation, printf, and template strings) can lead to subtle (and not so subtle) runtime bugs. Formatting brings compile-time checks.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of Formatting
Formatting Key Features
Formatting Examples and Code Snippets
@Setup
public void setup() {
src = " White spaces left and right ";
ltrimResult = "White spaces left and right ";
rtrimResult = " White spaces left and right";
}
@RequestMapping(value = "/formatting_tags", method = RequestMethod.GET)
public ModelAndView formattingTags(final Model model) {
ModelAndView mv = new ModelAndView("formatting_tags");
return mv;
}
public void showCodeSnippetFormattingUsingCodeTag() {
// do nothing
}
Community Discussions
Trending Discussions on Formatting
QUESTION
How can I specify a format string for a boolean that's consistent with the other format strings for other types?
Given the following code:
...ANSWER
Answered 2022-Feb-23 at 23:46Unfortunately, no, there isn't.
According to Microsoft, the only data types with format strings are:
- Date and time types (
DateTime, DateTimeOffset
) - Enumeration types (all types derived from
System.Enum
) - Numeric types (
BigInteger, Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, UInt64
) Guid
TimeSpan
Boolean.ToString() can only return "True" or "False". It even says, if you need to write it to XML, you need to manually perform ToLowerCase()
(from the lack of string formatting).
QUESTION
ANSWER
Answered 2022-Jan-13 at 15:07QUESTION
Background
I have a complex nested JSON object, which I am trying to unpack into a pandas df
in a very specific way.
JSON Object
this is an extract, containing randomized data of the JSON object, which shows examples of the hierarchy (inc. children) for 1x family (i.e. 'Falconer Family'), however there is 100s of them in total and this extract just has 1x family, however the full JSON object has multiple -
ANSWER
Answered 2022-Feb-16 at 06:41I think this gets you pretty close; might just need to adjust the various name
columns and drop the extra data (I kept the grouping
column).
The main idea is to recursively use pd.json_normalize with pd.concat for all availalable children
levels.
EDIT: Put everything into a single function and added section to collapse the name
columns like the expected output.
QUESTION
How can I extract all the code (chunks) from an RMarkdown (.Rmd) file and dump them into a plain R script?
Basically I wanted to do the complementary operation described in this question, which uses chunk options to pull out just the text (i.e. non-code) portion of the Rmd.
So concretely I would want to go from an Rmd file like the following
...ANSWER
Answered 2022-Feb-19 at 10:53You could use knitr::purl
, see convert Markdown to R script :
QUESTION
Somewhere between Java 11 and 17 currency formatting changed to where this:
...ANSWER
Answered 2022-Jan-30 at 03:49I dug a bit into this, the JDK locale data comes from Unicode CLDR by default, and it seems they reverted from $ CA
to $
back in August, see CLDR-14862 and this commit (expand common/main/fr_CA.xml
and then go to lines 5914/5923).
This was part of v40, released in October, so too late for JDK 17 whose doc says it uses CLDR v35.1 (which was introduced in Java 13) but it seems it was updated to v39 in April 2021 and they forgot the release note (JDK 16 appears to have been upgraded to v38 already).
CLDR v40 is planned for JDK 19.
You may want to run your application using the COMPAT
locales first, with
QUESTION
From various sources, I have come to the understanding that there are four main techniques of string formatting/interpolation in Python 3 (3.6+ for f-strings):
- Formatting with
%
, which is similar to C'sprintf
- The
str.format()
method - Formatted string literals/f-strings
- Template strings from the standard library
string
module
My knowledge of usage mainly comes from Python String Formatting Best Practices (source A):
str.format()
was created as a better alternative to the%
-style, so the latter is now obsolete- However,
str.format()
is vulnerable to attacks if user-given format strings are not properly handled
- However,
- f-strings allow
str.format()
-like behavior only for string literals but are shorter to write and are actually somewhat-optimized syntactic sugar for concatenation - Template strings are safer than
str.format()
(demonstrated in the first source) and the other two methods (implied in the first source) when dealing with user input
I understand that the aforementioned vulnerability in str.format()
comes from the method being usable on any normal strings where the delimiting braces are part of the string data itself. Malicious user input containing brace-delimited replacement fields can be supplied to the method to access environment attributes. I believe this is unlike the other ways of formatting where the programmer is the only one that can supply variables to the pre-formatted string. For example, f-strings have similar syntax to str.format()
but, because f-strings are literals and the inserted values are evaluated separately through concatenation-like behavior, they are not vulnerable to the same attack (source B). Both %
-formatting and Template strings also seem to only be supplied variables for substitution by the programmer; the main difference pointed out is Template's more limited functionality.
I have seen a lot of emphasis on the vulnerability of str.format()
which leaves me with questions of what I should be wary of when using the other techniques. Source A describes Template strings as the safest of the above methods "due to their reduced complexity":
The more complex formatting mini-languages of the other string formatting techniques might introduce security vulnerabilities to your programs.
- Yes, it seems like f-strings are not vulnerable in the same way
str.format()
is, but are there known concerns about f-string security as is implied by source A? Is the concern more like risk mitigation for unknown exploits and unintended interactions?
I am not familiar with C and I don't plan on using the clunkier %
/printf
-style formatting, but I have heard that C's printf
had its own potential vulnerabilities. In addition, both sources A and B seem to imply a lack of security with this method. The top answer in Source B says,
String formatting may be dangerous when a format string depends on untrusted data. So, when using str.format() or %-formatting, it's important to use static format strings, or to sanitize untrusted parts before applying the formatter function.
- Do
%
-style strings have known security concerns? - Lastly, which methods should be used and how can user input-based attacks be prevented (e.g. filtering input with regex)?
- More specifically, are Template strings really the safer option? and Can f-strings be used just as easily and safely while granting more functionality?
ANSWER
Answered 2022-Jan-18 at 12:53It doesn't matter which format you choose, any format and library can have its own downsides and vulnerabilities. The bigger questions you need to ask yourself is what is the risk factor and the scenario you are facing with, and what are you going to do about it. First ask yourself: will there be a scenario where a user or an external entity of some kind (for example - an external system) sends you a format string? If the answer is no, there is no risk. If the answer is yes, you need to see whether this is needed or not. If not - remove it to eliminate the risk. If you need it - you can perform whitelist-based input validation and exclude all format-specific special characters from the list of permitted characters, in order to eliminate the risk. For example, no format string can pass the ^[a-zA-Z0-9\s]*$ generic regular expression.
So the bottom line is: it doesn't matter which format string type you use, what's really important is what do you do with it and how can you reduce and eliminate the risk of it being tampered.
QUESTION
I've run into this issue today, and it's only started today. Ran the usual sequence of installs and pushes to build the app...
...ANSWER
Answered 2021-Nov-20 at 19:28I am following along with the Amplify tutorial and hit this roadblock as well. It looks like they just upgraded the react components from 1.2.5 to 2.0.0 https://github.com/aws-amplify/docs/pull/3793
Downgrading ui-react
to 1.2.5 brings back the AmplifySignOut and other components used in the tutorials.
in package.json:
QUESTION
I have tried speeding up a toy GEMM implementation. I deal with blocks of 32x32 doubles for which I need an optimized MM kernel. I have access to AVX2 and FMA.
I have two codes (in ASM, I apologies for the crudeness of the formatting) defined below, one is making use of AVX2 features, the other uses FMA.
Without going into micro benchmarks, I would like to try to develop an understanding (theoretical) of why the AVX2 implementation is 1.11x faster than the FMA version. And possibly how to improve both versions.
The codes below are for a 3000x3000 MM of doubles and the kernels are implemented using the classical, naive MM with an interchanged deepest loop. I'm using a Ryzen 3700x/Zen 2 as development CPU.
I have not tried unrolling aggressively, in fear that the CPU might run out of physical registers.
AVX2 32x32 MM kernel:
...ANSWER
Answered 2021-Dec-13 at 21:36Zen2 has 3 cycle latency for vaddpd
, 5 cycle latency for vfma...pd
. (https://uops.info/).
Your code with 8 accumulators has enough ILP that you'd expect close to two FMA per clock, about 8 per 5 clocks (if there aren't other bottlenecks) which is a bit less than the 10/5 theoretical max.
vaddpd
and vmulpd
actually run on different ports on Zen2 (unlike Intel), port FP2/3 and FP0/1 respectively, so it can in theory sustain 2/clock vaddpd
and vmulpd
. Since the latency of the loop-carried dependency is shorter, 8 accumulators are enough to hide the vaddpd
latency if scheduling doesn't let one dep chain get behind. (But at least multiplies aren't stealing cycles from it.)
Zen2's front-end is 5 instructions wide (or 6 uops if there are any multi-uop instructions), and it can decode memory-source instructions as a single uop. So it might well be doing 2/clock each multiply and add with the non-FMA version.
If you can unroll by 10 or 12, that might hide enough FMA latency and make it equal to the non-FMA version, but with less power consumption and more SMT-friendly to code running on the other logical core. (10 = 5 x 2 would be just barely enough, which means any scheduling imperfections lose progress on a dep chain which is on the critical path. See Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? (Unrolling FP loops with multiple accumulators) for some testing on Intel.)
(By comparison, Intel Skylake runs vaddpd/vmulpd on the same ports with the same latency as vfma...pd, all with 4c latency, 0.5c throughput.)
I didn't look at your code super carefully, but 10 YMM vectors might be a tradeoff between touching two pairs of cache lines vs. touching 5 total lines, which might be worse if a spatial prefetcher tries to complete an aligned pair. Or might be fine. 12 YMM vectors would be three pairs, which should be fine.
Depending on matrix size, out-of-order exec may be able to overlap inner loop dep chains between separate iterations of the outer loop, especially if the loop exit condition can execute sooner and resolve the mispredict (if there is one) while FP work is still in flight. That's an advantage to having fewer total uops for the same work, favouring FMA.
QUESTION
I have two broadly related questions.
I want to make a function that forwards the arguments to fmt::format
(and later to std::format
, when the support increases). Something like this:
ANSWER
Answered 2021-Aug-06 at 03:03You can use std::vformat
/ fmt::vformat
instead.
QUESTION
In Flutter, there is the sensor package https://pub.dev/packages/sensors that allow to know the velocity X, Y and Z.
My question is : how could I calculate the distance of a phone thrown in height ?
Example : you throw your telephone, with your hand at 0.5 meter from the ground. The phone reaching 1 meter from your hand (so 1.5 meter from the ground).
How can I get the 1 meter value ?
Thanks all !
Here is the code I have right now (you need to install sensors package):
...ANSWER
Answered 2021-Nov-30 at 18:54Correct me if I'm wrong, but if you're trying to calculate a phone's absolute position in space at any moment in time directly from (past and present) accelerometer data, that is actually very complex, mainly because the phone's accelerometer's frame of reference in terms of x, y, and z is the phone itself... and phones are not in a fixed orientation, especially when being thrown around, and besides... it will have zero acceleration while in the air, anyway.
It's sort of like being blindfolded and being taken on a space journey in a pod with rockets that fire in different directions randomly, and being expected to know where you are at the end. That would be technically possible if you knew where you were when you started, and you had the ability to track every acceleration vector you felt along the way... and integrate this with gyroscope data as well... converting all this into a single path.
But, luckily, we can still get the height thrown from the accelerometer indirectly, along with some other measurements.
This solution assumes that:
- The sensors package provides acceleration values, NOT velocity values (even though it claims to provide velocity, strangely), because accelerometers themselves provide acceleration.
- Total acceleration is equal to sqrt(x^2 + y^2 + z^2) regardless of phone orientation.
- The accelerometer will read zero (or gravity only) during the throw
- This article in wired is correct in that Height = (Gravity * Time^2) / 8
The way my code works is:
- You (user) hold the "GO" button down.
- When you throw the phone up, naturally you let go of the button, which starts the timer, and the phone starts listening to accelerometer events.
- We assume that the total acceleration of the phone in the air is zero (or gravity only, depending on chosen accelerometer data type)... so we're not actually trying to calculate distance directly from the accelerometer data:
- Instead, we are using the accelerometer ONLY to detect when you have caught the phone... by detecting a sudden change in acceleration using a threshold.
- When this threshold is met, the timer is stopped.
- Now we have a total time value for the throw from beginning to end and can calculate the height.
Side notes:
- I'm using AccelerometerEvent (includes gravity), not UserAccelerometer event (does not include gravity), because I was getting weird numbers on my test device (non-zero at rest) using UserAccelerometerEvent.
- It helps to catch the phone gently ***
- My math could be complete off... I haven't had anyone else look at this yet... but at least this answer gets you started on a basic theory that works.
- My phone landed in dog poo so I hope you accept this answer.
Limitations on Accuracy:
- The height at which you let go, and catch are naturally going to be inconsistent.
- The threshold is experimental.... test different values yourself. I've settled on 10.
- There is probably some delay between the GO button depress and the timer beginning.
- *** The threshold may not always be detected accurately, or at all if the deceleration ends too quickly because the frequency of accelerometer updates provided by the sensors package is quite low. Maybe there is a way to get updates at a higher frequency with a different package.
- There is always the chance that the GO button could be depressed too early (while the phone is still in your hand) and so the acceleration will be non zero at that time, and perhaps enough to trigger the threshold.
- Probably other things not yet considered.
Code:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install Formatting
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page