Как найти p opt

$begingroup$

Sorry if my question is banal. Consider an approximation scheme such as FPTAS that guarantees to find a soln>(1-eps)OPT for maximization. Now consider if OPT=exp(|input|) so It easily can be seen that soln is exp(|input|) So its run-time will be exponential too(just a print of result is exponential). So can we say the condition OPT<P(|input|) is a necessary condition for any problem that we want to find an approximation scheme algorithm for that?

asked Mar 29, 2015 at 17:49

CoderInNetwork's user avatar

$endgroup$

$begingroup$

FPTAS is commonly used for optimization problems whose associated decision problem is in NP. For those problems, it is guaranteed that the optimal solution has polynomial size (that’s part of the definition of NP), so this issue does not arise.

answered Mar 29, 2015 at 19:51

D.W.'s user avatar

D.W.D.W.

152k19 gold badges213 silver badges439 bronze badges

$endgroup$

IEEE Account

  • Change Username/Password
  • Update Address

Purchase Details

  • Payment Options
  • Order History
  • View Purchased Documents

Profile Information

  • Communications Preferences
  • Profession and Education
  • Technical Interests

Need Help?

  • US & Canada: +1 800 678 4333
  • Worldwide: +1 732 981 0060
  • Contact & Support

  • About IEEE Xplore
  • Contact Us
  • Help
  • Accessibility
  • Terms of Use
  • Nondiscrimination Policy
  • Sitemap
  • Privacy & Opting Out of Cookies

A not-for-profit organization, IEEE is the world’s largest technical professional organization dedicated to advancing technology for the benefit of humanity.
© Copyright 2023 IEEE — All rights reserved. Use of this web site signifies your agreement to the terms and conditions.

Быстрые клавиши Photoshop для разных этапов работы, а также их настройка вручную

15 июля 2020

3 минуты188269

https://gbcdn.mrgcdn.ru/uploads/post/2280/og_image/f4ed7e488d58df90933fedff0a28607f.jpg

Горячие клавиши в любом профессиональном инструменте — это маст-хэв, который помогает существенно увеличить скорость работы. Если не выискивать нужный инструмент на панели клик за кликом, а сразу вызывать его с клавиатуры, можно сэкономить несколько секунд — а за целый рабочий день они складываются чуть ли не в часы!

В этом посте мы собрали основные горячие клавиши Photoshop — популярнейшего дизайнерского инструмента — и сгруппировали их по функциональной принадлежности. Если рядом с операцией указаны два сочетания, то первое работает в Windows, второе — в macOS. Если указано одно сочетание — оно подойдёт для обеих операционных систем. Спойлер: если прочитать текст до конца, можно узнать, как настроить горячие клавиши так, как вам удобнее.

Работа с файлом 

  • Создать новый файл — Ctrl + N / Cmd + N.
  • Открыть файл — Ctrl + O / Cmd + O. 
  • Сохранить файл как… — Shift + Ctrl + S / Shift + Cmd + S.
  • Сохранить файл в формате PSD — Ctrl + S / Cmd + S.
  • Сохранить для Web — Shift + Ctrl + Alt + S / Shift + Cmd + Opt + S.
  • Показать/скрыть панель операций — Alt + F9 / Opt + F9.
  • Закрыть все открытые документы, кроме текущего — Ctrl + Alt + P / Cmd + Opt + P.

Стандартные команды 

  • Отменить последнее действие — Ctrl + Z / Cmd + Z.
  • Повторить последнее действие — Ctrl + Shift + Z / Command + Shift + Z.
  • Вырезать — F2.
  • Скопировать — F3 или Ctrl + C / Cmd + C.
  • Вставить — F4 или Ctrl + V / Cmd + V.
  • Восстановить — F12.

Просмотр и размер изображения 

  • Переключиться между стандартным режимом, полноэкранным с меню и полноэкранным — F.
  • Просмотреть изображение в масштабе 100% — Ctrl + Alt + 0 / Cmd + Alt + 0.
  • Увеличить изображение (приблизить) — Ctrl + «+» / Cmd + «+».
  • Уменьшить изображение (отдалить) — Ctrl + «–» / Cmd + «–».
  • Настроить изображения под масштаб экрана — Ctrl + 0 / Cmd + 0.
  • Изменить размер фото — открыть окно «Размер изображения» + Ctrl + Alt + I / Cmd + Opt + I.
  • Изменить размер источника клонирования — Shift + Alt + «[» или «]» / Option + Shift + «[» или «]».
  • Инструмент «Масштаб» — Z.

