Popular New Releases in Assertion
assert
Release 1.10.0
assert
Release 1.9.1
jest-extended
v2.0.0
shouldly
sinon-chai
3.7.0
Popular Libraries in Assertion
by webmozarts php
7015 MIT
Assertions to validate method input/output with nice error messages.
by webmozart php
6548 MIT
Assertions to validate method input/output with nice error messages.
by power-assert-js javascript
2714 MIT
Power Assert in JavaScript. Provides descriptive assertion messages through standard assert interface. No API is the best API.
by mjackson javascript
2306 MIT
Write better assertions
by assertj java
2134 Apache-2.0
AssertJ is a library providing easy to use rich typed assertions
by Automattic javascript
2087
Minimalistic BDD-style assertions for Node.JS and the browser.
by jest-community javascript
1883 MIT
Additional Jest matchers 🃏💪
by joel-costigliola java
1794 Apache-2.0
AssertJ is a library providing easy to use rich typed assertions
by shouldly csharp
1550 NOASSERTION
Should testing for .NET - the way Asserting *Should* be!
Trending New libraries in Assertion
by aaronabramov rust
197 MIT
Rust testing library
by earl-js typescript
161 MIT
☕ Ergonomic, modern and type-safe assertion library for TypeScript
by aspecto-io typescript
130 Apache-2.0
Tracing Based JavaScript Assertions
by asos-craigmorten typescript
79 MIT
Super-agent driven library for testing Deno HTTP servers.
by isidentical python
45 MIT
Formatter for your Python unit tests
by asos-craigmorten typescript
43 MIT
HTTP assertions for Oak made easy via SuperDeno. 🐿 🦕
by svartalf rust
41 NOASSERTION
Assertion macros toolkit for Rust
by pointfreeco swift
40 MIT
Define XCTest assertion helpers directly in your application and library code.
by de-vri-es rust
37 BSD-2-Clause
assert!() and check!() macros for Rust, inspired by Catch2
Top Authors in Assertion
1
7 Libraries
1030
2
7 Libraries
70
3
5 Libraries
2288
4
4 Libraries
2817
5
4 Libraries
48
6
3 Libraries
18
7
3 Libraries
17
8
3 Libraries
27
9
2 Libraries
18
10
2 Libraries
2367
1
7 Libraries
1030
2
7 Libraries
70
3
5 Libraries
2288
4
4 Libraries
2817
5
4 Libraries
48
6
3 Libraries
18
7
3 Libraries
17
8
3 Libraries
27
9
2 Libraries
18
10
2 Libraries
2367
Trending Kits in Assertion
Java Assertion is a mechanism to indicate that the programmer thinks that something unexpected has happened. It is like a sanity check in a code and should be used to ensure that the code works as expected. Assertion statements are available since Java 1.4 and can be enabled or disabled as per requirement. Assertions should not be used for user input validation, the normal flow of program execution, or any exception handling. Java Assertion Libraries is one of the most popular open-source libraries for assertion in Java. These libraries are useful to check whether the actual result and expected result are equal or not. Let's take a look at some of the most popular and useful assertion open source libraries in 2022 truth - Fluent assertions for Java and Android; assertj-core - library providing easy to use rich typed assertions; ArchUnit - Java architecture test library.
The assertion is a very important concept in software development. It allows you to check the conditions and make sure that everything is working properly. A very basic example is when you try to divide with 0, the program will throw an error because it's not possible. When you want to start testing your code, assertions can be very useful to ensure that it works as expected. The good thing about assertions is that it does nothing when the condition is met, so it won't affect the performance of your application. There are several libraries for Python which implement assertions and we have listed the best ones here. sure - idiomatic assertion toolkit with humanfriendly failure messages; assertpy - Simple assertion library for unit testing; expects - extensible TDD/BDD assertion library.
PHP asserts are used to make sure the code is working as expected. They are used to ensure that certain conditions are met and that the code is doing what it's supposed to be doing. An assertion is a statement in code that evaluates whether its condition is true or false. If it returns true, the program continues its execution, or else it throws an error. PHP Unit Testing consists of Assertions and the first step to doing unit testing is to write assertions for your code. Assertions are used for Test-Driven Development (TDD) and Behavior Driven Development (BDD). In this kit, we will go through the top 7 best PHP assertion libraries that you can use to write assertions for your code assert - validate method input/output with nice error messages; phpunit-snapshot-assertions - A way to test without writing actual test cases; SwaggerAssertions - API requests and responses match with your swagger definition.
Ruby is an interpreted, high-level, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro Matsumoto in Japan. According to the creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It also has a dynamic type system and automatic memory management. An assertion is one of the most important things in software development. Assertions are used to check for conditions that should never occur during normal execution. If an assertion fails, it indicates a bug, and the program should be terminated immediately. Here are 12 Ruby Assertion Open Source libraries that we recommend konacha - Rails application's JavaScript with the mocha test framework; Wrong - provides a general assert method; power_assert - Power Assert for Ruby.
Assertions help us make sure that the code does what it is intended to do. It is an essential part of programming to develop robust code. They are a set of statements that take action when a condition is not as expected. The ideal assertion library will have expressive assert functions, fluent assertions, and readable error messages. The assertion library should be simple and work on any Go project regardless of the framework being used. Go’s testing package is simple and elegant. There is no need to use a third party library to perform automated testing. Let’s see the 10 best open-source Go Assertion Libraries in 2022: testify - common assertions and mocks that plays nicely; testza - Full-featured test framework for Go! Assertions, fuzzing, input testing, output capturing, and much; gcassert - Assert your Go code is inlined and boundscheck eliminated.
C# Assertion is a construct that signals to the calling code that an unexpected event has taken place. It allows programmers to build in sanity checks into their programs, which can then be used to detect when the program is behaving in an unexpected fashion. Assertion libraries are an essential part of a tester's arsenal. They help us to check if our assumptions about the code we write/test are true. They facilitate evaluating the expected and actual results that are intended to be equal. Here are 7 best C# Assertion Open Source libraries that we recommend, shouldly - Should testing for .NET the way Asserting Should be; Verify - snapshot too; fido2-net-lib - NET library for FIDO2 / WebAuthn Attestation and Assertion.
The C++ Assertion library is a collection of macros for performing assertions and compile-time checks. It is a very useful tool for finding bugs in code during the early stages of development. If you want to use an Assertion library for C++, you have to make a decision on which one to use. There are many different libraries with different features. Some of them are quite old and were already used in C++98, others are more modern and only support C++11 or even later language versions. Some libraries are very small and easy to integrate into any project, others require some additional work. In this kit we will give you an overview of the most important assertion libraries for C++ debug_assert - Simple, flexible and modular assertion macro; PPK_ASSERT - a cross platform dropin & selfcontained C assertion library; asserts - The most overengineered C assertion library.
Testing is a crucial part of the software development process. A good JavaScript testing tool helps you identify bugs and errors quickly and fix them as soon as possible. All modern JavaScript testing frameworks use assertion libraries to perform assertions about the content of the code being developed. Assertions are a set of behaviors that developers can use to test if the function produces the correct output or not. These assertions help analyze the program and see if it is working correctly or not. Here we list down 11 best JavaScript Assertion open-source libraries chai - TDD assertion framework; power-assert |- Power Assert; nodeunit - Easy unit testing.
Trending Discussions on Assertion
Unqualified lookup of operators in standard library templates
How to avoid any binding null error and get code better
pip-compile raising AssertionError on its logging handler
Ambiguous Call when using Should().NotBeNull() on As item
Flutter Web : "Should never encounter KeyData when transitMode is rawKeyData."
error_code":403,"description":"Forbidden: bot was blocked by the user. error handle in python
Python threads difference for 3.10 and others
How to type constructor argument to initialise properties from plain object
Rust compiler not optimising lzcnt? (and similar functions)
Lookaround regex and character consumption
QUESTION
Unqualified lookup of operators in standard library templates
Asked 2022-Mar-05 at 16:301namespace N {
2 struct A {};
3
4 template<typename T>
5 constexpr bool operator<(const T&, const T&) { return true; }
6}
7
8constexpr bool operator<(const N::A&, const N::A&) { return false; }
9
10#include<functional>
11
12int main() {
13 static_assert(std::less<N::A>{}({}, {}), "assertion failed");
14}
15
See https://godbolt.org/z/vsd3qfch6.
This program compiles on seemingly random versions of compilers.
The assertion fails on all versions of MSVC since v19.15, but succeeds on v19.14.
It succeeds on GCC 11.2 and before, but fails on current GCC trunk.
It fails on Clang with libstdc++ in all versions. It succeeds with libc++ in all versions, including current trunk, except version 13.
It always succeeds with ICC.
Is it specified whether or not the static_assert
should succeed?
The underlying issue here is that std::less
uses <
internally, which because it is used in a template will find operator<
overloads via argument-dependent lookup from the point of instantiation (which is the proper method), but also via unqualified name lookup from the point of definition of the template.
If the global overload is found, it is a better match. Unfortunately this make the program behavior dependent on the placement and order of the standard library includes.
I would have expected that the standard library disables unqualified name lookup outside the std
namespace, since it cannot be relied on anyway, but is that supposed to be guaranteed?
ANSWER
Answered 2022-Mar-05 at 16:30What matters here is whether the unqualified lookup from inside std
finds any other operator<
(regardless of its signature!) before reaching the global namespace. That depends on what headers have been included (any standard library header may include any other), and it also depends on the language version since C++20 replaced many such operators with operator<=>
. Also, occasionally such things are respecified as hidden friends that are not found by unqualified lookup. It’s obviously unwise to rely on it in any case.
QUESTION
How to avoid any binding null error and get code better
Asked 2022-Feb-25 at 14:48I have this code and I am getting this error that I have been trying to solve from 3 to 4 days and I didn't find a solution hope anyone can help me to get a solution to solve this Binding error I am facing.
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/extension_navigation.dart:357:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
- 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart'). SchedulerBinding.instance!.addPostFrameCallback((_) { ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/extension_navigation.dart:468:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
- 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart'). SchedulerBinding.instance!.addPostFrameCallback((_) { ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/snackbar/snackbar.dart:452:22: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
- 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart'). SchedulerBinding.instance!.addPostFrameCallback( ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/rx_flutter/rx_disposable.dart:20:22: Warning: Operand of null-aware operation '?.' has type 'SchedulerBinding' which excludes null.
- 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart'). SchedulerBinding.instance?.addPostFrameCallback((_) => onReady()); ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/rx_flutter/rx_notifier.dart:130:22: Warning: Operand of null-aware operation '?.' has type 'SchedulerBinding' which excludes null.
- 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart'). SchedulerBinding.instance?.addPostFrameCallback((_) => onReady()); ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/simple/get_controllers.dart:90:20: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
- 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart'). WidgetsBinding.instance!.addObserver(this); ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/simple/get_controllers.dart:96:20: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
- 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart'). WidgetsBinding.instance!.removeObserver(this); ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/router_report.dart:53:22: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
- 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart'). WidgetsBinding.instance!.addPostFrameCallback((_) { ^ This app is linked to the debug service: ws://127.0.0.1:53736/oionbuT1rro=/ws Debug service listening on ws://127.0.0.1:53736/oionbuT1rro=/ws
Running with sound null safety Debug service listening on ws://127.0.0.1:53736/oionbuT1rro=/ws Error: Assertion failed: file:///C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.5.4/lib/src/firebase_core_web.dart:273:11 options != null "FirebaseOptions cannot be null when creating the default app." at Object.throw_ [as throw] (http://localhost:53548/dart_sdk.js:5066:11) at Object.assertFailed (http://localhost:53548/dart_sdk.js:4991:15) at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:53548/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42) at initializeApp.next () at http://localhost:53548/dart_sdk.js:40547:33 at _RootZone.runUnary (http://localhost:53548/dart_sdk.js:40417:59) at _FutureListener.thenAwait.handleValue (http://localhost:53548/dart_sdk.js:35361:29) at handleValueCallback (http://localhost:53548/dart_sdk.js:35907:49) at Function._propagateToListeners (http://localhost:53548/dart_sdk.js:35945:17) at _Future.new.[_completeWithValue] (http://localhost:53548/dart_sdk.js:35793:23) at async._AsyncCallbackEntry.new.callback (http://localhost:53548/dart_sdk.js:35814:35) at Object._microtaskLoop (http://localhost:53548/dart_sdk.js:40684:13) at _startMicrotaskLoop (http://localhost:53548/dart_sdk.js:40690:13) at http://localhost:53548/dart_sdk.js:36167:9
ANSWER
Answered 2022-Feb-22 at 11:50This happend to me when I updated Dart SDK to Beta channel, If you also updated your Dart sdk try to downgrade your Dart sdk from Beta channe; to the Stable Channel Dart version.
The commend to downgrade your dart is
1 flutter downgrade v2.10.0.2
2
3Downgrade flutter to version 10.0.2
4? [y|n]:
5
QUESTION
pip-compile raising AssertionError on its logging handler
Asked 2022-Feb-13 at 12:37I have a dockerfile that currently only installs pip-tools
1FROM python:3.9
2
3RUN pip install --upgrade pip && \
4 pip install pip-tools
5
6COPY ./ /root/project
7
8WORKDIR /root/project
9
10ENTRYPOINT ["tail", "-f", "/dev/null"]
11
I build and open a shell in the container using the following commands:
1FROM python:3.9
2
3RUN pip install --upgrade pip && \
4 pip install pip-tools
5
6COPY ./ /root/project
7
8WORKDIR /root/project
9
10ENTRYPOINT ["tail", "-f", "/dev/null"]
11docker build -t brunoapi_image .
12docker run --rm -ti --name brunoapi_container --entrypoint bash brunoapi_image
13
Then, when I try to run pip-compile
inside the container I get this very weird error (full traceback):
1FROM python:3.9
2
3RUN pip install --upgrade pip && \
4 pip install pip-tools
5
6COPY ./ /root/project
7
8WORKDIR /root/project
9
10ENTRYPOINT ["tail", "-f", "/dev/null"]
11docker build -t brunoapi_image .
12docker run --rm -ti --name brunoapi_container --entrypoint bash brunoapi_image
13root@727f1f38f095:~/project# pip-compile
14Traceback (most recent call last):
15 File "/usr/local/bin/pip-compile", line 8, in <module>
16 sys.exit(cli())
17 File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1128, in __call__
18 return self.main(*args, **kwargs)
19 File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1053, in main
20 rv = self.invoke(ctx)
21 File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1395, in invoke
22 return ctx.invoke(self.callback, **ctx.params)
23 File "/usr/local/lib/python3.9/site-packages/click/core.py", line 754, in invoke
24 return __callback(*args, **kwargs)
25 File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 26, in new_func
26 return f(get_current_context(), *args, **kwargs)
27 File "/usr/local/lib/python3.9/site-packages/piptools/scripts/compile.py", line 342, in cli
28 repository = PyPIRepository(pip_args, cache_dir=cache_dir)
29 File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 106, in __init__
30 self._setup_logging()
31 File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 455, in _setup_logging
32 assert isinstance(handler, logging.StreamHandler)
33AssertionError
34
I have no clue what's going on and I've never seen this error before. Can anyone shed some light into this?
Running on macOS Monterey
ANSWER
Answered 2022-Feb-05 at 16:30It is a bug, you can downgrade using:
pip install "pip<22"
QUESTION
Ambiguous Call when using Should().NotBeNull() on As item
Asked 2022-Feb-11 at 13:22When I do the following test
1var contentRes = res as OkNegotiatedContentResult<List<MachineHealthTableDTO>>;
2contentRes.Should().NotBeNull();
3
I get the error
1var contentRes = res as OkNegotiatedContentResult<List<MachineHealthTableDTO>>;
2contentRes.Should().NotBeNull();
3The call is ambiguous between the following methods or properties: 'DataRowAssertionExtensions.Should<TDataRow>(TDataRow)' and 'DataSetAssertionExtensions.Should<TDataSet>(TDataSet)'
4
This started happening when I upgraded from fluent assertions 5 to 6. Any Idea as to how I can go about resolving this issue would be appreciated.
ANSWER
Answered 2021-Aug-26 at 09:38I've just had this exact issue with a .NET Framework 4.8 console app. Would build fine locally but failed the build step in the Azure DevOps pipeline.
Turns out that pipeline was using the vs2017-win2016
vm. Bumping it up to windows-2019
- which used Visual Studio 2019/later version of MSBuild - sorted the issue.
QUESTION
Flutter Web : "Should never encounter KeyData when transitMode is rawKeyData."
Asked 2022-Feb-05 at 02:04When I run my project on web the Exception message and stack trace was
1"Should never encounter KeyData when transitMode is rawKeyData."
2 at Object.throw_ [as throw] (http://localhost:2621/dart_sdk.js:5061:11)
3 at Object.assertFailed (http://localhost:2621/dart_sdk.js:4986:15)
4 at hardware_keyboard.KeyEventManager.new.handleKeyData (http://localhost:2621/packages/flutter/src/services/restoration.dart.lib.js:5334:28)
5 at http://localhost:2621/dart_sdk.js:160131:47
6 at Object.invoke (http://localhost:2621/dart_sdk.js:179656:7)
7 at _engine.EnginePlatformDispatcher.__.invokeOnKeyData (http://localhost:2621/dart_sdk.js:160131:17)
8 at _engine.KeyboardBinding.__.[_onKeyData] (http://localhost:2621/dart_sdk.js:158922:49)
9 at _engine.KeyboardConverter.new.handleEvent (http://localhost:2621/dart_sdk.js:159210:16)
10 at http://localhost:2621/dart_sdk.js:158929:74
11 at loggedHandler (http://localhost:2621/dart_sdk.js:158906:43)
12Error: Assertion failed: file:///E:/flutter_windows_2.5.2-stable/flutter/packages/flutter/lib/src/services/hardware_keyboard.dart:787:16
13
ANSWER
Answered 2021-Oct-31 at 06:28try one of theies
flutter run -d chrome --web-renderer html
flutter build web --web-renderer html
QUESTION
error_code":403,"description":"Forbidden: bot was blocked by the user. error handle in python
Asked 2022-Jan-10 at 01:46I have a problem using telebot API in python. If the user sends a message to the bot and waits for the response and at the same time he blocks the bot. I get this error and the bot will not respond for other users:
403,"description":"Forbidden: bot was blocked by the user
Try, catch block is not handling this error for me
any other idea to get rid of this situation? how to find out that the bot is blocked by the user and avoid replying to this message?
this is my code:
1import telebot
2import time
3
4
5@tb.message_handler(func=lambda m: True)
6def echo_all(message):
7 try:
8 time.sleep(20) # to make delay
9 ret_msg=tb.reply_to(message, "response message")
10 print(ret_msg)
11 assert ret_msg.content_type == 'text'
12 except TelegramResponseException as e:
13 print(e) # do not handle error #403
14 except Exception as e:
15 print(e) # do not handle error #403
16 except AssertionError:
17 print( "!!!!!!! user has been blocked !!!!!!!" ) # do not handle error #403
18
19
20tb.polling(none_stop=True, timeout=123)
21
ANSWER
Answered 2021-Aug-27 at 08:13This doesn't appear to actually be an error and thus try
catch
won't be able to handle it for you. You'll have to get the return code and handle it with if
else
statements probably (switch statements would work better in this case, but I don't think python has the syntax for it).
EDIT
Following the method calls here it looks like reply_to()
returns send_message()
, which returns a Message
object, which contains a json
string set to self.json
in the __init__()
method. In that string you can likely find the status code (400s and 500s you can catch and deal with as you need).
QUESTION
Python threads difference for 3.10 and others
Asked 2022-Jan-04 at 21:25For some, simple thread related code, i.e:
1import threading
2
3
4a = 0
5threads = []
6
7
8def x():
9 global a
10 for i in range(1_000_000):
11 a += 1
12
13
14for _ in range(10):
15 thread = threading.Thread(target=x)
16 threads.append(thread)
17 thread.start()
18
19
20for thread in threads:
21 thread.join()
22
23
24print(a)
25assert a == 10_000_000
26
We got different behaviour, based on Python version.
For 3.10, the output is:
1import threading
2
3
4a = 0
5threads = []
6
7
8def x():
9 global a
10 for i in range(1_000_000):
11 a += 1
12
13
14for _ in range(10):
15 thread = threading.Thread(target=x)
16 threads.append(thread)
17 thread.start()
18
19
20for thread in threads:
21 thread.join()
22
23
24print(a)
25assert a == 10_000_000
26❯ python3.10 b.py
2710000000
28
For 3.9, the output is:
1import threading
2
3
4a = 0
5threads = []
6
7
8def x():
9 global a
10 for i in range(1_000_000):
11 a += 1
12
13
14for _ in range(10):
15 thread = threading.Thread(target=x)
16 threads.append(thread)
17 thread.start()
18
19
20for thread in threads:
21 thread.join()
22
23
24print(a)
25assert a == 10_000_000
26❯ python3.10 b.py
2710000000
28❯ python3.9 b.py
292440951
30Traceback (most recent call last):
31 File "/Users/romka/t/threads-test/b.py", line 24, in <module>
32 assert a == 10_000_000
33AssertionError
34
As we do not acquire any lock, for me, results of 3.9 is obvious and expected. Question is why and how 3.10 got "correct" results, while should not?
I'm review changelog for Python 3.10 and there is no anything related to threads or GIL which can bring such results.
ANSWER
Answered 2021-Nov-17 at 14:58An answer from a core developer:
Unintended consequence of Mark Shannon's change that refactors fast opcode dispatching: https://github.com/python/cpython/commit/4958f5d69dd2bf86866c43491caf72f774ddec97 -- the INPLACE_ADD opcode no longer uses the "slow" dispatch path that checks for interrupts and such.
QUESTION
How to type constructor argument to initialise properties from plain object
Asked 2021-Dec-30 at 04:33I'm trying to come up with a simple way to write a class with a constructor that takes a plain object argument, and initialises the instance properties accordingly.
1class Foo {
2 x: string
3 y: string
4
5 constructor(init: Foo) {
6 Object.assign(this, init)
7 }
8}
9
10
11new Foo({x: 'a', y: 'b'})
12
This gives an error on the two properties: "has no initializer and is not definitely assigned in the constructor". If init
is a valid Foo
, which the type system says it is, those properties are definitely assigned in the constructor. I realise that assertion relies on an understanding of Object.assign
, but I've seen other examples where it seems the compiler does have that.
What would be the best way to fix this? Right now I'm adding initialisers, but I'd prefer not to.
ANSWER
Answered 2021-Dec-30 at 03:43The compiler cannot perform the analysis on Object.assign(this, init)
to know that all the properties of this
will be initialized as a result. The typings for Object.assign(target, ...args)
don't mutate the type of the target
parameter at all.
You could use a definite assignment assertion for each and every property, to suppress the error:
1class Foo {
2 x: string
3 y: string
4
5 constructor(init: Foo) {
6 Object.assign(this, init)
7 }
8}
9
10
11new Foo({x: 'a', y: 'b'})
12class Foo {
13 x!: string
14 y!: string
15
16 constructor(init: Foo) {
17 Object.assign(this, init)
18 }
19}
20
and that's fine for a single Foo
class with only two properties. But it could be quite tedious indeed if you have lots of properties to initialize.
In such cases, you could write a class factory function which generalizes the pattern of copying the constructor parameter into this
. You only have to do a single type assertion inside the implementation:
1class Foo {
2 x: string
3 y: string
4
5 constructor(init: Foo) {
6 Object.assign(this, init)
7 }
8}
9
10
11new Foo({x: 'a', y: 'b'})
12class Foo {
13 x!: string
14 y!: string
15
16 constructor(init: Foo) {
17 Object.assign(this, init)
18 }
19}
20function ClassFor<T extends object>() {
21 return class {
22 constructor(init: any) {
23 Object.assign(this, init);
24 }
25 } as new (init: T) => T;
26}
27
And then you can just use the factory to generate your specific class constructors:
1class Foo {
2 x: string
3 y: string
4
5 constructor(init: Foo) {
6 Object.assign(this, init)
7 }
8}
9
10
11new Foo({x: 'a', y: 'b'})
12class Foo {
13 x!: string
14 y!: string
15
16 constructor(init: Foo) {
17 Object.assign(this, init)
18 }
19}
20function ClassFor<T extends object>() {
21 return class {
22 constructor(init: any) {
23 Object.assign(this, init);
24 }
25 } as new (init: T) => T;
26}
27class Foo extends ClassFor<{ x: string, y: string }>() {
28
29}
30
And verify that it behaves as you like:
1class Foo {
2 x: string
3 y: string
4
5 constructor(init: Foo) {
6 Object.assign(this, init)
7 }
8}
9
10
11new Foo({x: 'a', y: 'b'})
12class Foo {
13 x!: string
14 y!: string
15
16 constructor(init: Foo) {
17 Object.assign(this, init)
18 }
19}
20function ClassFor<T extends object>() {
21 return class {
22 constructor(init: any) {
23 Object.assign(this, init);
24 }
25 } as new (init: T) => T;
26}
27class Foo extends ClassFor<{ x: string, y: string }>() {
28
29}
30const foo = new Foo({ x: 'a', y: 'b' })
31console.log(foo.x.toUpperCase()) // "A"
32console.log(foo.y.toUpperCase()) // "B"
33
QUESTION
Rust compiler not optimising lzcnt? (and similar functions)
Asked 2021-Dec-26 at 01:56This follows as a result of experimenting on Compiler Explorer as to ascertain the compiler's (rustc's) behaviour when it comes to the log2()
/leading_zeros()
and similar functions. I came across this result with seems exceedingly both bizarre and concerning:
Code:
1pub fn lzcnt0(val: u64) -> u64 {
2 val.leading_zeros() as u64
3}
4
5pub unsafe fn lzcnt1(val: u64) -> u64 {
6 core::arch::x86_64::_lzcnt_u64(val)
7}
8
9pub unsafe fn lzcnt2(val: u64) -> u64 {
10 asm_lzcnt(val)
11}
12
13#[inline]
14pub unsafe fn asm_lzcnt(val: u64) -> u64 {
15 let lzcnt: u64;
16 core::arch::asm!("lzcnt {}, {}", in(reg) val, lateout(reg) lzcnt, options(nomem, nostack));
17 lzcnt
18}
19
Output:
1pub fn lzcnt0(val: u64) -> u64 {
2 val.leading_zeros() as u64
3}
4
5pub unsafe fn lzcnt1(val: u64) -> u64 {
6 core::arch::x86_64::_lzcnt_u64(val)
7}
8
9pub unsafe fn lzcnt2(val: u64) -> u64 {
10 asm_lzcnt(val)
11}
12
13#[inline]
14pub unsafe fn asm_lzcnt(val: u64) -> u64 {
15 let lzcnt: u64;
16 core::arch::asm!("lzcnt {}, {}", in(reg) val, lateout(reg) lzcnt, options(nomem, nostack));
17 lzcnt
18}
19example::lzcnt0:
20 test rdi, rdi
21 je .LBB0_2
22 bsr rax, rdi
23 xor rax, 63
24 ret
25.LBB0_2:
26 mov eax, 64
27 ret
28
29example::lzcnt1:
30 jmp core::core_arch::x86_64::abm::_lzcnt_u64
31
32core::core_arch::x86_64::abm::_lzcnt_u64:
33 lzcnt rax, rdi
34 ret
35
36example::lzcnt2:
37 lzcnt rdi, rax
38 ret
39
40
The compiler options are to best emulate cargo's 'release' configuration (with opt-level=3 for good measure), and otherwise trying my best to get the compiler to optimise the functions. The specific target shouldn't matter, as long as it targets x86-64, I've tried x86_64-{pc-windows-{msvc,gnu},unknown-linux-gnu}
.
All of these outputs should be identical to lzcnt2
. Instruction Performance Tables lzcnt
is evidently a fast instruction across the board and should be used, and having an unnecessary branch in such a low level function is dismal. What's weirder, the function _lzcnt_u64()
calls leading_zeros()
under the hood - which the compiler is happy to magic away (there's no checks or asserts either), but won't seem to do it for the underlying function. What's more, the compiler won't inline the lzcnt
instruction even in that case? (the implementation marks the function a #[inline]
too) Sure, a jmp
isn't as bad, but it's entirely unnecessary as should be avoided.
- Compiler bug?
- Purposeful choice I don't understand?
- I don't understand how to use Compiler Explorer properly?
- Other?
I'm seeing similar results in functions like log2
and (I presume) others that rely on the ctlz
rust compiler intrinsic in their implementation.
If you understand compilers sufficiently, any clarification would be greatly appreciated. I don't fancy writing loads of utility functions for little reason, but I'll do so if there's no better alternative.
P.S. If your answer is along the lines of that the performance gain is negligible in most situations, and/or that I shouldn't care due to code quality or similar reasoning: I understand the sentiment, but that's not the point of this question. I'm writing for bare-metal, hot code in a personal project.
ANSWER
Answered 2021-Dec-26 at 01:56Old x86-64 CPUs don't support lzcnt
, so rustc/llvm won't emit it by default. (They would execute it as bsr
but the behavior is not identical.)
Use -C target-feature=+lzcnt
to enable it. Try.
More generally, you may wish to use -C target-cpu=XXX
to enable all the features of a specific CPU model. Use rustc --print target-cpus
for a list.
In particular, -C target-cpu=native
will generate code for the CPU that rustc itself is running on, e.g. if you will run the code on the same machine where you are compiling it.
QUESTION
Lookaround regex and character consumption
Asked 2021-Dec-20 at 12:26Based on the documentation for Raku's lookaround assertions, I read the regex / <?[abc]> <alpha> /
as saying "starting from the left, match but do not not consume one character that is a
, b
, or c
and, once you have found a match, match and consume one alphabetic character."
Thus, this output makes sense:
1'abc' ~~ / <?[abc]> <alpha> / # OUTPUT: «「a」 alpha => 「a」»
2
Even though that regex has two one-character terms, one of them does not capture so our total capture is only one character long.
But next expression confuses me:
1'abc' ~~ / <?[abc]> <alpha> / # OUTPUT: «「a」 alpha => 「a」»
2'abc' ~~ / <?[abc\s]> <alpha> / # OUTPUT: «「ab」 alpha => 「b」»
3
Now, our total capture is two characters long, and one of those isn't captured by <alpha>
. So is the lookaround capturing something after all? Or am I misunderstanding something else about how the lookaround works?
ANSWER
Answered 2021-Dec-20 at 12:26<?[ ]>
and <![ ]>
does not seem to support some backslashed character classes. \n
, \s
, \d
and \w
show similar results.
<?[abc\s]>
behaves the same as <[abc\s]>
when \n
, \s
, \d
or \w
is added.
\t
, \h
, \v
, \c[NAME]
and \x61
seem to work as normal.
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Assertion
Tutorials and Learning Resources are not available at this moment for Assertion