Привет всем !
Gulpfile.js:
const gulp = require('gulp'),
gp = require('gulp-load-plugins')();
gulp.task('img:compress', gulp.series( function(cb) {
return gulp.src('img/*')
.pipe(gp.tinypng('RJnL6Rx3l41Y58OJziMBRUeoteR09LBb'))
.pipe(gulp.dest('compressed_img/'))
cb();
}));
В консоли выдает:
[19:11:08] The following tasks did not complete: img:compress, <anonymous>
[19:11:08] Did you forget to signal async completion?
В чем может быть причина?
Как мне изменить код чтобы, это сообщение больше не вылазило в консоли?
-
Вопрос заданболее трёх лет назад
-
1687 просмотров
Пригласить эксперта
У вас вызов cb()
стоит после return
т.е. он вообще не вызывается. Но поскольку в списке аргументов он есть – gulp ожидает его вызова и, не дождавшись, ругается.
В вашем случае cb
вообще не нужен, просто уберите его из списка аргументов и всё начнёт работать.
gulp.task('img:compress', function {
return gulp.src('img/*')
.pipe(gp.tinypng('RJnL6Rx3l41Y58OJziMBRUeoteR09LBb'))
.pipe(gulp.dest('compressed_img/');
});
-
Показать ещё
Загружается…
21 мая 2023, в 09:15
3000 руб./за проект
21 мая 2023, в 08:17
4000 руб./за проект
21 мая 2023, в 08:13
100 руб./за проект
Минуточку внимания
sample code .h
class My {
public:
My();
~My();
void Quit();
private:
};
sample code .cpp
void My::Quit()
{
gtk_main_quit();
}
My::My()
{
...
item = gtk_menu_item_new_with_label("Quit");
gtk_widget_show(item);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(this->Quit), NULL);
...
}
getting error: invalid use of member (did you forget the «&» ?)
What is my problem?
asked Feb 21, 2015 at 13:54
3
this->Quit
isn’t a valid expression; it can only be used to call the function directly.
The syntax for taking the address of a member function is &My::Quit
.
The function will have to be a static member or non-member to be used as a callback.
answered Feb 21, 2015 at 14:04
Mike SeymourMike Seymour
249k28 gold badges446 silver badges638 bronze badges
- Forum
- General C++ Programming
- invalid use of member (did you forget th
invalid use of member (did you forget the &?)
hi everyone, this is my first post, so bear with me.
this is driving me insane. im trying to write a program for Project Euler problem 4. here is the code that is giving me problems (its not complete yet)
|
|
and the errors are
/home/nick/Euler/Euler004/main.cpp||In function ‘bool isPalindrome(int)’:|
/home/nick/Euler/Euler004/main.cpp|23|error: invalid use of member (did you forget the ‘&’ ?)|
/home/nick/Euler/Euler004/main.cpp|25|error: invalid use of member (did you forget the ‘&’ ?)|
||=== Build finished: 2 errors, 0 warnings ===|
what exactly does this error message mean and how do i fix it?
Last edited on
haha duh. i forgot the () after both check.length lol. mods can delete this if they feel like it 😛
Haha – yeah got to admit I’ve missed that myself a few times from typing to quickly 🙁
Topic archived. No new replies allowed.
Начало: «Пакет gulp-html-bem-validator».
Если взять пример описания задачи для менеджера задач «Gulp» от автора пакета «gulp-html-bem-validator», который приведен по следующей ссылке:
https://github.com/dDenysS/gulp-html-bem-validator#simple-example
var gulp = require('gulp'); var gulpHtmlBemValidator = require('gulp-html-bem-validator'); gulp.task('html-bem-validator', () => { gulp.src('pages/*.html') .pipe(gulpHtmlBemValidator()) .pipe(gulp.dest('build/')); });
и запустить описанную задачу из командной строки, то получим примерно следующее:
С одной стороны, пакет (плагин менеджера задач «Gulp») «gulp-html-bem-validator» свою задачу выполнил. С другой стороны, менеджер задач «Gulp» почему-то не сообщил о завершении задачи, а вместо этого в конце вывел какие-то тревожные предупреждения:
[08:26:30] The following tasks did not complete: html-bem-validator [08:26:30] Did you forget to signal async completion?
По-русски это что-то вроде следующего:
[08:26:30] Следующие задачи не завершены: html-bem-validator [08:26:30] Вы забыли подать сигнал об асинхронном завершении?
Причина этих сообщений
Каждая задача в менеджере задач «Gulp» является асинхронной функцией, написанной на языке JavaScript. Об этом сказано на сайте менеджера задач «Gulp»:
https://gulpjs.com/docs/en/getting-started/creating-tasks
Библиотеки среды выполнения «Node.js» управляют асинхронностью множеством различных способов. Самым распространенным способом из них является использование функции обратного вызова (по-английски «callback»), в которой первый аргумент зарезервирован для передачи объекта-ошибки (по-английски такая конструкция называется «error-first callback»).
Менеджер задач «Gulp» тоже позволяет использовать множество способов управления асинхронностью, в том числе и конструкцию вида «error-first callback». Менеджер задач «Gulp» ждет от задач сигнала об их завершении. Об этом сказано тут:
https://gulpjs.com/docs/en/getting-started/async-completion
Таким образом, причина вышеуказанных сообщений в том, что в вышеуказанном описании задачи «html-bem-validator» эта задача, являясь асинхронной функцией, ничего не возвращает (что само по себе явилось бы сигналом о завершении задачи), а также не вызывает внутри себя свой первый аргумент (это менеджер задач тоже считает сигналом о завершении задачи).
Как исправить
Подадим менеджеру задач сигнал о завершении задачи с помощью вызова первого аргумента функции обратного вызова. Для этого внесем исправления в описание задачи (я пометил исправления красным цветом):
var gulp = require('gulp'); var gulpHtmlBemValidator = require('gulp-html-bem-validator'); gulp.task('html-bem-validator', (cb) => { gulp.src('pages/*.html') .pipe(gulpHtmlBemValidator()) .pipe(gulp.dest('build/')); cb(); // сигнал о завершении задачи });
Теперь после запуска задачи вышеуказанные сообщения не появятся. Зато появится сообщение о завершении задачи и количестве времени, которое понадобилось на ее выполнение:
Дополнительно: регистрация задач с помощью task() не рекомендуется
На сайте менеджера задач «Gulp» сказано, что регистрация задач с помощью метода task()
теперь не рекомендуется (раньше это был основной способ). Об этом можно прочитать тут:
https://gulpjs.com/docs/en/api/task
Теперь предлагается использовать экспорт. Перепишем описание нашей задачи способом экспорта:
var gulp = require('gulp'); var gulpHtmlBemValidator = require('gulp-html-bem-validator'); function htmlBemValidator(cb) { gulp.src('pages/*.html') .pipe(gulpHtmlBemValidator()) .pipe(gulp.dest('build/')); cb(); } exports.htmlBemValidator = htmlBemValidator;
Вот и всё. Из названия задачи пришлось убрать дефисы, потому что язык JavaScript не позволяет в именах функций дефисы. Теперь и вызов задачи из командной строки немного изменится:
> gulp htmlBemValidator
В остальном результат работы пакета должен быть таким же, как и раньше.
The error message “Did you forget to register or load this tag?” is a common one that Django developers encounter. The error is displayed when a custom tag library that has not been registered or loaded is used in a Django template.
It’s a common issue, but don’t worry! It’s easily fixable once you understand what’s causing the template tag error, whether typo, syntax, or forgetting to load the library.
What is a tag in Django?
A tag in Django adds special functionality to a Django template allowing you to perform actions in your template. For example, with a tag, you can display data in a specific format, loop over items in a context variable, include other templates in a template, etc.
Django tag are written using specific syntax. They are surrounded by a combination of curly braces and percent signs like this: {% ... %}
. Here is an example of a Django built-in tag that is used to iterate through items in a list or dictionary: {% for item in items %}
.
These tags can be used in a Django template file just the way you would in other .html files.
Django comes with a couple of built-in template tags that you can use out of the box- because that is what Django was made for. Besides, Django provides you the capability of creating your own custom tags to meet your specific web development needs.
Here is an example Django template tag code that uses a context variable name called, articles
, to loop over each blog post and display their titles on a web page.
{% for blogpost in blogposts %}
<li>{{ blogpost.title }}</li>
{% endfor %}
Basically, that’s how Django template tags work. They allow you to add extra functionality to a template file that would not be possible in a normal .html file.
Now, let’s see what are the common causes that would lead to the “Did you forget to register or load this tag” error in Django.
Causes of “Did you forget to register or load this tag” in Django
- You forgot to install or import the required tag library.
- Using custom tags before loading them in a template.
- Typos in your tag name: The error may occur if the tag name is spelled incorrectly.
- Miss restarting the development server after making changes to your Django code. You may be loading a cached version of your website that has tag errors.
Cause 1: Forgetting to install or import the required tag library
Missing the tag library is one of the common causes of the error “Did you forget to register or load this tag” in Django templates. This happens when you are using a custom template tag that is loaded through a third-party package installed through the pip package manager. Because the package is not installed in your Django project virtual environment, Django will throw the error as you’re trying to use a tag that has not been registered or loaded.
How to fix the error
To fix the error when you’re using a custom template tag loaded using a Pypi package, here are the things you need to do:
1. Install the module in your Python Django project environment
You can install the module using the pip install package_name
command.
pip install package_name
2. Add the module that defines your tag library to the INSTALLED_APPS
settings.
Open your project settings.py file and ensure you have added your module to the list of INSTALLED_APPS. Save the file and restart the development server.
That should fix the problem.
Cause 2: Using custom tags before loading them in a templates
When you forget to load the tag library in your Django templates will lead to “Did you forget to register or load this tag” error. You can register your tag library, but the error will persist if you forget to load the template tag in your template using the {% load ... %}
tag.
To use a custom tag in your Django templates, you must first load the tag library that defines the custom tag. This can be done using the {% load library_name %} tag at the top of your template files. The {% load ... %}
tag takes the name of your library as an argument and instructs Django to load it. Once loaded, you can be able to use the custom tags defined inside the library you loaded.
Here’s an example syntax on how to load a custom tag in a .html file:
{% load your_custom_tags_lib %}
How to fix the error
To fix the “Did you forget to register or load this tag” error associated with using custom tags without loading them in your templates you should simply add the {% load ... %}
template tag at the top of your file.
Cause 3: Typos in your tag name
When you misspell your tag name, Django will throw the “Did you forget to register or load this tag” error. This is another common error that Django developers make when trying to use built-in and custom template tags. Django will always throw the exception because it cannot find the misspelled tag name from the library loaded at the top.
Also, consider case sensitivity because built-in and custom tag names are case sensitive. Thus, it’s important to make sure that the tag name you’re using in your template matches the tag name defined in your tag library using the correct case.
For example, if you have a custom tag defined in your tag library as, my_custom_tag
, you must use the same spelling and capitalization when using the tag in your template. If you misspell the tag name, such as using My_Custom_Tag instead of my_custom_tag, Django will not be able to find the tag and you will encounter the “Did you forget to register or load this tag?” error. That goes for built-in tags too. The for tag loaded as For will result in Django throwing the “Did you forget to register or load this tag” exception.
How to fix the error
To avoid the “Did you forget to register or load this tag?” problem, make sure that the tag name you’re using in your template matches the tag name defined in your tag library exactly, including capitalization.
Cause 4: Missing to restart Django development server
Missing to restart the Django development server after making changes to your custom tag library, Django settings, or installing a library loading the template tags can cause the “Did you forget to register or load this tag?” error.
As you make changes to your Django settings, Python virtual environment, or your custom tag library, the development server must be restarted in order for those changes to take effect. If you don’t restart the development server after making changes, the old code will still be in use (cached) and you may encounter the “Did you forget to register or load this tag?” error again.
How to fix the error
To avoid the “Did you forget to register or load this tag?” error, make sure to always restart the development server after making changes to your Django project. You can do this by stopping the development server using CTRL + C
in the terminal where your Django development server is running, and then starting it again using the python manage.py runserver
command.
python manage.py runserver
This will ensure that your changes have taken effect and that you’re using the latest code in your development server.
Steps to resolve the error: “Did you forget to register or load this tag”
Step 1. Install and import the tag library in your Django project
Check your tag library installation and registration. Make sure that the custom tag library you’re trying to use has been installed and registered in your Django project.
Tag library installation can be done using the pip command:
pip3 install pypi_package_name
The registration of the tag library should be done in the INSTALLED_APPS
setting of your project’s settings.py
file.
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# new line
'new_package_name',
]
Step 2. Make sure the tag library is loaded using the correct syntax
If you’re using your own custom tags, ensure you have loaded them in your template using the correct syntax: {% load tag_library %}
Check the load
tag in your template and make sure that you have used the load
tag at the top of your template to load the custom tag library. Also, specify the correct name of your tag library when loading it.
Step 3. Double-check the spelling of the tag name
Check the tag name and ensure that the tag name you’re using in your template matches the tag name defined in your tag library, including capitalization. Custom tags are case-sensitive, so it’s important to make sure the spelling and capitalization are correct.
Check for typos by double-checking your template file for typos in the tag name, spelling, or capitalization. Check in the line number provided by Django for easier identification. Typos can cause the “Did you forget to register or load this tag?” error, so it’s important to make sure your code is correct.
Step 4. Restart development server
Restart the development server. Ensure to restart the development server after making changes to your Django project, including changes to your custom tag library or Django settings. You can do this by stopping the development server using CTRL + C
in the terminal where it’s running, and then starting it again using the python manage.py runserver
command.
By following these steps, you can resolve the “Did you forget to register or load this tag?” error in Django.