Работа со слоями

  • Показать/скрыть панель «Слои» — F7.
  • Создать слой — Ctrl + Shift + N / Cmd + Shift + N.
  • Создать копию слоя — Ctrl + J / Cmd + J.
  • Создать новый слой путём вырезания — Shift + Ctrl + J / Shift + Cmd + J.
  • Сгруппировать слои — Ctrl + G / Cmd + G.
  • Разгруппировать слои — Ctrl + Shift + G / Cmd + Shift + G.
  • Выделить все слои — Ctrl + Alt + A / Cmd + Opt + A.
  • Выделить верхний слой — Alt + «.» / Opt + «.».
  • Выделить нижний слой — Alt + «,» / Opt + «,».
  • Опустить выбранный слой на один уровень — Ctrl + «[» / Cmd + «[».
  • Поднять выбранный слой на один уровень — Ctrl + «]» / Cmd + «]».
  • Сделать выбранный слой самым верхним — Shift + Ctrl + «]» / Shift + Cmd + «]».
  • Сделать выбранный слой самым нижним — Shift + Ctrl + «[», Shift + Cmd + «[».
  • Объединить выделенные слои — Ctrl + E / Cmd + E.
  • Объединить все видимые слои — Ctrl + Shift + Alt + E / Cmd + Shift + Option + E.
  • Переместить слой без выделения на один пиксель — Ctrl + стрелка / Cmd + стрелка.
  • Залить фоновый или стандартный слой — открытие диалогового окна Backspace или Shift + Backspace / Delete или Shift + Delete.
  • Удалить корректирующий слой — Delete или Backspace / Delete.
  • Скопировать все слои в выделенной области в буфер обмена — Shift + Ctrl + C / Shift + Cmd + C.

Работа с выделением

  • Инвертировать изображение в выделенной области — Shift + F7.
  • Переключиться между исходным изображением и просмотром выделенной области — X.
  • Убрать выделение — Ctrl + D / Cmd + D.
  • Вернуть выделение — Shift + Ctrl + D / Shift + Cmd + D.
  • Инвертировать выделение — Shift + F7.
  • Исключить часть выделенной области — зажать Alt + выделение, зажать Opt + выделение.
  • Добавить новую область к уже выделенной — зажать Shift + выделение.
  • Растушевать выделенную область — Shift + F6.
  • Залить выделенную область — открыть окно с параметрами заливки, затем Shift + F5.

Коррекция изображений

  • Повернуть на 15 градусов — Ctrl + T + Shift + колёсико мыши / Cmd + T + Shift + колёсико мыши.
  • Обесцветить выделенную область или слой — Shift + Ctrl + U / Shift + Cmd + U.
  • Залить — Shift + F5.
  • Обрезать — использовать инструмент «Рамка» + Enter.
  • Инвертировать изображение (отразить зеркально) — Shift + Ctrl + I / Shift + Cmd + I.
  • Переключить режим прозрачности — «/».
  • Перейти в режим свободного трансформирования — Ctrl + T / Cmd + T.
  • Создать или отменить обтравочную маску — Ctrl + Alt + G / Cmd + Opt + G.
  • Повернуть холст — R.
  • Открыть окно «Кривые» — Ctrl + M / Cmd + M.
  • Открыть окно «Уточнить край» — Ctrl + Alt + R / Cmd + Opt + R.
  • Открыть окно «Цветовой тон» — Ctrl + U / Cmd + U.
  • Открыть окно «Уровни» — Ctrl + L / Cmd + L.
  • Открыть окно «Цветовой баланс» — Ctrl + B / Cmd + B.
  • Применить «Автотон» — Shift + Ctrl + L / Shift + Cmd + L.
  • Применить «Автоконтраст» — Alt + Shift + Ctrl + L / Opt + Shift + Cmd + L.
  • Применить автоматическую цветовую коррекцию — Shift + Ctrl + B / Shift + Cmd + B.
  • Переключиться из стандартного режима в режим «Быстрая маска» — Q.
  • Переключить цвет холста вперёд — «пробел» + F.
  • Переключить цвет холста назад — «пробел» + Shift + F.

Работа с инструментами 

Удерживайте клавишу, чтобы временно выбрать нужный инструмент. Если её отпустить, снова активируется предыдущий. 

  • Волшебная палочка — W.
  • Выделение контура — A.
  • Кадрирование перспективы — C.
  • Кисть — B.
  • Лассо — L.
  • Ластик — E.
  • Осветлитель — O.
  • Перо — P.
  • Перемещение — V.
  • Пипетка — I.
  • Поворот вида — R.
  • Прямоугольник — U.
  • Рамка — C.
  • Рука — H.
  • Текст — T.
  • Штамп — S.

Работа с кистью 

  • Показать или скрыть панель кистей — F5.
  • Уменьшить размер кисти — «[».
  • Увеличить размер кисти — «]».
  • Уменьшить жёсткость кисти — «{».
  • Увеличить жёсткость кисти — «}».
  • Повернуть кисть на 1 градус по часовой стрелке — «→».
  • Повернуть кисть на 1 градус против часовой стрелки — «←».
  • Повернуть кисть на 15 градусов по часовой стрелке — Shift + «→».
  • Повернуть кисть на 15 градусов против часовой стрелки — Shift + «←».
  • Предыдущая кисть — «,».
  • Следующая кисть — «.».
  • Первая кисть — «<».
  • Последняя кисть — «>».

Как настроить быстрые клавиши в Photoshop

Бывает так, что вместо одной комбинации горячих клавиш вы вслепую всё время нажимаете другую. Или часто выполняете какую-то операцию, которая требует четырёх кнопок — а хотелось бы всё-таки нажимать две. Или вашим пальцам просто не хватает растяжки для нужной комбинации. Здесь пригодится функция настройки горячих клавиш. К счастью, в Photoshop она есть.

Чтобы организовать всё под себя, зайдите во вкладку «Редактирование» и откройте «Комбинации клавиш». Эту панель также можно вызвать нашей бонусной комбинацией: Alt + Shift + Ctrl + K / Alt + Shift + Cmd + K. Затем выбирайте операции и присваивайте им нужные сочетания. Главное — потом их не забыть.

Горячие клавиши помогут вам работать быстро, но скорость — это не всё, что нужно, чтобы выдавать шедевры. Важно понимать основы композиции и колористики, освоить дизайнерское мышление, уметь работать с идеями. Ну и инструментами пользоваться, конечно. Всему этому учат на факультете дизайна GeekUniversity.

дизайнgraphic-design

Время на прочтение
10 мин

Количество просмотров 56K

В интернете кучу статей по настройке сервера, настройки Apache, Nginx и т.п. В данной статье будет пошагово настроен простой shared хостинг. Все операции производятся через консоль.

В посте будут решены и описаны следующий задачи:

1. Установка Apache + PHP
2. Возможность выбора версий PHP
3. Возможность работы сайтов от разных пользователей, с ограничением на чтение директорий других сайтов.
4. Установка Nginx с модулем pagespeed от google
5. Настройка Nginx как reverse proxy

Все этапы будут содержать описание и пояснения. Сам пост писался больше для себя, чтобы не потерять порядок настройки, но будет очень полезным для новичков, которые начинают разбираться в администрировании сервера. В качестве сервера установлен Ubuntu 16.0.4 только с SSH.

ЭТАП 1 (Установка Apache + PHP)

Запускаем оболочку с root правами:

sudo -i

Устанавливаем apache:

apt install -y apache2

Ключ

 -y 

нужен для того чтобы в процессе установки, автоматически на все вопросы отвечал положительно. К примеру если выполнить:

 apt install apache2 

то в процессе установки нас спросят, действительно ли мы хотим установить.

Устанавливаем php (как mod_php)

 apt install -y php libapache2-mod-php 

На данном этапе у нас установиться php версии 7 как модуль apache.

ЭТАП 2 (Возможность выбора версий PHP)

На первом этапе мы установили сервер Apache + PHP при чем PHP у нас работает как модуль Apache. Существует несколько режимов работы PHP подробную информацию можно прочитать по ссылке «Коротко о CGI, FastCGI, PHP-FPM и mod_php».

Если вам лень читать, то объясню проще:

1. mod_php — сам Apache выполняет php скрипт.

Плюсы: работает быстро, требует минимум настроек и знаний
Минусы: скрипты выполняются от пользователя apache (как правило www-data)

2. CGI/FastCGI — Сервер Apache запускает прикладной скрипт интерпретатора php-cgi, который в свою очередь выполняет php скрипт

Плюсы: скрипты выполняются от произвольного пользователя, можно использовать в связке с другими приложениями (Nginx + PHP), конфигурацию PHP можно сделать индивидуальной
Минусы: скорость работы, дополнительная настройка

3.PHP-FPM — это модернизированный fast-cgi сервер который постоянно держит готовые для работы пул-процессов.

Плюсы: скорость работы, скрипты выполняются от произвольного пользователя, можно использовать в связке с другими приложениями (Nginx + PHP-FPM — самая распространная реализация)
Минусы: дополнительная настройка, занимает порт, на каждого пользователя открывается свой порт.

Мы остановимся на CGI/FastCGI. На самом деле многие может испугать, что он самый медленный, но на большинстве shared хостингов, именно этот режим работы (ispmanager использует именно этот режим работы). Нам потребуется собрать из исходников версии php которые нам необходимы.

2.1 Сборка php из исходников

Обновляем репозиторий:

apt update

Устанавливаем необходимые для сборки пакеты:

apt install -y make 
git autoconf 
lynx 
wget 
build-essential 
libxml2-dev 
libssl-dev 
libbz2-dev 
libcurl4-openssl-dev 
libpng12-dev 
libfreetype6-dev 
libxpm-dev 
libmcrypt-dev 
libmhash-dev 
libmysqlclient-dev 
libjpeg62-dev 
freetds-dev 
libjson-c-dev 
re2c 
zlib1g-dev 
libpcre3 
libpcre3-dev 
unzip 
libxslt1-dev

Символ используется как перенос строки, для удобства чтения.

Создаем папки для php:

mkdir -p /opt/source/php
mkdir -p /opt/php/

Переходим в директорию в которой будут храниться исходники php

cd /opt/source/php

Скачиваем необходимую версию php и распаковываем ёё:

wget -c http://php.net/get/php-5.6.18.tar.bz2/from/this/mirror -O php-5.6.18.tar.bz2
tar xvjf php-5.6.18.tar.bz2

В последней команде мы скачали по ссылке php-5.6.18 и сохранили как php-5.6.18.tar.bz2
После чего распаковали архив.

Переходим в директория скаченного и распакованного php

cd /opt/source/php/php-5.6.18

Конфигурируем php

./configure --enable-cli 
 --prefix=/opt/php/php-5.6.18		
 --disable-rpath		
 --enable-calendar		
 --enable-discard-path 		
 --enable-fastcgi		
 --enable-force-cgi-redirect		
 --enable-fpm		
 --enable-ftp		
 --enable-gd-native-ttf		
 --enable-inline-optimization		
 --enable-mbregex		
 --enable-mbstring		
 --enable-pcntl		
 --enable-soap		
 --enable-sockets		
 --enable-sysvsem		
 --enable-sysvshm		
 --enable-zip		
 --with-bz2		
 --with-curl		
 --with-curl 		
 --with-freetype-dir		
 --with-gd		
 --with-gd 		
 --with-gettext		
 --with-jpeg-dir 		
 --with-jpeg-dir=/usr/lib/		
 --with-libdir=/lib/x86_64-linux-gnu		
 --with-libxml-dir=/usr		
 --with-mcrypt		
 --with-mhash		
 --with-mysql		
 --with-mysql 		
 --with-mysqli		
 --with-mysqli 		
 --with-openssl		
 --with-pcre-regex		
 --with-pdo-mysql		
 --with-png-dir=/usr		
 --with-zlib		
 --with-zlib-dir

Стоить обратить внимание на строку —prefix=/opt/php/php-5.6.18. Именно в эту директорию будет собран проект. Также вы самостоятельно можете добавлять или удалять необходимые модуль и компоненты php. Но при конфигурации обязательно должны быть —enable-fastcgi и —enable-force-cgi-redirect. После конфигурации собираем php

make
make install

Процесс сборки непривычно долгий, поэтому не стоит переживать по этому поводу. По завершению сборки можно проверить командой:

/opt/php/php-5.6.18/bin/php -v

В результате будет что то вроде:

PHP 5.6.18 (cli) (built: Jun 8 2017 15:59:20)
Copyright © 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright © 1998-2016 Zend Technologies

2.2 Настройка Apache

Далее нам потребуется чтобы Apache вызывал php скрипт через режим fastcgi. Устанавливаем и активируем mod_fcgi

apt install libapache2-mod-fcgid
a2enmod cgi fcgid actions

перезапустим сервис Apache

service apache2 restart

2.3 Создание CGI скрипта

Создадим обертку для запуска PHP-FastCGI

mkdir -p /opt/php/php-5.6.18/fcgi-bin

В данной папке создадим скрипт с именем php со следующим содержимом
#!/opt/php/php-5.6.18/bin/php-cgi. Лично я использую редактор nano.

nano /opt/php/php-5.6.18/fcgi-bin/php

Вставляем код, выходим CTRL+X и подтверждаем изменения.

Делаем файл испольняемым:

chmod +x /opt/php/php-5.6.18/fcgi-bin/php

В той же директории создаем файл php.ini () можно скопировать /opt/source/php/php-5.6.18/php.ini-production.

2.4 Настройка хоста для Apache

В примере будет показана настройка виртуального хоста по умолчанию:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        <IfModule mod_fcgid.c>
            IPCCommTimeout 7200
            FcgidConnectTimeout 320
            MaxRequestLen 25728640
            FcgidMaxRequestsPerProcess 0
            FcgidBusyTimeout 3600
            FcgidOutputBufferSize 0
        </IfModule>

        <FilesMatch ".ph(p[3-5]?|tml)$">
                SetHandler fcgid-script
                FCGIWrapper /opt/php/php-5.6.18/fcgi-bin/php
        </FilesMatch>
        ErrorLog /var/www/html/error.log
        CustomLog /var/www/html/access.log combined
</VirtualHost>
<Directory /var/www/html>
        Options +Includes +ExecCGI
</Directory>

Перезапускаем настройки Apache:

service apache2 reload

ЭТАП 3 ( Возможность работы сайтов от разных пользователей, с ограничением на чтение директорий других сайтов.)

Для разграничения прав по пользователям у Apache есть 2 разных модуля suEXEC и ITK.

Рассмотрим как работает каждый из них:

ITK — При поступлении запроса, apache создает процесс-обработчик, который наследует права корневого процесса, но после проверки контекста меняет свои права на указанного пользователя.

suEXEC -При поступлении запроса apache запускает CGI и аналогичные собственные или сторонних разработчиков скрипты/программы внутри веб-папки домена от имени указанного пользователя.

suEXEC в нашем варианте предпочтительней из-за особенности архитектуры работы. Устанавливаем suEXEC

apt install apache2-suexec-custom
a2enmod suexec

Важно, для правильной работы suexec необходимы правильно выставить права на директории.
Как располагать директории вы должны определиться сами, в примере приведется пример, и он не является оптимальным.

Иерархия папок следующая:

|--/var/www/ - Корневая папка, права 751 владелец root
|----/php-bin - Папка храннения дефолтных настроек для php
|------/php-5.6.18 - Папка храннения дефолтных настроек для php-5.6.18
|--------php - Исполняемый файл для php-5.6.18
|--------php.ini - Дефольный файл настроке
|--------php.ini - Дефольный файл настроке
|----/apache-cert - папка хранения сертификатов для apache

Создаем папки для пользователя:

mkdir -p /var/www/users/admin
mkdir -p /var/www/users/admin/domain.ru
mkdir -p /var/www/users/admin/apache-log
mkdir -p /var/www/users/admin/php-bin
mkdir -p /var/www/users/admin/temp
mkdir -p /var/www/users/admin/temp/php-session

Копируем файлы настроек для php:

cp /opt/php/php-5.6.18/fcgi-bin/php /var/www/users/admin/php-bin/php
cp /opt/php/php-5.6.18/fcgi-bin/php.ini /var/www/users/admin/php-bin/php.ini

Создаем юзера (важно помнить что все пользователи в группе admin имеют доступ на запуск программ из sudo, поэтому при выборе имени admin он автоматически будет иметь права на выполнения sudo. В данном примере это не критично, но вам следует помнить об этом при создании пользователя).

useradd -m -s /bin/bash admin
passwd admin

Выставляем владельца папки:

chown admin:admin -R /var/www/users/admin

Выставляем корневую директорию для пользователя:

usermod -d /var/www/users/admin admin

Настраиваем виртуальные хосты в apache:

<VirtualHost *:8080>
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/users/admin/domain.ru

	SuexecUserGroup admin admin	

	<IfModule mod_remoteip.c>
	      RemoteIPHeader X-Forwarded-For
	      RemoteIPHeader X-Real-IP
	      RemoteIPInternalProxy 127.0.0.1
	</IfModule>

	<ifmodule mod_rewrite.c>
		RewriteEngine On
		RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
	</ifmodule>


	<IfModule mod_fcgid.c>
	    IPCCommTimeout 7200
	    FcgidConnectTimeout 320
	    MaxRequestLen 25728640
	    FcgidMaxRequestsPerProcess 0
	    FcgidBusyTimeout 3600
	    FcgidOutputBufferSize 0
	</IfModule>

	<FilesMatch ".ph(p[3-5]?|tml)$">
		SetHandler fcgid-script
		FCGIWrapper /var/www/users/admin/php-bin/php
	</FilesMatch>

	ErrorLog /var/www/users/admin/apache-log/error.log
	CustomLog /var/www/users/admin/apache-log/access.log combined
</VirtualHost>
<Directory /var/www/users/admin/www>
	AllowOverride All
	Options +Includes +ExecCGI
</Directory>

В настройках php.ini пользователя меняем session.save_path
session.save_path = /var/www/users/admin/temp/php-session

Перезапускаем apache:

service apache2 restart

ЭТАП 4 (Установка Nginx с модулем pagespeed от google)

Забегая вперед, для поддержки pagespeed в Nginx требуется пересобрать сам Nginx с этим модулем, но чтобы потом не лазить дополнительно в настройках, проще сначало установить его.
Изменяем порты для Apache:

/etc/apache2/ports.conf
+ Ваши созданные виртуальные хосты

Перезапускаем Apache:

service apache2 restart

Устанавливаем ngnix:

apt-get install nginx

Собираем Nginx с pagespeed

Вначале необходимо установить все необходимы для сборки пакеты:

apt install -y build-essential zlib1g-dev libpcre3 libpcre3-dev unzip libxslt1-dev libgd-dev libgeoip-dev

Создаем папки для исходников nginx:

mkdir -p /opt/source/nginx
cd /opt/source/nginx

Скачиваем и распаковываем pagespeed и psol. Yt cnjbn g

wget https://github.com/pagespeed/ngx_pagespeed/archive/v1.11.33.4-beta.zip
unzip v1.11.33.4-beta.zip
cd ngx_pagespeed-1.11.33.4-beta
wget https://dl.google.com/dl/page-speed/psol/1.11.33.4.tar.gz
tar -xzvf 1.11.33.4.tar.gz

Сам psol скачивается и распаковывается в директории с ngx_pagespeed. Переходим в папку с Ngnix

cd /opt/source/nginx

Проверяем версию ngnix (по умолчанию в ubuntu 16.0.4 устанавливается 1.10.0):

nginx -V

Загружаем т версию NGINX:

wget https://nginx.ru/download/nginx-1.10.0.tar.gz
tar -xvzf nginx-1.10.0.tar.gz

Собираем nginx с теми же параметрами что и установленный, но в конце добавляем дополнительные модули:

cd /opt/source/nginx/nginx-1.10.0
./configure 
--with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module --with-http_sub_module --with-http_xslt_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads 
--add-module=/opt/source/nginx/ngx_pagespeed-1.11.33.4-beta 
--with-http_mp4_module

Собираем Nginx:

make
make install

Собранный бинарный файл Nginx располагается в директории /opt/source/nginx/nginx-1.10.0/objs/nginx. Для того чтобы установить, требуется просто заменить текущий испоняемый файл Nginx на собранный.

Остановим Nginx, заменим файл, и перезапустим его.

service nginx stop

#Переименовываем (на всякий случай) текущий nginx в nginx_backup:

mv /usr/sbin/nginx /usr/sbin/nginx_backup

# Перемещаем на его место новый собранный бинарник:

mv /opt/source/nginx/nginx-1.10.0/objs/nginx /usr/sbin/nginx

перезапускаем Nginx:

service nginx start

Создаем папку хранения кэша для pagespeed:

/var/www/temp/
/var/www/temp/page-speed/

Добавим /etc/nginx/nginx.conf в секцию http:

pagespeed on;
pagespeed FileCachePath "/var/www/temp/page-speed/";
pagespeed EnableFilters combine_css,combine_javascript,rewrite_images,rewrite_css,rewrite_javascript,inline_images,recompress_jpeg,recompress_png,resize_images;
pagespeed JpegRecompressionQuality 85;
pagespeed ImageRecompressionQuality 85;
pagespeed ImageInlineMaxBytes 2048;
pagespeed LowercaseHtmlNames on;

ЭТАП 5 (Настройка Nginx как reverse proxy )

Скажу скажу что в интернете кучу статей для настройки Nginx как reverse proxy. Я лиш приведу ознакомительный вариант настройки.

server { 

	listen 80; 
	server_name domain.ru; 
	access_log /var/log/nginx.access_log;


	location ~* .(jpg|jpeg|gif|png|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|txt|xml|docx|xlsx)$ { 
		root /var/www/users/admin/domain.ru; 
		index index.html index.php; 
		access_log off; 
		expires 30d; 
		error_page 404 = @prox;
	} 

	location @prox{
		proxy_pass 127.0.0.1:8880; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-for $remote_addr; 
		proxy_set_header Host $host; 
		proxy_connect_timeout 60; 
		proxy_send_timeout 90; 
		proxy_read_timeout 90; 
		proxy_redirect off; 
		proxy_set_header Connection close; 
		proxy_pass_header Content-Type; 
		proxy_pass_header Content-Disposition; 
		proxy_pass_header Content-Length;
	}


	location ~ /.ht { 
		deny all; 
	} 


	location / { 
		proxy_pass 127.0.0.1:8880; 
		proxy_set_header X-Real-IP $remote_addr; 
		proxy_set_header X-Forwarded-for $remote_addr; 
		proxy_set_header Host $host; 
		proxy_connect_timeout 60; 
		proxy_send_timeout 90; 
		proxy_read_timeout 90; 
		proxy_redirect off; 
		proxy_set_header Connection close; 
		proxy_pass_header Content-Type; 
		proxy_pass_header Content-Disposition; 
		proxy_pass_header Content-Length; 
	} 
} 

This Python tutorial will teach you how to use the “Python Scipy Curve Fit” method to fit data to various functions, including exponential and gaussian, and will go through the following topics.

  • What is Curve Fit in Scipy?
  • Python Scipy Curve Fit Gaussian
  • Python Scipy Curve Fit Multiple Variables
  • Python Scipy Curve Fit Initial Guess
  • Python Scipy Curve Fit Maxfev
  • Python Scipy Curve Fit Exponential

What is Curve Fit in Scipy

The curve_fit() method of module scipy.optimize that apply non-linear least squares to fit the data to a function.

The syntax is given below.

scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(- inf, inf), method=None, jac=None, full_output=False, **kwargs)

Where parameters are:

  • f: The model’s f(x,…) function. The independent variable must be the first argument, and the subsequent arguments must be the fitting parameters separately.
  • xdata(array_data): It is the independent variable used to measure the data. Can be any object, but should typically be an M-length sequence or a (k, M)-shaped array for functions with k predictors.
  • ydata(array_data): A length M array with nominally as the dependent data f(xdata, …).
  • p0(array_data): Parameters’ initial best guess (length N). If it is None, all starting values will be 1.
  • sigma: Determines the ydata’s level of uncertainty.
  • absolute_sigma(boolean): If True, the computed parameter covariance pcov represents the absolute values of sigma in its application.
  • check_finite(boolean): If True, make sure the input arrays don’t have any nans or infs, and if they do, issue a ValueError. If the input arrays actually contain nans, setting this argument to False can silently result in nonsensical results. As a default, True.
  • bounds(two tuples): Parameters’ lower and upper bounds. No boundaries are the default. A tuple’s elements must each be either an array with a length equal to the number of parameters, or a single element.
  • method: A technique for optimization For unconstrained issues, the default is “lm,” and if bounds are given, it is “trf.” When there are fewer observations than variables, the method “lm” will not function, in this situation, try “trf” or “dogbox.”
  • jac(string, callable): Function with the signature jac(x,…) that generates a dense array-like structure representing the Jacobian matrix of the model function about parameters. It will be scaled using the sigma you supply. The Jacobian will be mathematically estimated if None (the default). The ‘trf’ and ‘dogbox’ methods’ string keywords can be used to choose a finite difference scheme.
  • full_output(boolean): This function returns additional data in the form of infodict, mesg, and ier if True.

The method curve_fit() returns popt(The parameters should be set at their optimum values to minimize the sum of the squared residuals of “f(xdata, *popt) – ydata.”), pcov( popt’s estimated covariance. The parameter estimate’s variance is provided by the diagonals.), infodict(an optional outputs dictionary with the keys) and mesg(a string message containing details about the answer).

Now we will use this method to fit the data in the following subtopics.

Also, check: Python Scipy Derivative of Array

Python Scipy Curve Fit Gaussian

The form of the charted plot is what we refer to as the dataset’s distribution when we plot a dataset, like a histogram. The bell curve, usually referred to as the Gaussian or normal distribution, is the most frequently seen shape for continuous data.

Let’s fit the data to the gaussian distribution using the method curve_fit by following the below steps:

Import the required methods or libraries using the below python code.

from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt

Create x and y data using the below code.

x_data = [ -7.0, -6.0, -10.0, -9.0, -8.0, -1.0, 0.0, 1.0, 2.0, -5.0, -4.0, -3.0, -2.0, 7.0, 8.0, 3.0, 4.0, 5.0, 6.0, 9.0, 10.0]
y_data = [ 8.3, 10.6,1.2, 4.2, 6.7, 15.7, 16.1, 16.6, 11.7, 13.5, 14.5, 16.0, 12.7, 10.3, 8.6, 15.4, 14.4, 14.2, 6.1, 3.9, 2.1]

To make use of NumPy arrays’ useful capabilities, convert x_data and y_data into them.

x_data = np.asarray(x_data)
y_data = np.asarray(y_data)
plt.plot(x_data, y_data, 'o')
Python Scipy Curve Fit Gaussian Example
Python Scipy Curve Fit Gaussian Example

Create a Gaussian function using the below code.

def Gaussian_fun(x, a, b):
    y_res = a*np.exp(-1*b*x**2)
    return y_res

Now fit the data to the gaussian function and extract the required parameter values using the below code.

params, cov = curve_fit(Gaussian_fun, x_data, y_data)
  
fitA = params[0]
fitB = params[1]

fity = Gaussian_fun(x_data, fitA, fitB)

Plot the fitted data using the below code.

plt.plot(x_data, y_data, '*', label='data')
plt.plot(x_data, fity, '-', label='fit')
plt.legend()
Python Scipy Curve Fit Gaussian
Python Scipy Curve Fit Gaussian

From the output, we have fitted the data to gaussian approximately.

Read: Python Scipy Gamma

Python Scipy Curve Fit Multiple Variables

The independent variables can be passed to “curve fit” as a multi-dimensional array, but our “function” must also allow this. Let’s understand with an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy import optimize
import numpy as np

Create a function that will call the array P and unpack it to p and q using the below code.

def fun(P, x, y, z):
    p,q = P
    return np.log(x) + y*np.log(p) + z*np.log(q)

Create some noisy data to fit using the below code.

p = np.linspace(0.1,1.2,100)
q = np.linspace(1.1,2.1, 100)
x, y, z = 8., 5., 9.
z = fun((p,q), x, y, z) * 1 + np.random.random(100) / 100

Define initial guess and fit data to multiple variables using the below code.

p0 = 7., 3., 6.
print(optimize.curve_fit(fun, (p,q), z, p0))
Python Scipy Curve Fit Multiple Variables
Python Scipy Curve Fit Multiple Variables

Read: Python Scipy Stats Poisson

Python Scipy Curve Fit Initial Guess

The fit parameters are initially estimated using the “curve fit” procedure using values of 1.0. However, there are instances where the fit will not converge, in which case we must offer a wise assumption as a starting point. Let’s see with an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy import optimize
import numpy as np

Here, we’ll specify some data that are similarly spaced in time and a range of temperatures in the hopes that they will fit an exponential that resembles a charging capacitor. In addition to defining error bars on the temperature values, we take this array of temperatures and add some random noise to it.

def capcitor(x, y, z):
    return y*(1-np.exp(z*x))
t = np.linspace(0.5,3.0, 9)
tempretures = np.array([14.77, 18.47, 20.95, 22.62, 23.73, 24.48, 24.98, 25.32, 25.54])
tempretures = tempretures + 0.4*np.random.normal(size=len(tempretures))
dTempretures = np.array([1.3, 0.8, 1.1, 0.9, 0.8, 0.8, 0.7, 0.6, 0.6])

Now fit data using the below code.

fit_Params, fit_Covariances = optimize.curve_fit(capcitor, t, tempretures)
print(fit_Params)
print(fit_Covariances)

The code above won’t work if we run it. Take a look at the resulting error message.

Python Scipy Curve Fit Initial Guess Example
Python Scipy Curve Fit Initial Guess Example

As soon as we add some educated guesses (p0) for a and b, we’ll see that the fit is now perfect.

fit_Params, fit_Covariances = optimize.curve_fit(capcitor, t, tempretures, p0 = [30.0, -1.0])
print(fit_Params)
print(fit_Covariances)
Python Scipy Curve Fit Initial Guess
Python Scipy Curve Fit Initial Guess

This is how to use the initial guesses with the method curve_fit() for fitting.

Read: Python Scipy Eigenvalues

The method curve_fit() of Python Scipy accepts the parameter maxfev that is the maximum number of function calls. In the above subsection, When run fit the function to a data without initial guess, it shows an error Optimal parameters not found: Number of calls to function has reached maxfev = 600.

That means the function is called 600 times and didn’t find any optimal parameters. Let’s increase the value of the argument maxfev and see if it finds the optimal parameters. So here we will take the same example as we have taken in the above subsection “Python Scipy Curve Fit Initial Guess”.

fit_Params, fit_Covariances = optimize.curve_fit(capcitor, t, tempretures, maxfev=800)
print(fit_Params)
print(fit_Covariances)
Python Scipy Curve Fit Maxfev
Python Scipy Curve Fit Maxfev

From the output, we can see that the optimal parameters are found when the function is called 800 times.

Read: Python Scipy Stats Multivariate_Normal

Python Scipy Curve Fit Exponential

The curve_fit() method in the scipy.optimize the module of the SciPy Python package fits a function to data using non-linear least squares. As a result, in this section, we will develop an exponential function and provide it to the method curve fit() so that it can fit the generated data.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy import optimize

Create an exponential function using the below code.

def expfunc(x, y, z, s):
    return y * np.exp(-z * x) + s

Use the code below to define the data so that it can be fitted with noise, fit for the parameters of the function “expfunc” and also restrict the optimization to a specific area.

x_data = np.linspace(0, 5, 60)
y_data = expfunc(x_data, 3.1, 2.3, 1.0)

random_numgen = np.random.default_rng()
noise_y = 0.3 * random_numgen.normal(size=x_data.size)

data_y = y_data + noise_y
plt.plot(x_data, data_y, 'b-', label='data')

p_opt, p_cov = optimize.curve_fit(expfunc, x_data, data_y)
plt.plot(x_data, expfunc(x_data, *p_opt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(p_opt))
Python Scipy Curve Fit Exponential
Python Scipy Curve Fit Exponential

From the above output, we can see the fitted data to an exponential function using the method curve_fit(), this is how to fit the data to an exponential function.

You may also like to read the following Python SciPy tutorials.

  • Python Scipy Freqz
  • Scipy Ndimage Imread
  • Python Scipy Gaussian_Kde
  • Scipy Distance Matrix
  • Python Scipy Stats Fit
  • Python Scipy Exponential
  • Scipy Special Module

So, in this tutorial, we have learned about the “Python Scipy Curve Fit” and covered the following topics.

  • What is Curve Fit in Scipy?
  • Python Scipy Curve Fit Gaussian
  • Python Scipy Curve Fit Bounds
  • Python Scipy Curve Fit Multiple Variables
  • Python Scipy Curve Fit Initial Guess
  • Python Scipy Curve Fit Maxfev
  • Python Scipy Curve Fit Exponential

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти внутреннее сопротив
  • Облако на телефоне как найти на айфоне
  • Как найти объем шкафа формула
  • Плохое прошлое как исправить
  • Как найти кубатуру бревна

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии