Изменить имя таблицы с помощью миграции Laravel 10

В этой статье мы увидим, как изменить имя таблицы с помощью миграции laravel 10. Здесь мы узнаем об имени таблицы изменений laravel 10 с помощью миграции. Вы можете переименовать таблицу с помощью миграции. В laravel 10 предоставьте метод rename() для изменения имени таблицы. 

Итак, давайте посмотрим на миграцию имен таблиц laravel 10, как переименовать таблицу при миграции laravel 10 и как переименовать существующую таблицу в laravel 8, laravel 9 и laravel 10.

Чтобы переименовать существующую таблицу базы данных, используйте  rename метод.

use Illuminate\Support\Facades\Schema;
 
Schema::rename($from, $to);

Schema::rename('old_table_name', 'new_table_name');

Пример:

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangeUsersTableName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('user', 'users');
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}

Оригинальный источник статьи: https://websolutionstuff.com/

#laravel #name #change 

Изменить имя таблицы с помощью миграции Laravel 10

使用 Laravel 10 迁移更改表名

在本文中,我们将看到如何使用 laravel 10 迁移更改表名。在这里,我们将学习使用迁移的 laravel 10 更改表名。您可以在迁移的帮助下重命名表。在 laravel 10 中,提供了 rename() 方法来更改表名。 

那么,让我们看看 laravel 10 更改表名迁移,如何在 laravel 10 迁移中重命名表,以及如何在 laravel 8、laravel 9 和 laravel 10 中重命名现有表。

要重命名现有数据库表,请使用 rename 方法。

use Illuminate\Support\Facades\Schema;
 
Schema::rename($from, $to);

Schema::rename('old_table_name', 'new_table_name');

例子:

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangeUsersTableName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('user', 'users');
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}

原文出处:https: //websolutionstuff.com/

#laravel #name #change 

使用 Laravel 10 迁移更改表名

Change Table Name Using Laravel 10 Migration

In this article, we will see how to change the table name using laravel 10 migration. Here, we will learn about the laravel 10 change table name using migration. You can rename the table with the help of migration. In laravel 10, provide rename() method for change the table name. 

So, let's see laravel 10 change table name migration, how to rename a table in laravel 10 migration, and how to rename an existing table in laravel 8, laravel 9, and laravel 10.

To rename an existing database table, use the rename method.

use Illuminate\Support\Facades\Schema;
 
Schema::rename($from, $to);

Schema::rename('old_table_name', 'new_table_name');

Example:

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class ChangeUsersTableName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('user', 'users');
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
}

Original article source at: https://websolutionstuff.com/

#laravel #name #change 

Change Table Name Using Laravel 10 Migration

Изменить имя пользователя в Debian 11 Bullseye

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

Изменить имя пользователя в Debian 11 Bullseye через командную строку

Обратите внимание, что вы не можете изменить имя пользователя текущего пользователя в Debian. Однако вы можете изменить текущее имя пользователя, создав временного пользователя , а затем войдя в систему под этим пользователем и соответствующим образом изменив его.

Например, если у вас есть имя пользователя с идентификатором «user1» , вам нужно будет создать другого пользователя «user2» и войти в систему под этим пользователем. После этого вы можете изменить имя пользователя user1 .

Чтобы создать нового пользователя в Debian, выполните приведенную ниже команду:

sudo adduser mainuser

После создания пользователя предоставьте этому пользователю привилегии sudo с помощью следующей команды:

sudo usermod -aG sudo mainuser

Теперь подтвердите пользователя, отобразив список всех пользователей. Следующая команда в Linux используется для получения списка всех пользователей:

cut -d: -f1 /etc/passwd

Изменить имя пользователя в Debian 11 Bullseye

Вы можете изменить имя пользователя в Debian 11 с:

  • Терминал
  • графический интерфейс

1: изменить имя пользователя в Debian из терминала

Есть два способа изменить имя пользователя в Debian из терминала:

  • Использование команды usermod
  • Использование команды sed

i: изменить имя пользователя в Debian из терминала с помощью команды usermod

Во-первых, убедитесь, что имя пользователя не входило в систему. Измените имя с помощью команды usermod. Имя пользователя будет изменено со старого имени на новое имя:

sudo usermod -l <newname> <oldname>

В приведенном ниже примере я меняю имя пользователя моего временно созданного пользователя с именем mainuser на zainab :

sudo usermod -l zainab mainuser

Проверьте, изменено имя или нет, выполнив команду для отображения списка пользователей:

ii: изменение имени пользователя в Debian из терминала с помощью команды sed

Откройте терминал и переключитесь на root с помощью следующей команды:

sudo su

Затем измените имя пользователя учетной записи, введя старое и новое имя. Ниже приведен основной синтаксис команды:

sed -i s/<old_user>/<new_user>/g /etc/passwd

Давайте изменим имя пользователя zainab на linux2 с помощью следующей команды:

sed -i s/zainab/linux2/g /etc/passwd

После запуска команды перезагрузите систему, и вы увидите измененное имя на экране блокировки:

Изменить имя пользователя в Debian 11 Bullseye через графический интерфейс

Другой самый простой способ изменить имя пользователя в Debian — через графический интерфейс. Запустите настройки устройства из Activity:

В настройках устройства нажмите «Пользователи» на левой панели, и вы увидите список пользователей в правой части экрана. Сначала необходимо ввести пароль, чтобы внести изменения в устройство:

На изображении ниже я изменяю имя пользователя Linux2 на zainab , щелкнув значок карандаша:

Имя пользователя успешно изменено:

Заворачивать

При настройке имени пользователя для вашей системы Debian могут возникнуть ошибки, но вы можете их исправить. В Debian вы можете использовать команду usermod для изменения текущего имени пользователя. Чтобы изменить имя пользователя в Debian, сначала вам нужно создать временного пользователя с привилегиями sudo, чтобы можно было изменить имя текущего пользователя. Надеюсь, теперь у вас есть имя пользователя для вашей системы Debian именно так, как вам нравится.

Оригинальный источник статьи: https://linuxhint.com/

#debian #change #username 

Изменить имя пользователя в Debian 11 Bullseye
津田  淳

津田 淳

1682424072

在 Debian 11 Bullseye 上更改用户名

当您在您的设备上设置 Debian 系统时,您首先要输入的是用户名。但稍后,您可能不喜欢用户名并想要更改它。Debian 中的每个用户都有一个特定的唯一用户名来标识他们。如果您想更改您在 Debian 中的当前用户名,您可以随时按照本文的指南进行更改。

通过命令行在 Debian 11 Bullseye 上更改用户名

请注意,您不能更改 Debian 上当前用户的用户名。但是,您可以通过创建一个临时用户来更改当前用户名,然后登录到该用户并相应地进行更改。

例如,如果您的用户名带有“user1” id,您将需要创建另一个用户“user2”,并在系统上登录到该用户。之后,您可以更改user1的用户名。

要在 Debian 上创建新用户,请执行以下命令:

sudo adduser mainuser

创建用户后,通过以下命令为该用户授予 sudo 权限:

sudo usermod -aG sudo mainuser

现在,通过显示所有用户的列表来验证用户。Linux中的以下命令用于获取所有用户的列表:

cut -d: -f1 /etc/passwd

在 Debian 11 Bullseye 上更改用户名

您可以从以下位置更改 Debian 11 上的用户名:

  • 终端
  • 图形用户界面

1:从终端更改 Debian 上的用户名

有两种方法可以从终端更改 Debian 上的用户名:

  • 使用 usermod 命令
  • 使用 sed 命令

i:使用 usermod 命令从终端更改 Debian 上的用户名

首先,确保该用户名尚未登录系统。使用 usermod 命令更改名称。用户的名称将从旧名称更改为新名称:

sudo usermod -l <newname> <oldname>

在下面给出的示例中,我将名称为mainuser的临时创建的用户的用户名更改为zainab

sudo usermod -l zainab mainuser

通过执行显示用户列表的命令来验证名称是否已更改:

ii:使用 sed 命令从终端更改 Debian 上的用户名

打开终端并通过以下命令切换到根目录:

sudo su

然后通过输入旧名称和新名称来更改帐户的用户名。以下是该命令的基本语法:

sed -i s/<old_user>/<new_user>/g /etc/passwd

让我们通过以下命令将用户名zainab更改为linux2 :

sed -i s/zainab/linux2/g /etc/passwd

运行命令后,重新启动系统,您将在锁定屏幕上看到更改后的名称:

通过 GUI 在 Debian 11 Bullseye 上更改用户名

在 Debian 上更改用户名的另一种最简单的方法是通过 GUI。从活动启动设备的设置:

在设备设置中,单击左侧面板中的用户,您将在屏幕右侧看到用户列表。您必须先输入密码才能在设备中进行更改:

在下图中,我通过单击铅笔图标将Linux2的用户名修改为zainab :

用户名修改成功:

包起来

为您的 Debian 系统设置用户名时可能会遇到错误,但您可以修复它们。在 Debian 中,您可以使用usermod 命令更改当前用户名。要在 Debian 中更改用户名,您首先需要创建一个具有 sudo 权限的临时用户,以便可以更改当前用户的用户名。希望您现在已经按照自己喜欢的方式获得了 Debian 系统的用户名。

文章原文出处:https: //linuxhint.com/

#debian #change #username 

在 Debian 11 Bullseye 上更改用户名
Gordon  Matlala

Gordon Matlala

1682420225

Change Username on Debian 11 Bullseye

When you set up the Debian system on your device, the first thing you have to enter is the username. But later on, you might not like the username and want to change it. Each user in Debian has a specific unique username that identifies them. If you want to change your current username in Debian, you can change it anytime by following this article’s guidelines.

Change Username on Debian 11 Bullseye via Command Line

Note that you cannot change the username of a current user on Debian. However, you can change the current username by creating a temporary user and then login to that user and changing it accordingly.

For example, if you have a username with “user1” id, you will need to create another user “user2”, and login to that user on the system. After that, you can change the username of user1.

To create a new user on Debian, follow the below-given command:

sudo adduser mainuser

After creating the user, give this user sudo privileges from the following command:

sudo usermod -aG sudo mainuser

Now, verify the user by displaying the list of all the users. The following command in the Linux is used to get the list of all users:

cut -d: -f1 /etc/passwd

Change Username on Debian 11 Bullseye

You can change username on Debian 11 from:

  • Terminal
  • GUI

1: Change Username on Debian from Terminal

There are two ways to change the username on Debian from the terminal:

  • Using the usermod Command
  • Using the sed Command

i: Change Username on Debian from Terminal Using usermod Command

First, make sure the username has not logged in to the system. Change the name using the usermod command. The name of the user will be changed from the old name to the new name:

sudo usermod -l <newname> <oldname>

In the below-given example I am changing the username of my temporarily created user with the name of mainuser to the zainab:

sudo usermod -l zainab mainuser

Verify whether the name is changed or not by executing the command for displaying the list of users:

ii: Change Username on Debian from Terminal Using sed Command

Open the terminal and switch to the root via the following command:

sudo su

Then change the username of the account by entering the old and new name. The following is the basic syntax of the command:

sed -i s/<old_user>/<new_user>/g /etc/passwd

Let’s change the username zainab to the linux2 by the following command:

sed -i s/zainab/linux2/g /etc/passwd

Once you run the command, reboot the system and you will see the changed name on the lock screen:

Change Username on Debian 11 Bullseye via GUI

The other easiest approach to changing the username on the Debian is via the GUI. Launch the settings of the device from Activities:

In the device settings, click on the Users from the left panel and you will see the list of users on the right side of the screen. You have to enter the password first to make the changes in the device:

In the below image, I am modifying the username of Linux2 to zainab by clicking on the pencil icon:

The username has been changed successfully:

Wrap Up

Errors can be encountered while setting a username for your Debian system but you can fix them. In Debian, you can use the usermod command to change the current username. To change the username in Debian first you need to create a temporary user with sudo privileges so that the username of the current user can be altered. Hopefully, you’ve now got the username for your Debian system just the way you like it.

Original article source at: https://linuxhint.com/

#debian #change #username 

Change Username on Debian 11 Bullseye

Изменить размер подкачки в Ubuntu

В этом руководстве мы покажем, как изменить размер подкачки в Ubuntu 22.04.

Подкачать файл в Linux

Оперативная память машины разделена ядром Linux на части, называемые «страницами». Всякий раз, когда страница копируется в предварительно сконфигурированное пространство на дополнительных устройствах хранения (в большинстве случаев на жестком диске или SSD), это называется «обменом». Предварительно сконфигурированное выделенное пространство называется «пространством подкачки».

Общий объем физической памяти (ОЗУ) и пространства подкачки называется «виртуальной» памятью.

Обмен обязателен?

Есть несколько причин, почему замена необходима:

  • Когда требуется больше памяти, чем доступно физически, замена менее важных страниц освобождает больше памяти для процесса, которому требуется больше памяти.
  • Большая часть страниц, используемых во время запуска программы, может использоваться очень мало. Замена этих страниц может освободить больше памяти для других приложений.
  • Если пространство подкачки не назначено, если пространство ОЗУ полностью занято, это может привести к сбою системы, особенно в системах с небольшим объемом ОЗУ.

Однако обмен имеет свои недостатки:

  • По сравнению с оперативной памятью вторичные хранилища (жесткие диски, твердотельные накопители и т. д.) работают очень медленно. Для сравнения, скорость доступа к оперативной памяти измеряется в наносекундах, тогда как скорость доступа к диску измеряется в миллисекундах.
  • Из-за разницы в скорости чтения/записи подкачка — очень медленный процесс. Когда происходит много подкачки, это в конечном итоге замедляет работу системы.

Типы пространств подкачки

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

  • Выделенный раздел подкачки — там нельзя хранить никакие другие файлы.
  • Файлы подкачки — эти файлы могут находиться где угодно в файловой системе.

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

Подкачать файл в Ubuntu

Ubuntu обычно использует выделенный раздел подкачки для подкачки. Часто этот раздел создается во время установки. Однако мы можем создавать и настраивать файлы подкачки по желанию.

Список пространств подкачки

Следующая команда показывает все пространства подкачки, которые настроены в данный момент:

$ swapon

Список содержит все области подкачки, как разделы, так и файлы подкачки.

Создание файлов подкачки

Ключевое преимущество файлов подкачки по сравнению с разделом подкачки заключается в том, что размер файла можно легко изменить, тем самым изменив объем пространства подкачки, не касаясь разделов диска. В этом разделе мы создаем новый файл подкачки и добавляем его в текущий пул подкачки.

Сначала создайте пустой файл с помощью следующей команды:

$ sudo dd if=/dev/zero of=/new_swap bs=1M count=2048

Здесь:

  • Размер файла рассчитывается как 1M X 2048 = 2G.
  • Чтобы создать файл другого размера, соответствующим образом измените значение аргумента count.
  • /dev/zero — это специальное блочное устройство в системе Linux, которое выводит нулевые байты при каждом чтении.
  • Хотя мы можем использовать другие инструменты, такие как fallocate, для создания файла, в некоторых ситуациях это может привести к проблемам. Это обсуждается более подробно в этом посте AskUbuntu .

Далее нам нужно установить правильные права доступа к файлам с помощью следующей команды:

$ sudo chmod 600 /new_swap

Теперь нам нужно отформатировать файл как swap, используя следующую команду:

$ sudo mkswap /new_swap

Наконец, мы можем добавить файл в пул подкачки.

$ sudo swapon /new_swap

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

$ swapon

Обратите внимание, что это действие является временным. После перезагрузки файл подкачки больше не будет использоваться. Чтобы сделать это изменение постоянным, мы должны обновить таблицу /etc/fstab следующей записью:

$ /new_swap swap swap defaults 0 0

Проверка свободного пространства подкачки

Следующая команда выводит использование как памяти, так и подкачки:

$ sudo free -h

Удаление файла подкачки

Чтобы удалить файл подкачки, мы сначала должны убедиться, что он не используется. Следующая команда деактивирует файл подкачки:

$ sudo swapoff -v /<swap_file>

Проверьте список активных пространств подкачки, чтобы подтвердить изменение.

$ swapon

Если файл подкачки объявлен в /etc/fstab , вы также должны удалить запись. Теперь файл подкачки можно безопасно удалить. Удалите его с помощью следующей команды:

$ sudo rm /<swap_file>

Изменение размера свопа

В зависимости от типа пространства подкачки (раздел или файл) процесс изменения размера подкачки может различаться.

Изменение размера раздела подкачки

Раздел можно расширить только в том случае, если сразу после него есть незанятые места. В противном случае единственным другим вариантом изменения размера является сжатие раздела. Это также относится к разделу подкачки.

Если вы используете рабочий стол GNOME, приложение «Диски» может дать представление о ситуации.

Кроме того, мы можем использовать GParted для визуализации.

Как видите, в этой системе раздел подкачки находится непосредственно рядом с корневым разделом. Это не оставляет места для расширения раздела подкачки.

Однако можно выполнять операции сжатия и переформатирования. Узнайте больше об управлении разделами с помощью fdisk или GParted . Команда resize2fs также необходима для изменения размера существующей файловой системы в соответствии с измененным размером раздела.

Изменение размера файла подкачки

Чтобы манипулировать файлом подкачки, нам сначала нужно удалить его из пула подкачки. Выполните следующую команду:

$ sudo swapoff /new_swap

Теперь повторно запустите команду dd, чтобы увеличить размер файла:

$ sudo dd if=/dev/zero of=/new_swap bs=1G count=2 oflag=append conv=notrunc

Здесь мы добавили на 2 ГБ больше места в файл подкачки. Далее мы переформатируем файл как swap, используя следующую команду:

$ sudo mkswap /new_swap

Наконец, мы можем включить обмен на него:

$ sudo swapon /new_swap

$ swapon

Обратите внимание, что в определенных ситуациях попытка отключить файл подкачки может привести к ошибке, например «Ошибка подкачки: невозможно выделить память». В таком случае делаем следующее:

  • Создайте новый файл подкачки с большим пространством.
  • Прикрепите больший своп к системе.
  • Удалите старый файл подкачки меньшего размера.
  • Удалите старую запись файла подкачки из /etc/fstab (если применимо).

Заключение

Мы подробно обсудили управление пространствами подкачки в Ubuntu. Мы обсудили различные типы пространств подкачки. Мы научились изменять размер разделов подкачки и работать с файлами подкачки (создавать, удалять и изменять размер).

Хотите освоить Ubuntu? Ознакомьтесь с подкатегорией Ubuntu , которая содержит многочисленные руководства по настройке системы Ubuntu и использованию различных инструментов.

Удачных вычислений!

Оригинальный источник статьи: https://linuxhint.com/

#ubuntu #change #size 

Изменить размер подкачки в Ubuntu
佐藤  桃子

佐藤 桃子

1681241400

在 Ubuntu 中更改交换大小

在本指南中,我们将演示如何在 Ubuntu 22.04 中更改交换大小。

Linux 中的交换文件

机器的 RAM 被 Linux 内核分成称为“页面”的块。每当将页面复制到辅助存储设备(大多数情况下是硬盘或 SSD)上的预配置空间时,它就称为“交换”。预先配置的专用空间称为“交换空间”。

物理内存 (RAM) 和交换空间的总量称为“虚拟”内存。

是否需要交换?

需要交换的原因有几个:

  • 当需要比实际可用内存更多的内存时,交换不太重要的页面可以为需要更多内存的进程释放更多内存。
  • 程序启动期间使用的大部分页面可能很少使用。交换这些页面可以为其他应用释放更多内存。
  • 如果没有分配交换空间,如果 RAM 空间被完全占用,可能会导致系统崩溃,尤其是 RAM 空间不足的系统。

然而,交换有其自身的一系列缺点:

  • 与 RAM 相比,二级存储(硬盘、SSD 等)速度极慢。换句话说,RAM 访问速度以纳秒为单位,而磁盘访问速度以毫秒为单位。
  • 由于读/写速度的差异,交换是一个非常缓慢的过程。当发生大量交换时,它最终会减慢系统速度。

交换空间的类型

您会在 Linux 中遇到两种类型的交换空间:

  • 一个专用的交换分区——那里不能存储其他文件。
  • 交换文件——这些文件可以位于文件系统中的任何位置。

根据可用的 RAM 空间,交换空间的大小可能会有所不同。这里有几个例子:

在 Ubuntu 中交换文件

Ubuntu 通常使用专用的交换分区进行交换。通常,此分区是在安装过程中创建的。但是,我们可以随意创建和调整交换文件。

列出交换空间

以下命令显示当前配置的所有交换空间:

$ swapon

该列表包含所有交换空间,包括分区和交换文件。

创建交换文件

交换文件相对于交换分区的一个关键优势是可以轻松更改文件大小,从而在不触及磁盘分区的情况下更改交换空间量。在本节中,我们创建一个新的交换文件并将其添加到当前交换池中。

首先,使用以下命令创建一个空白文件:

$ sudo dd if=/dev/zero of=/new_swap bs=1M count=2048

这里:

  • 文件大小计算为 1M X 2048 = 2G。
  • 要创建具有不同大小的文件,请相应地更改 count 参数的值。
  • /dev/zero 是 Linux 系统中的一种特殊块设备,每次读取时输出零字节。
  • 虽然我们可以使用其他工具(如 fallocate)来创建文件,但在某些情况下,它可能会导致问题。这篇AskUbuntu 帖子对此进行了更深入的讨论。

接下来,我们需要使用以下命令设置正确的文件权限:

$ sudo chmod 600 /new_swap

现在,我们需要使用以下命令将文件格式化为交换文件:

$ sudo mkswap /new_swap

最后,我们可以将文件添加到交换池中。

$ sudo swapon /new_swap

如果操作成功,新的交换文件应该出现在交换空间列表中。

$ swapon

请注意,此操作只是暂时的。重新启动后,将不再使用交换文件。要使其成为永久更改,我们必须使用以下条目更新 /etc/fstab 表:

$ /new_swap swap swap defaults 0 0

检查可用交换空间

以下命令打印内存和交换使用情况:

$ sudo free -h

删除交换文件

要删除交换文件,我们首先必须确保它未被使用。以下命令停用交换文件:

$ sudo swapoff -v /<swap_file>

检查活动交换空间列表以确认更改。

$ swapon

如果交换文件在/etc/fstab中声明,您还必须删除该条目。现在,可以安全删除交换文件了。使用以下命令删除它:

$ sudo rm /<swap_file>

更改交换大小

根据交换空间类型(分区或文件),更改交换大小的过程可能会有所不同。

更改交换分区的大小

仅当紧接其后有未分配的空间时,才能扩展分区。否则,唯一的其他调整大小选项是缩小分区。它也适用于交换分区。

如果您使用的是 GNOME 桌面,“磁盘”应用程序可以让您深入了解情况。

或者,我们可以使用GParted将其可视化。

如您所见,交换分区紧挨着该系统中的根分区。这没有为扩展交换分区留下空间。

但是,可以执行缩小和重新格式化操作。了解有关使用fdisk 或 GParted管理分区的更多信息。还需要resize2fs 命令来根据调整后的分区调整现有文件系统的大小。

更改交换文件的大小

要操作交换文件,我们首先需要将其从交换池中删除。运行以下命令:

$ sudo swapoff /new_swap

现在,重新运行 dd 命令以增加文件的大小:

$ sudo dd if=/dev/zero of=/new_swap bs=1G count=2 oflag=append conv=notrunc

在这里,我们向交换文件添加了 2GB 以上的空间。接下来,我们使用以下命令将文件重新格式化为交换文件:

$ sudo mkswap /new_swap

最后,我们可以启用交换:

$ sudo swapon /new_swap

$ swapon

请注意,在某些情况下,尝试禁用交换文件可能会导致类似“交换失败:无法分配内存”的错误。在这种情况下,我们执行以下操作:

  • 创建一个具有更大空间的新交换文件。
  • 将更大的交换连接到系统。
  • 删除旧的、较小的交换文件。
  • 从/etc/fstab中删除旧的交换文件条目(如果适用)。

结论

我们讨论了有关在 Ubuntu 中管理交换空间的深入演示。我们讨论了各种类型的交换空间。我们学习了调整交换分区的大小以及如何使用交换文件(创建、删除和调整大小)。

有兴趣掌握 Ubuntu 吗?查看Ubuntu 子类别,其中包含大量关于调整 Ubuntu 系统和使用各种工具的指南。

快乐的计算!

文章原文出处:https: //linuxhint.com/

#ubuntu #change #size 

在 Ubuntu 中更改交换大小
Lawson  Wehner

Lawson Wehner

1681222140

Change the Swap Size in Ubuntu

In this guide, we will demonstrate on how to change the swap size in Ubuntu 22.04.

Swap File in Linux

The RAM of the machine is divided into chunks by the Linux kernel called “pages”. Whenever a page is copied to a preconfigured space on the secondary storage devices (hard disk or SSD in most cases), it’s called “swapping”. The preconfigured dedicated space is called the “swap space”.

The total amount of physical memory (RAM) and swap space is called the “virtual” memory.

Is Swapping Necessary?

There are a couple of reasons why swapping is needed:

  • When there’s a demand for more memory than what is physically available, swapping less important pages frees up more memory for the process that requires more memory.
  • A big portion of the pages used during the startup of a program may see very little usage. Swapping those pages can free up more memory for other apps.
  • If no swap space is assigned, if the RAM space is fully occupied, it can cause the system to crash, especially the systems with low RAM space.

However, swapping comes with its own set of downsides:

  • Compared to RAM, secondary storages (hard disks, SSDs, and such) are extremely slow. To put it into perspective, RAM access speeds are measured in nanoseconds whereas the disk access speeds are measured in milliseconds.
  • Because of the difference in read/write speeds, swapping is a very slow process. When a lot of swapping is happening, it eventually slows down the system.

Types of Swap Spaces

You will come across two types of swap spaces in Linux:

  • A dedicated swap partition – No other files can be stored there.
  • Swap files – These files can be anywhere within the filesystem.

Depending on the available RAM space, the size of the swap space can vary. Here are a couple of examples:

Swap File in Ubuntu

Ubuntu generally uses a dedicated swap partition for swapping. Oftentimes, this partition is created during the installation. However, we can create and tweak the swap files at will.

Listing the Swap Spaces

The following command shows all the swap spaces that are currently configured:

$ swapon

The list contains all the swap spaces, both partitions and swap files.

Creating Swap Files

A key advantage of swap files over swap partition is that the file size can easily be altered, thus changing the amount of swap space without touching the disk partitions. In this section, we create a new swap file and add it to the current swap pool.

First, create a blank file using the following command:

$ sudo dd if=/dev/zero of=/new_swap bs=1M count=2048

Here:

  • The file size is calculated as 1M X 2048 = 2G.
  • To create a file with a different size, change the value of the count argument accordingly.
  • The /dev/zero is a special block device in the Linux system that outputs zero bytes every time it’s read.
  • While we can use other tools like fallocate to create the file, in some situations, it can lead to problems. It’s discussed more in-depth in this AskUbuntu post.

Next, we need to set the correct file permissions using the following command:

$ sudo chmod 600 /new_swap

Now, we need to format the file as swap using the following command:

$ sudo mkswap /new_swap

Finally, we can add the file to the swap pool.

$ sudo swapon /new_swap

If the action is successful, the new swap file should appear on the list of swap spaces.

$ swapon

Note that this action is only temporary. Upon restart, the swap file will no longer be used. To make it a permanent change, we have to update the /etc/fstab table with the following entry:

$ /new_swap swap swap defaults 0 0

Checking the Free Swap Space

The following command prints both memory and swap usage:

$ sudo free -h

Deleting the Swap File

To delete a swap file, we first have to make sure that it’s not in use. The following command deactivates a swap file:

$ sudo swapoff -v /<swap_file>

Check the list of active swap spaces to confirm the change.

$ swapon

If the swap file is declared in /etc/fstab, you also have to remove the entry. Now, the swap file is safe to be deleted. Delete it using the following command:

$ sudo rm /<swap_file>

Changing the Swap Size

Depending on the swap space type (partition or file), the process of changing the swap size may vary.

Changing the Size of the Swap Partition

A partition can only be extended if there are unallocated spaces immediately after it. Otherwise, the only other resizing option is shrinking the partition. It also applies to the swap partition.

If you’re using the GNOME desktop, the “Disks” app can offer an insight into the situation.

Alternatively, we can use GParted to visualize it.

As you can see, the swap partition is directly next to the root partition in this system. This leaves no room for extending the swap partition.

However, shrinking and reformatting operations can be performed. Learn more about managing partitions using fdisk or GParted. The resize2fs command is also needed to resize the existing filesystem in accordance with the resized partition.

Changing the Size of the Swap File

To manipulate a swap file, we first need to remove it from the swap pool. Run the following command:

$ sudo swapoff /new_swap

Now, rerun the dd command to increase the size of the file:

$ sudo dd if=/dev/zero of=/new_swap bs=1G count=2 oflag=append conv=notrunc

Here, we added 2GB more space to the swap file. Next, we reformat the file as swap using the following command:

$ sudo mkswap /new_swap

Finally, we can enable swapping to it:

$ sudo swapon /new_swap

$ swapon

Note that in certain situations, trying to disable the swap file may result in an error like “swapoff failed: Cannot allocate memory”. In that case, we do the following:

  • Create a new swap file with bigger space.
  • Attach the bigger swap to the system.
  • Delete the older, smaller swap file.
  • Remove the older swap file entry from /etc/fstab (if applicable).

Conclusion

We discussed an in-depth demonstrated about managing the swap spaces in Ubuntu. We discussed the various types of swap spaces. We learned to resize the swap partitions and how to work with swap files (creating, deleting, and resizing).

Interested in mastering Ubuntu? Check out the Ubuntu sub-category which contains numerous guides on tweaking the Ubuntu system and using various tools.

Happy computing!

Original article source at: https://linuxhint.com/

#ubuntu #change #size 

Change the Swap Size in Ubuntu
Desmond  Gerber

Desmond Gerber

1670680080

How to Change The Host File Of an Android Emulator

While working on a bug in one of my projects recently, I found an issue that I could only recreate on an Android device. However, due to some cross-origin resource sharing (CORS) issues on my server, I had to serve my development environment from a changed hostfile that had a specific subdomain of my project.

With the ability to use a remote Chrome debugger from your desktop to a mobile device, you can use an emulator and still have your full Chrome debugging capabilities. The only problem then, is how to get the host file to match your desktop environment. Following these steps will allow you to do just that!

Pre-Requisites

In order to do this, you’ll need to install a few things first:

During installation, it will ask you if you want to setup an emulator. You’ll want to install all of the related Intel Virtualization packages, as it will greatly increase your speed of the emulator.

  • Download and install the android-platform-tools. This will include adb command directly on your path for you to utilize
    • For macOS, I suggest using the Homebrew package manager and running brew cask install android-platform-tools
    • For Windows, I suggest using the Chocolatey package manager and running choco install adb
    • For Linux, you’ll want to check with your package manager for one of the two above-mentioned package names

Setup Steps

Once you have Android Studio installed, we’ll need to setup an emulator. To do so, open the application:

The opening screen to Android Studio

Then, press “Configure” in the bottom right corner. Then press the “AVD Manager” in the sub-menu.

The sub-menu for configure in the Android Studio startup screen

You’ll see a popup window that will show you the list of virtual devices. These are devices that will be used in order to run an emulator. You may already have a virtual device setup from the initial setup of Android Studio. They include the version of the operating system you use when you boot up the device. While the virtual device that was setup out-of-the-box is fine for most operations, we’ll want to setup an older version of the emulator. This will allow us to change the host file in Android, which requires root (something the default images won’t allow).

Select Create Virtual Device, then select a device type. In my example, I selected Nexus 5, but any device definition of a relatively modern phone should work.

A popup dialog for creating a new virtual device setup

As mentioned before, the default images that are provided will not allow us to replace the host files. In order to do so, we have to download an older Android image (and one that does not include Google Play Store). To do this, I selected the x86_64 Android 7.1.1 (non Google API version) image to download and then selected Next.

The selection of the aforementioned Nougat image

It’s worth noting that we specifically must select a non-Google version, otherwise our future commands will not work (per Google’s restrictions on Google API images).

After this step, proceed to name the Android Device. I’d suggest you name it something without any spaces in order to run a command later that you’ll need to run. In this case, I called the image Nexus5.

My naming of the AVD

Handling the Emulator

Once the AVD is initially setup, open your terminal, and find your installation path of Android Studio.

  • For MacOS, this should be under ~/Library/Android/sdk
  • For Windows, this should be C:\Users<username>\AppData\Local\Android\sdk

Once in that path, you want to run a specific emulator command:

./emulator/emulator -writable-system -netdelay none -netspeed full -avd <AVDName>

For example, given that I’m on macOS and my AVD name is Nexus5, I ran:

~/Library/Android/sdk/emulator/emulator -writable-system -netdelay none -netspeed full -avd Nexus5

This will start the emulator under specific pretenses. These pretenses will allow you to write to any file on your OS, including the host file.

A screenshot of the above command running and the emulator started

Once you’re done with running the emulator, open a new tab and run the following commands (in a folder you want to have the host file within):

  • adb root
  • adb remount
  • adb pull /system/etc/hosts

A screenshot of the above commands running

Upon running these commands, you’ll find a hosts file. This file is the file that tells your OS what path a given domain has. You can, for example, map example.com to go to a specific IP address, similar to how DNS works for most domains.

Inside the emulator, the IP address 10.0.2.2 refers to the host OS. For example, if you’re running a local server on your Windows/MacOS/Linux machine on localhost:3000, you can access it using 10.0.2.2:3000 from the Android emulator.

Knowing these two things, you can change the host file to make example.com refer to the host by adding the following to the host file:

10.0.2.2 example.com

A screenshot of the host file being edited using micro

Pushing the Changes

Once you’ve made the changes to the host file that you want to have changed, you’ll have to push the host file to the OS of the AVD:

  • adb push ./hosts /etc/hosts
  • adb push ./hosts /etc/system/hosts
  • adb push ./hosts /system/etc/hosts

While only one of these host file locations is needed to replaced, it’s easier to run all three than only run one to see if it worked

A screenshot of the above commands being ran

In order for the changes to the host file to take effect, you’ll have to restart the emulator. In order to do so, you’ll want to press and hold the power button off to the right of the emulator. Then, press “Restart”.

If you close the emulator and re-open it using the command above, it may work, but I’ve found instances where it seems to reset the host file, making you go through the whole process again

A screenshot of the above commands being ran

Seeing the Results

Finally, you’re able to sideload the Chrome APK’s x86 variant in order to load the example codebase.

So, for example, using the above hostfile as an example, we can visit example.com:8000 when running the development mode for the project’s GitHub code, you’re able to see a preview of the Unicorn Utterances website from a different domain.

A screenshot of the above commands being ran

And that’s it! You now know how to modify and update the host file for an emulated Android device. I hope this has helped with your development usage!

Original article source at: https://www.thepolyglotdeveloper.com/

#android #change #host #androidstudio 

How to Change The Host File Of an Android Emulator
Gordon  Matlala

Gordon Matlala

1670585767

5 Killer steps to Change And Innovation

Introduction

ADAPTing Agile development, as the leading Agile speaker and author Mike Cohn describes “how one can iterate toward increased agility by combining a senior-level guiding coalition with multiple action teams.”

To successfully implement a change, senior leadership need to create a sense of urgency in their organization so that employees, lower-level managers and other impacted stakeholders are on board. It will help gain confidence and cooperation of the teams.

Following 5 steps are necessary for ADAPTing to Agile development:

  1. Awareness – That there is always a room for improvement in the current practices.
  2. Desire – To adapt to changes for improvement.
  3. Ability – To work with Agile mindset
  4. Promote – Early success so others can see and follow
  5. Transfer – The Agile implication and impact through put the organisation.

For successful Agile transition, it’s very important the each individual moves through Awareness, Desire and Ability stages. Using the Promote stage of Agile transition, early adopters of Agile can build awareness and desire amongst the late adopters of Agile. Lastly its utmost important to Transfer the implication and impact of Agile to other groups throughout the organisation like Project management office, sales, information technology, operations, hardware development; otherwise the Agile transition will fail inevitably.

Lets go through the wife stages for ADAPTing to Agile development

ADAPTing Agile – Awareness

When it comes to achieving desired results, it’s important to be aware of the current process / practise and that its efficiency can be improved. A change in approach begins with recognizing that the current approach has a room for improvement. However, it can be difficult to embrace that what worked in the past may not work in the present. One of the most common reasons people don’t become aware of the need to change is because they don’t have enough exposure to the big picture. In this Awareness stage, Rather than listing a variety of common project problems, focus on the two or three major problems that reflect the need for change.

Some Tools to Create awareness:

  • Communicate the issue
  • Use metrics to track progress
  • Provide new and different experiences.
  • Focus attention on the most important reasons to change.

ADAPTing Agile – Desire

There needs to be a strong desire to adopt Agile as a way to address the current problems. Not only must we recognize the need for change, but we must also have the desire to change. Many people find it difficult to move from the realization that the current development process isn’t working to the desire to use a different one.

Desire Tools:

  • Communicate There’s a Better Way
  • Create a sense of urgency
  • Build momentum
  • Get the team to use Agile for a test drive
  • Align incentives
  • Focus on addressing fears
  • Helping people let go
  • Don’t discredit the past

ADAPTing Agile – Ability

If you want to be successful, you need to be able to be agile. To be successful with Agile, team members must learn new skills and overcome old ones. Some of the larger challenges that Agile teams will face includes: Learning new technical skills, think and work as an Agile team and delivering working product frequently.

Ability Tools:

  • Coaching and training can help your employees improve their performance.
  • Hold individuals accountable for their actions.
  • Share your information with others.
  • Aim for goals that are reasonable and achievable.

ADAPTing Agile – Promote

Promote by sharing our experiences with Agile, we can help others remember and learn from our successes. By publicizing current successes with Agile, you’ll quickly start creating awareness for the next round of improvements. This stage also help teams maintain Agile behavior by sharing the successes that teams have achieved. Finally, publicizing Agile success help those not directly involved in adopting Agile to become more aware and interested in it.

Promote Tools:

  • Publicize the successes of agile teams and help to get the word out about how agile can help businesses achieve their goals.
  • Organize an Agile safari
  • Attract attention and interest from potential agile adopters.

Transfer

It is impossible for a development team to remain Agile without help from the rest of the company. If the impact of using Agile is not transferred to other departments, the organizational focus from those departments will eventually stall and stifle transition efforts. The rest of the organization must be able to work effectively with Agile.

There are other departments that must also be aware of the effects of Agile on their work. Many groups with an organizational gravity, such as the project management office, sales, information technology, operations, hardware development, and others, contribute to the success of a business. The impact of Agile for long-term success will be important to consider.

Visit Knolway to access more resources.

Original article source at: https://blog.knoldus.com/

#agile #step #change #innovation 

5 Killer steps to Change And Innovation
Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
 

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!


What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Original article source at https://www.freecodecamp.org

#python 

Understanding Arrays in Python

Best 7 Ways Big Data Training Can Change Your Organization

The recent news of the United Arab Emirates making military service mandatory for all Emirati men between the age groups of 18 and 30 years has prompted me to think as to why countries regardless of their economic status ensure that citizens be prepared to defend the country.

 One could argue that limited number of citizens in a country, often force the government to make military service mandatory. But what about China? It’s the largest country by population but it also ensures citizens going for further education serve compulsory military time. In short, nations are basically preparing themselves to defend in the event of conflict and everyone must be prepared for it. Be it an electrician, a businessmen, a carpenter, they all unite for a common cause.

 Bizarre as it may sound, one can draw an uncanny parallel between such nations and today’s organizations that want to stay competitive. The current threat or rather a challenge in the form of Big Data has prompted organizations big and small to bring together its manpower across various departments to commonly address it. To go further on this, typically nations enforcing compulsory military service always have an eligibility criteria, in the same way organizations find it logical in giving big data training only to those employees who have some form of interaction with large chunks of data and are required to employ Hadoop at every touch point.

 Just as an Army General in liaison with the government decides the kind of weaponry and training to be assigned to its otherwise novice citizen-turned-new-recruit, in the same way a CTO is expected to be at the helm of IT infrastructure and legacy systems driving new technology innovation to allow his/her employees perform better. With a shared objective to tackle big data, let us try to understand in detail where big data is used and why is it important to train your comrades in it.

1.Information Technology: Improving productivity with Big Data Training 

Perhaps at the forefront of big data implementation, the IT team is the epicenter for taking the change forward. An IT training decision maker who wishes to bring big data training to the employees has to begin with the IT department. Why? Because when it comes to engagement with technology at every stage of activity, the geeks at the basement (popular slang for IT) are the closest. So how relevant is it?

Let us look at a report submitted by the popular site, CIO, which states:

“According to a recent CompTIA survey of 500 US business and IT executives, 50 percent of firms that are ahead of the curve in leveraging data, and 71 percent of firms that are average or lagging in leveraging data, feel that their staff are moderately or significantly deficient in data management and analysis skills”

Given the fact that data management and storage is a part of the core function of IT, there is a need to have a parallel approach towards big data platform implementation and strengthening the IT skills within big data. Supporting the fact is a McKinsey report stating that by 2018, there will be a shortage of over 140,000-190,0000 professionals with deep technical and analytical expertise! As more and more technical professionals require big data training, organizations are looking to train technical professionals more for quick ROI and platform specialists, admin and engineers working in the IT department are at the helm of it.

Marrying Trinity of Core IT Function with Big Data

The term Trinity often reminds me of two religious concepts: One is the Hindu mythology of the creator, preserver and destroyer and the other is the Christian concept of the father, son and the holy ghost. Both strive for the betterment of mankind. In the same way, these three functions of an IT team strive for the betterment of the entire organization with departments with different needs when it comes to information technology. Apart from security and support functions, an IT department can relate to these functions when it comes to big data implementation.

Planning- The Planning activity within an IT team focuses on ensuring the organization’s IT strategy is aligned with the business objectives. This includes working on customizing software, bringing in new platforms that meet the needs of different business departments. In other words, any new implementation will always start from IT.

Network- It involves developing networks that facilitate all forms of communication between voice, data, video and Internet traffic and there are various checkpoints for recording data be it customer interaction, sentiment analysis and traffic update, they all collect data real time! An IT department often ensures smooth integration of networks to work along with objective of processing big data.

Data- To put it simply, an IT team brings in tools to collect, store, manage, secure and distribute data to employees for various strategic decisions in the organization. All forms of data like sales record, financial records, stock details are stored in a single data center. This creates a responsibility within the IT team to implement platforms for big data that allow designated users to store and retrieve information at any data location.

In any IT team, one needs a versatile mix of members with different tasks towards big data implementation. To begin with there is a need for a specialist who ensures smooth transitioning from traditional systems to big data platforms. For that one requires a techie to focus on maintaining the platform in its entire life cycle across all departments. Then comes a need for a member who must constantly monitor whether every technological implementation is aligned with the organizational objective.

2.Product Development: Rethinking innovation across all stages of R&D

Big Data Training, Product Development, Engineering

Perhaps one of the most important departments when it comes to taking the organization into the next level of innovation! One of the biggest advantages of big data is integration of data across different touch points in product development right from product design, manufacturing, quality, warranty, diagnostics, vehicle and software applications. The data generated from these touch points defines the way the product is and how successful it can be. This basically takes product developers, R&D professionals and designers to the data-driven and data-analysis approach.

Engineering Big Data into reality

When it comes to product development, one popular example would be the driver less car that Audi is developing and planning to launch by 2016. Yes, there is the product development team that has the huge task of making sure the CEO’s vision of innovation is accomplished. But along the way, there are various challenges and questions right from development to testing that only big data can answer. Let us see why.

Consider a test-ride being monitored from point A to point B. Here are the kinds of data that can be generated:

a. Sensor Data – The sensors within the car could store details about the distance it had measured between cars behind it and in front of it and the frequency of vehicles it encountered in the journey.

b. Driver Data – Multiple tests with different age groups could be carried out and the details of comfort level, performance and how many times the driver needed to override automatic driving will be compressed into large sets of rows and columns for analysis.

c. Demographic Data – A test might be carried out in India and in the US. The A.I within the automatic driving could analyze the obstructions that it encounters in driving in two different countries. Which country is more viable for automatic driving and which county is not?

d. Market Performance Data – After the product is launched and it is on the road, engineers could also monitor its success by analyzing live data with feeds being provided 24×7 by the car’s program giving insights if the the introduction of automatic driving is helping in keeping the road’s safer?

There are N number of possible data that can be churned out from product engineering. We are just beginning to explore OEM from the auto-industry. Think about the possibilities of big data across various sectors say medicine, health care, electronics and so on. Who knows?

FUN FACT: Did you know that Ford’s adopting of Big Data and Analytics saved it from a near-death experience in the 2000s when competition was stiff from European and Asian Auto-makers!

3.Finance: Training employees on big data platforms to handle financial modelling 

Financial Forecasting, Big Data, Finance Analytics

We might have often heard the term that money is the blood of business. Taking care of that money is a responsibility of the finance department. The business world defines the functions of the finance department as typically being involved in ‘planning, organizing, auditing, accounting and controlling its company’s finances along with producing the company’s finances.

Having said that finance department in general is often the brainchild when it comes to handling money and the role expands to various activities like generating cash flow statements, cost modelling, prize realization and compliance to name a few. A few decades ago performing all these activities with limited systems and platforms was quite feasible, but in the age of big data the two challenges every finance department face is performing regular finance functions in the changing scenario and gathering insights for the future. Let us look at it from a deeper perspective.

With the information spread across different servers, organizations often encounter the challenge of consolidating that data and perform actions as per business requirements. An important function within is internal auditing that keeps a tab on organization’s governance, risk management and management controls and conducting proactive fraud audits to identify fraudulent acts. With the rise of analytics, there is a need to integrate internal auditing as well. This has sparked new methods like audit data analytics which help assess the risk, create financial models and give an overall picture of finance within an organization.

Cost Modelling & Price Realization

 Cost modelling is an important component for effective utilization of resources. Companies must identify the activities that drive costs, the total direct materials and labor needed for task completion and so on. Cost modelling helps companies to accurately identify the overall production costs to products across all activities within the company. In the age of big data it becomes important to keep a track of every financial activity taking place at different departments within an organization that consolidates that information to build an ideal cost model. From purchase to sale, all data gets stored in finance history and the fundamental basics of developing a cost model is to fetch the large chunks of data and create a model that can apply for the future.

 Although one can debate that Price Realization efforts are directed more towards sales to improve profitability, there is a greater role played by the finance department when it comes to benefiting from price realization. To break it down to simpler terms, consider a retail outlet that plans to provide discounts to push sales. The fundamental objective is to reduce price leakage and improve pocket price.

Price leakage occurs when the price of a product is discounted so less (in a bid to make sales) that they compromise on profitability and pocket price is the selling price post discounts. To fulfill a profitable price realization effort, the sales team collaborates with the finance department to understand the structure of costs for each individual products and where discounts can be given. This in turn requires the finance department to develop a framework for price realization models for the future and define the limits within such marketing activities. The task includes processing data from procurement, warehouse cost, shelf life and then estimating the cost of goods sold (CGS).

 F-12 & Predictive Analytics

One of the important activities within financial department is to monitor the financial health of the organization. Just as a doctor uses different metrics such as pulse rate, body warmth or stimuli reaction to judge whether the patient is alive or dead, in the same way the financial world monitors the 12 metrics to know where the company is headed monetarily and what lies beyond. From Real Revenue Growth, Sustainable Revenue Growth, Pricing Policy and Pricing Index, Operating Expense Control, Comparing EBITDA versus Cash Flow, Debt Free Cash Flow, Excess Cash, Return on Assets, Working Capital, Use of Debt Financing, Net Trade Cycle and Cost of Capital form important components in financial reporting for an organization so that the upper management can take sound decision.

As a part of the challenge in the big data world, understanding these ratios requires processing large chunks of information spread across the organization to make it in a standard format for analysis. Predictive analytics comes into play when this data is processed from past history, compared with the same elements in the present such that accurate estimations are made for the future. The best part is predictive analytics platform and methods are built to process big data thereby simplifying the finance department’s task.

 FUN FACT: Did you know that the Oversea-Banking Corporation (OCBC) based in Singapore was able to use big data for customer insights which was directly responsible for 40% increase in acquiring new customer!

4.Human Resources: Redefining HR employee capabilities

HR Analytics, Attrition, Recruitment, Big Data, Performance Analysis

Imagining Big Data in Human Resources may often urge readers to dismiss as a humbug, since an organization typically doesn’t prioritize much in implementing Big Data technology in the HR department as it would rather focus on Marketing, Operation or Finance. But in reality, the Human resources department plays a crucial role in making sure that the right talent enters the organization among other activities.

Adding more teeth to the HR

Perhaps the most ignored among all departments when it comes to Big data implementation, but in today’s fast changing world, the way that an HR department works defines the success of an organization.

According to Forbes, an average large company has more than 10 different HR applications and their core HR system is over 6 years old. This trend highlights the fact that an organization needs the correct resources to bring this data together. Training in Big Data & Analytics brings skills like data analysis, visualization and problem solving right from operational reporting to strategic analytics.

An HR department by default is expected to deliver in terms of basic HR operations, but Big Data training takes it to a whole new level. As the HR department becomes more analytical with tools, it changes their approach to engage in more strategic activity. Critical question like how to have more employee retention; factors affecting sales; quality of candidate pipeline and evaluating talent gaps is identified and strategic steps are taken through analyzing relevant data through it.

The shift will move from simple headcount to more predictive analysis.

The Oracle within Human Resources

There was a funny story that I recall of a friend who worked as an HR. She had an exhausting job of headhunting before sending the candidate to the relevant department head who would only say the magic words: “Ok, lets hire him.”

For a while, things did go well as she brought in good talent to the company. As time passed, she grew confident in her hiring skills to the extend of pushing the upper management to add more people to her team, implementing HR systems and including more third party consultancies. The tricky part was she made tall promises to the upper management with her confidence.

History has shown that the one who prepares for future event is more successful than the one riding on past glory. There was a time when she was expected to hire a large number of professionals in the domain the company was expanding in. She began filling vacancies with a compromise on hiring quality professionals. She adopted a more target-driven approach. The result? Most of the professionals she hired put down papers citing various reasons and she was questioned by the management. Often I would hear her mumble:

“I head-hunt 1000 Cvs, shortlist 100 Cvs, call 50 candidates for interview, filter 10 from my psychometric assessments, among the 10, I take 5 who are worth it, send the 5 to the management, they zero in on 1 and that one guy leaves after 2 months.”

I did chuckle at her misery apart from offering my sympathies, but it made me wonder whether human resources can make better judgment with their experience or is there a need to have a more data-driven approach to this whole hiring process? Well, we do use predictive analysis from finding which team is going to win the world cup but why not use the same techniques in the hiring process, especially when we are dealing with complex elements such as human beings?

 Now, the job of hiring is not necessarily an easy job, it involves a lot of processes and the rules of hiring often change according to the industry the HR is in; the role she is hiring for; the rules of the organization and so on.

If one observes successful organizations that use predictive analytics and have lesser attrition rates, there is a pattern of first deciding on the desired characteristics within a candidate that ensure success, consolidating it into an ‘ideal’ profile and comparing it to every candidate who is closest to it and then engaging them with customized assessments that evaluate the characteristics of these candidates.

A point to note is that the whole psychometric assessment industry with leading players such as Pearsons, Thomas Assessment & SHL sprung up due to the demand from HR professionals for analyzing candidate profile in their need to perfect hiring process!

Getting back to predictive analytics, as a part of implementing it, the HR personnel must first define who is a ‘successful candidate’ according to the organization, then she/he must define the factors that can drive effectiveness of hiring and develop and observe as to why some hires do better than the others with a hypothesis if need be. Based on that, she/he can compare it with the data of successful employees who have stayed long with the organization and thirdly use statistical techniques to measure why some people stay longer.

The approach is good for a start, but implementing predictive analytics within HR includes a lot of techniques that an HR is free to explore. The best part of this process is the reduction in the cost of replacing an employee with new ones and perhaps gaining more ROI than the old one.

At the end of the day, the combination of intuition, experience and a sound data-driven approach often refines not only an HR’s judgment but ours as well.

FUN FACT: Did you know that American giant Xerox reduced its call center turnover by 20% by applying analytics to prospective candidates with the finding that creative people were more likely to remain with the company for the 6 months necessary to recoup the $6,000 cost of their training than inquisitive people?

5.Supply Chain & Logistics: Training delivery team with big data platforms

Supply Chain & Logistics, Big Data training

Supply Chain & Logistics basically form an important component in organizational strategies and goals. The objective for Supply Chain & Logistics is in saving costs and improving performance, speed and agility. When it comes to logistics, they capture and track different forms of data to fundamentally improve operational efficiency, improving customer experience and new business models. These factors can often help organizations to conserve resources, build a better brand name and create a systematic process for supply chain & logistics.

Tracking Big Data across the world

Let us take an example of a e-commerce giant which uses Big Data for delivery to its customers. A product is dispatched from a location to the address of the customer. Devices within the transport vehicle such as GPS tracker, mic, sensor has structured and unstructured data that are sent back to the monitoring center for real-time updates. Along with that it also helps analyze the efficiency of delivery time, shortest path and the resources used to perform one delivery operation in the list of millions of such transactions. This gold-mine of data across different markets is consolidated by the organizations and then analyzed to bring further improvement in the process or bring a whole level of new innovation!

FUN FACT : Did you know that Big data in the form of tracking customer pages by Amazon has helped it to position its products to the warehouse nearest to customer in order to improve delivery speed and efficiency?

6.Operations, Support & Customer service: Employee training on big data at every customer interaction

Operation, Customer Support, Big Data, Customer experience,training,Customer Interaction

The success of any product or service is based on the after-sale support that a customer receives and often the vendor takes an oath to be there for him/her at all times. This comes from the fact that when a customer takes a product or a service, he makes a ‘leap-of-faith’ in the hope that the vendor doesn’t let him/her down in the lifespan of the product/service. Delivering from this perspective is critical for organizational success.

Let us look at support at a granular level. I recently had the opportunity to watch Christopher Nolan’s ‘Interstellar’ that explored space travel to the end of space. This got me into thinking about future airlines that will offer flight services through worm-holes spanning millions of light years away! What would be the challenges then? What kind of big data is going to be generated in this almost never-ending journey? How will the on board team ensure that the passenger enjoys the ride throughout? To begin with, the service provider must focus on primary objectives like ensuring air-safety, keeping track of its flight path, delivering customer requirements and so on.

On-the-go Big Data 24×7

The idea for interstellar travel might be a distant dream for the next 100 years (being optimistic!), but it doesn’t stop us from looking at the data being generated by a similar service currently operational now which will shed more light on how customer service & support is carried out in the ‘after-sale’ scenario and how organizations can engage in improving their efforts in real-time.

Now to begin with, Southwest Airlines is one of the most celebrated airlines that took advantage of Big data in order to improve its customer experience. In its bid to improve air safety, Southwest Airlines collaborated with NASA to engage in big-data experiment for improving overall flight experience. This includes pinging NASA satellites with information on flight path, reports from pilots and other air traffic information. At the pinnacle of such innovative technique, there lies the basic big data concept called ‘text data-mining’ which converts unstructured textual information into meaningful text for insights. So you thought text data-mining ends there?

Of course it doesn’t, even a simple concept in big data such as text data-mining extends way beyond that. We all know that customer feedback is an important component in understanding where an organization goes wrong at every point of customer interaction. Text data-mining also helps customer-service by analyzing open-ended survey responses. Instead of constraining customers to common options like option A, option B, option C, open-ended questions provide more insights, but classifying them and recording the responses may be a key issue. That is where text data-mining comes into play where it groups certain set of words and consolidates them for insights!

Looking beyond that, we all must admit that no organization is perfect and that every one of them has a small set of customers who may not be happy with the service. The result? A database flooded with email, messages, tweets from customers registering complaints or ‘areas-of-improvement’ tips to put it rather softly. Text data mining goes a step ahead from traditional mail filters and can classify mails as per the priority and reroute it to the department in question.

FUN FACT : Did you know that Southwest Airlines, as part of its effort to improve customer services has deployed data analysis with the feature called ‘speech-analysis’ that records interaction between customer and personnel for insights!

7.Marketing: Training employees on a systematic marketing approach with big data

Marketing Analytics, Digital Marketing, Brand Management, Big Data, Online Marketing

Marketing as an activity is all about numbers today. With the surge of digital marketing, we can now accurately measure the response of ads, click-through-rate, impressions, ROI and so on. For a non-marketing professionals, such metrics maybe greek, but for those in marketing this data is a gold-mine. Subsequently, along with metrics, large chunks of data is generated across at every point of customer interaction, social media & sales. It is up to the marketing professional to keep track of such data and use it to push one’s products more effectively. Training in Big Data plays an essential role here since platforms like Hadoop & R help serve the purpose.

Secondly, time-to-time marketing professionals often indulge into retrospection for their brand. Questions like :

How is my brand better than others?

What do other brands offer?

What features does my competitor have on the same product?

The study goes much deeper than this. From analyzing competitor product based on the 4Ps (Product, Price, Place, Positioning) to understanding content of which product presented in the competitor’s webpage, the amount of data generated is huge and complicated. As told before, taking advantage of text-mining can help the marketer perform competitor-analysis by simply crawling the competitor’s website. This simple function in the domain of big data can give a consolidated idea about what the competitor is doing and what products they have in place for the market, thereby giving the marketer who embraced big data an edge!

Arming the Creative

For example a social media strategist wants to know about the brand perception of his organization across social media platforms, then probably engaging in sentiment analysis in R & Hadoop will help achieve this goal. In the same way, use of Big Data tools helps marketing at various activities such as pricing, product positioning and so on.

Another example could be a marketing manager at a retail outlet looking to maximize sales. Everyone would know the example of Walmart which was able to position beer and milk side-by-side in the aisle based on past customer purchase history by retrieving large chunks of data spanning millions of customers over a timeframe!

FUN FACT: Did you know that General Motors with its yearly marketing budget of $2 Billion per year used Big Data Analytics to create detailed customer profiles and combine spatial data analytics with detailed demographics/customer information for more personalized marketing!

Why companies are shifting to Big Data platforms

Typically, organizations using old legacy systems have data spread across many systems. Due to spread of data at different locations, the processing speed goes down along with accuracy of analyzing data. This calls for consolidating data within an enterprise data hub which creates a faster access of data resulting in deeper analytics. One of the important objective of the IT department in any organization is to provide accurate data swiftly for all departments in the organization upon request.

With data being collected, it is important to unify unstructured, structured and semi-structured data sources onto one platform to perform in depth analysis and basically aid business decision making. This feature of Hadoop brings in more people to the table within the organization since there are employees who interact with data at different touch points in day-to-day operations. Also, traditional ETL and batch processes can take a long time, whereas Hadoop with its high volume batch processing speeds it up to 10 times.

The significance of Hadoop doesn’t necessarily mean that every employee within an organization needs to be trained in the Big Data platform which may not be feasible in most cases. But it would be of strategic advantage for a CTO to identify and train those professionals who are in constant interaction with data.

Having covered the storage, processing, retrieval of data through the popular Hadoop platform, another important phenomenon that is a part of the natural progression is the Big Data analytics. To put it simpler, organizations needs multiple perspective from various professionals within an organizations.

The number ‘6’ can be viewed as the number ‘9’ from the other side of the table. In other words, conclusion from observing data differs from person to person.

Organizations know this and often engage in training employees in similar platform so that people from different departments interconnected by the same activity discuss, engage and share insights for sound decision making. So, I believe it would be safe to define Big Data training as an opportunity for every employee to be on the same page and take organizations to the next level!

Got a question for us? Mention them in the comments section and we will get back to you. 

Related Posts:

Get started with Big Data and Hadoop

Original article source at: https://www.edureka.co/

#bigdata #organization #change 

Best 7 Ways Big Data Training Can Change Your Organization
Hunter  Krajcik

Hunter Krajcik

1669384742

How to Change Text on HTML Pages using JavaScript

JavaScript - how to change text on HTML pages

This guide will show you how to change text on pages using JavaScript

The easiest way to change the text content of HTML pages is to manipulate the textContent property of the specific element using JavaScript.

First, you need to select the element you want to change the text. It may be a <span>, a <div>, a <p> or any other tag. All HTML elements have the textContent property from which you can set the text for that element.

For example, suppose you have the following HTML page:

<body>
  <h1 id="header">Hello, World!</h1>
  <p id="content">It's a very good weather we are having today.</p>
</body>

Here’s how to change the text inside the <h1> element into “Greetings from Mark”:

First, you need to select the element <h1> using JavaScript’s element selector. The browser provides you with 4 methods to select an HTML element:

  • getElementById() - fetch a single element with matching id attribute
  • getElementsByClassName() - fetch the elements with matching class attribute
  • getElementsByName() - fetch the elements with matching name attribute
  • getElementsByTagName() - fetch the elements with matching tag name like "li" for <li>, "body" for <body>

The most recommended approach is to use getElementById() method because it’s the most specific of these methods.

Out of the four methods, only getElementById() will retrieve a single element as an object. The other methods will fetch the elements as an array even when the page has only one matching element.

Since the <h1> tag above already has an id attribute, you can use that to get the element as follows:

const header = document.getElementById("header");

If your element doesn’t have an id attribute, then you can add it first. Please make sure that no two elements or more have the same id attribute value. JavaScript will return only the first element it found if you do.

Next, you just need to replace the textContent property as in the code below:

header.textContent = "Greetings from Mark";

And just like that, you’ll have the text inside the <h1> tag changed.

Keep in mind that the textContent property is used only to change the text inside the element. If you add an HTML tag inside the text, it will be displayed on the page literally.

For example, suppose you want to add an italic styled text with <i> tag. You may try to add it like this:

header.textContent = "<i>Greetings from Mark</i>";

What would happen is the text "<i>Greetings from Mark</i>" will be displayed on the HTML page.

To properly add HTML tags to your new text, you need to use the innerHTML property instead of the textContent property. Here’s an example:

header.innerHTML = "<i>Greetings from Mark</i>";

Now the <h1> tag content will be styled properly.

The innerHTML property allows you to set the HTML content of the element, not just plain text as in textContent property. Feel free to use the method that meets your need 😉

You can use the same methods to change other HTML elements like a <div>, a <span>, or a <p> tag.

Original article source at: https://sebhastian.com/

#javascript #change #text

How to Change Text on HTML Pages using JavaScript

How to Change The Class Attribute Value Of an HTML Element using JS

Change the class value of an HTML element using JavaScript

To change an HTML element’s class attribute value using JavaScript, you can use either the className or the classList property provided for every single HTML element.

This tutorial will help you learn how to use both methods, starting from the className property.

Change the class value using className property

The className property allows you to fetch an HTML element’s class attribute value as a string.

Here’s an example of how className property works:

<body>
  <p id="header" class="red">Hello World! This is a paragraph element.</p>
  <script>
    const paragraph = document.getElementById("header");
    console.log(paragraph.className); // "red"
  </script>
</body>

Now that you know how the className property works, you can change the class value of an element by assigning a new value to the property as follows:

<body>
  <p id="header" class="red">Hello World! This is a paragraph element.</p>
  <script>
    const paragraph = document.getElementById("header");
    paragraph.className = "yellow blue";
    console.log(paragraph.className); // "yellow blue"
  </script>
</body>

Using the className property allows you to change the class attribute value, but you need to add the previous value manually if you want to keep it.

For example, to keep the class "red" from the <p> element above and adds a new class named "font-large", you need to assign both classes as follows:

const paragraph = document.getElementById("header");
paragraph.className = "red font-large";

Even though the "red" class is already present, you still need to assign it again, creating a small redundancy in your code.

To avoid this kind of redundancy, you can use the classList property instead.

Change the class value using classList property

The classList property is a read-only property of an HTML element that returns the class attribute value as an array. The property also provides several methods for you to manipulate the class attribute value.

For example, to add new class names without removing the current value, you can use the classList.add() method.

Using the same <p> element example above, here’s how to add the "font-large" class without removing the "red" element:

<body>
  <p id="header" class="red">Hello World! This is a paragraph element.</p>
  <script>
    const paragraph = document.getElementById("header");
    paragraph.classList.add("font-large");
    console.log(paragraph.classList); // ["red", "font-large"]
  </script>
</body>

When you want to remove an element’s class attribute value, you can use the remove() method, which allows you to remove() class names as a comma-delimited string:

<body>
  <p id="header" class="red">Hello World! This is a paragraph element.</p>
  <script>
    const paragraph = document.getElementById("header");
    paragraph.classList.add("font-large");
    paragraph.classList.remove("red");
    console.log(paragraph.classList); // ["font-large"]
  </script>
</body>

For more information on classList property you can read the following post:

JavaScript classList() property and methods explained

And that’s how you can change the class attribute value using the className or classList property methods.

Original article source at: https://sebhastian.com/

#javascript #change #class 

How to Change The Class Attribute Value Of an HTML Element using JS