Ошибка syntax error unexpected identifier expecting end of file

This is a sample program I am doing for my COBOL class and I had a few questions about an error code I am getting when I tried to compile through the command line. Please see below. Below the COBOL will be my terminal code. How can I fix the «unexpected indentifier?»

       IDENTIFICATION DIVISION.
   PROGRAM-ID.      SAMPLE135.
   AUTHOR.          ME.

   ENVIRONMENT DIVISION.


   DATA DIVISION.
   77 FIELD-A PIC 9(2).
   77 FIELD-B PIC 9(2).
   77 FIELD-C PIC 9(3) VALUE ZERO.
   77 FIELD-D PIC 9(3) VALUE ZERO.

   WORKING-STORAGE SECTION.

   PROCEDURE DIVISION.
   FIRST-PARAGRAPH.
       MOVE ZEROS TO FIELD-A FIELD-B.
       PERFORM SECOND-PARAGRAPH.
       PERFORM THIRD-PARAGRAPH.
       PERFORM SECOND-PARAGRAPH.
       PERFORM WRITE-DATA.
       STOP RUN.      

   SECOND-PARAGRAPH.
       ADD 10 TO FIELD-A.
       ADD 20 TO FIELD-B.

   THIRD-PARAGRAPH.
       MULTIPLY FIELD-A BY FIELD-B GIVING FIELD-C.
       DIVIDE FIELD-A INTO FIELD-B GIVING FIELD-D.

   WRITE-DATA.
       DISPLAY FIELD-A.
       DISPLAY FIELD-B.
       DISPLAY FIELD-C.
       DISPLAY FIELD-D.

   END PROGRAM.



Sample2.cbl:9: Error: syntax error, unexpected "Identifier", expecting "end of file"

Ken White's user avatar

Ken White

123k14 gold badges224 silver badges441 bronze badges

asked Sep 16, 2016 at 0:48

You have the ’77’ data items in the wrong place,also indent. Also make sure that the Field names start in area B (unless using free format). try

DATA DIVISION.

WORKING-STORAGE SECTION.
   77  FIELD-A          PIC 9(2).
   77  FIELD-B          PIC 9(2).
   77  FIELD-C          PIC 9(3) VALUE ZERO.
   77  FIELD-D          PIC 9(3) VALUE ZERO.

In Cobol code it is generally considered better to only use ‘.’ when they are absolutely needed (before procedures) i.e

SECOND-PARAGRAPH.
    ADD 10              TO FIELD-A
    ADD 20              TO FIELD-B

    .
THIRD-PARAGRAPH.

Finally it is also standard practice indent TO and PIC statements
as I have

answered Sep 16, 2016 at 1:10

Bruce Martin's user avatar

Bruce MartinBruce Martin

10.4k1 gold badge27 silver badges37 bronze badges

0

The WORKING-STORAGE SECTION header must come before the 77-level definitions.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       77 FIELD-A PIC 9(2).
       77 FIELD-B PIC 9(2).
       77 FIELD-C PIC 9(3) VALUE ZERO.
       77 FIELD-D PIC 9(3) VALUE ZERO.

You’re also missing the program name in the end marker.

       END PROGRAM SAMPLE135.

answered Sep 16, 2016 at 17:23

Edward H's user avatar

Edward HEdward H

5763 silver badges8 bronze badges

1

You are running a Bash script, and you see a syntax error: Unexpected end of file.

What does it mean?

This can happen if you create your script using Windows.

Why?

Because Windows uses a combination of two characters, Carriage Return and Line Feed, as line break in text files (also known as CRLF).

On the other side Unix (or Linux) only use the Line Feed character as line break.

So, let’s see what happens if we save a script using Windows and then we execute it in Linux.

Using the Windows notepad I have created a Bash script called end_of_file.sh:

#/bin/bash

if [ $# -gt 0 ]; then
  echo "More than one argument passed"
else
  echo "No arguments passed"
fi

And here is the output I get when I execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh 
./end_of_file.sh: line 2: $'r': command not found
./end_of_file.sh: line 8: syntax error: unexpected end of file 

How do we see where the problem is?

Edit the script with the vim editor using the -b flag that runs the editor in binary mode:

[ec2-user@localhost scripts]$ vim -b end_of_file.sh

(Below you can see the content of the script)

#/bin/bash^M
^M
if [ $# -gt 0 ]; then^M
  echo "More than one argument passed"^M
else^M
  echo "No arguments passed"^M
fi^M

At the end of each line we see the ^M character. What is that?

It’s the carriage return we have mentioned before. Used by Windows but not by Unix (Linux) in line breaks.

To solve both errors we need to convert our script into a format that Linux understands.

The most common tool to do that is called dos2unix.

If dos2unix is not present on your system you can use the package manager of your distribution to install it.

For instance, on my server I can use YUM (Yellowdog Updater Modified).

To search for the package I use the yum search command:

[root@localhost ~]$ yum search dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
====================== N/S matched: dos2unix =====================================
dos2unix.x86_64 : Text file format converters

And then the yum install command to install it:

[root@localhost ~]$ yum install dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                   | 2.4 kB  00:00:00
amzn2extra-docker                                            | 1.8 kB  00:00:00     
Resolving Dependencies
--> Running transaction check
---> Package dos2unix.x86_64 0:6.0.3-7.amzn2.0.2 will be installed
--> Finished Dependency Resolution 

Dependencies Resolved 

==================================================================================
  Package       Arch        Version            Repository            Size
==================================================================================
 Installing:
  dos2unix      x86_64      6.0.3-7.amzn2.0.2  amzn2-core            75 k
 
 Transaction Summary
==================================================================================
 Install  1 Package

 Total download size: 75 k
 Installed size: 194 k
 Is this ok [y/d/N]: y
 Downloading packages:
 dos2unix-6.0.3-7.amzn2.0.2.x86_64.rpm                      |  75 kB  00:00:00     
 Running transaction check
 Running transaction test
 Transaction test succeeded
 Running transaction
   Installing : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 
   Verifying  : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 

 Installed:
   dos2unix.x86_64 0:6.0.3-7.amzn2.0.2                                                                                                                         
 Complete! 

We are ready to convert our script using dos2unix!

[ec2-user@localhost scripts]$ dos2unix end_of_file.sh 
dos2unix: converting file end_of_file.sh to Unix format ... 

And now it’s time to execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh  No arguments passed

It works!

If you are interested I have written an article that explains the basics of Bash script arguments.

Conclusion

I have found myself having to use the dos2unix command several times over the years.

And now you know what to do if you see the syntax error “Unexpected end of file” while running a Bash script 🙂


Related FREE Course: Decipher Bash Scripting

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

If you’ve ever updated a plugin or pasted code into your WordPress website, chances are you’ve problem seen the parse error syntax error unexpected end in WordPress message. This is a common error because it only takes one character to cause it. In this article, we’ll explore what causes this error and see how to fix it.

What Does Parse Error: Syntax Error, Unexpected End in WordPress Mean?

Parse error syntax error unexpected end in WordPress can be the simplest of errors and still cause a big problem.

The error has two parts:

Syntax Error – This error is caused by an error in the PHP structure when a character is missing or added that shouldn’t be there.

Unexpected – This means the code is missing a character and PHP reaches the end of the file without finding what it’s looking for. The error will include information at the end that explains what it saw that was unexpected.

If you see Parse Error: Syntax Error, Unexpected end in WordPress, it just means that WordPress detected that something in the code is missing or added. It can be something as simple as a comma, semi-colon, a closing parenthesis, or one too many brackets.

The missing syntax can be within code that you’ve written or pasted into your website, or within a theme or plugin that you’ve installed or updated.

Fortunately, it’s not that difficult to find and fix. However, you will need to understand how code works and how to edit it.

How to Solve Parse Error: Syntax Error Unexpected End in WordPress

How to Solve Parse Error

The actual parse error syntax error unexpected end in WordPress will have a different ending depending on what’s causing the error.

Examples include:

  • 1) syntax error, unexpected end of file
  • 2) syntax error, unexpected token
  • 3) syntax error, unexpected variable
  • 4) syntax error, unexpected identifier

The error message will usually identify the specific token, variable, identifier, etc., that it doesn’t like. We’ll see a few examples of this as we go.

Testing the Parse Error Syntax Error Unexpected End in WordPress

WordPress has made lots of improvements in how it handles code. Now, instead of running bad code and killing your website, if it has a previous version of the code that ran, it tries to use that code instead when displaying the site to visitors.

This keeps your site from displaying the error to your visitors and keeps you from being locked out. It is still possible for your site to go down and lock you out, but it’s more difficult now.

Also, the code editors now show markup, so it’s easy to identify variables and other code elements. This makes it easier to test code within the plugin and theme code editors within WordPress.

Unfortunately, WordPress doesn’t always give you a clear message. Sometimes there is no message, content is missing, or it just doesn’t show the website. All of these can be fixed, but they might take a little more troubleshooting.

Let’s look at a few examples. We’ll start with something easy.

Editing Plugin Code

Editing Plugin Code

First, start with what you did last. In this example, I’ve edited code in a plugin file. The file reverted to the last known good code, so my changes are not working. Look at the error. It will tell you what’s causing the error code and the line of code with the error.

In this example, WordPress is seeing an unexpected bracket when it’s expecting to see a semi-colon.

This one is simple. First, look at the line above it. We see the word break, ending case 4. We’re fortunate in that we have other cases to compare to. Above it is case 3, which also ends with break, but this one has a closing semi-colon.

Editing Plugin Code

Next, edit the code that caused the error.

Editing Plugin Code

Here’s another example in the same plugin file. This one is showing the error on line 488. However, that line of code is correct. It’s giving me a clue, though. It’s identifying this as an unexpected variable.

Editing Plugin Code

If we look at the code above 488, we see that it’s missing a closing bracket. This causes WordPress to see the next line incorrectly.

Editing Plugin Code

Simply add the closing bracket and update the file. The code now works correctly.

These problems were simple, but most of the time you see a parse error syntax error unexpected end in WordPress, it’s exactly like these examples.

Fixing the Parse Error When You Can’t Find the Error

There are two ways to find the parse error if it doesn’t display for you or you’re not sure where it’s coming from. Here’s a look at both methods.

Debug Mode

The first step is to enable the WordPress error log. Go to your wp-config file using FTP or cPanel. Search for a line of code that looks like this:

define( 'WP_DEBUG', false );

If you have this code, change false to true.

If you don’t have this line of code, look for a line that says:

“Stop editing! Happy blogging.” and paste this code:

define( 'WP_DEBUG', true );

Load the website. This will display the error and you now have a place to start troubleshooting.

Debugging Plugin

Query Monitor

Query Monitor is one of the most popular debugging plugins. It provides tools that you can access from the frontend and backend from the top menu bar and as an overlay.

Query Monitor

This will enable several debugging tools including an error log where you can find the information you need.

Fixing the Parse Error if You’re Locked Out of WordPress

Fixing the Parse Error if You’re Locked Out of WordPress

If you’re locked out of the admin dashboard, you’ll need to make your changes another way. You’ll need to download the file from the server that contains the error and open it in a code editor to make your edits.

In my case, I was making changes in the functions.php file for the Twenty Twenty One theme. I made an error in my syntax and my site went down. All it shows is this error that doesn’t help.

Fixing the Parse Error if You’re Locked Out of WordPress

The best options are to use FTP or your host’s cPanel. I’ll use cPanel for this example, but the process is the same. First, open File Manager in cPanel.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, open the folder for the website you’re working on. If it’s the primary site, you might see a globe icon. Otherwise, open the folder with the name of the website.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the wp-content folder.

Fixing the Parse Error if You’re Locked Out of WordPress

Navigate to the folder with the theme or plugin you want to edit. In this case, I’m editing a theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Select the folder of the theme or plugin. I’m selecting the folder for the Twenty Twenty One theme.

Fixing the Parse Error if You’re Locked Out of WordPress

Next, go to the file you were editing when the problem occurred. I was editing the functions.php file. Either download the file to work offline or edit the file. I recommend downloading a backup before making changes.

Fixing the Parse Error if You’re Locked Out of WordPress

Your code editor might provide information about the error. In my case, it’s showing that it’s expecting a parenthesis on line 29. In reality, it’s missing a bracket on line 17, which causes the editor to think it needs a parenthesis.

Fixing the Parse Error if You’re Locked Out of WordPress

Adding the bracket removes the error. I can now upload my new file to replace the current file or save it if I’m using the online editor.

Fixing the Parse Error if You’re Locked Out of WordPress

My website now works as normal.

Restoring a Previous File

Restoring a Previous File

If you’re not sure what’s changed in the code and you want to restore a previous file that you know works, go to the file in FTP or cPanel.

Sometimes WordPress doesn’t tell you where the problem is coming from. In this case, you can rename the folders one at a time to see if the problem goes away. Start with your plugins.

If you do know where the problem is coming from, you can upload a replacement file. For a plugin or theme in the WordPress repository, you can delete the folder and reinstall it.

If you prefer, you can download the theme or plugin from the WordPress repository (or where you got it from), unzip the file, and only replace the file you need to. It works similarly to how we’ll replace WordPress in the next section.

Upload a Clean Copy of WordPress

Upload a Clean Copy of WordPress

If the problem is the WordPress core, you can upload a new version of WordPress without deleting your files. Download a new copy of WordPress and unzip it.

Upload a Clean Copy of WordPress

Next, delete the wp-content folder and the file called wp-config-sample.php.

Upload a Clean Copy of WordPress

Next, upload the WordPress files from the unzipped folder into your WordPress root folder. This will overwrite all files except for the two you deleted. Your site should work now.

Ending Thoughts on the Parse Error Syntax Error Unexpected End in WordPress

The parse error syntax error unexpected end in WordPress is a common error for anyone handling code. It’s not difficult to fix, but it can sometimes take time to track it down. The steps are simple:

  • If you’ve added code, start there.
  • If you’ve installed a plugin or theme, deactivate it.
  • When you can’t find the problem, replace the suspected files.
  • When all else fails, restore a backup.

Following a few troubleshooting steps will help get your site running smoothly as fast as possible.

We want to hear from you. Have you had the parse error syntax error unexpected end in WordPress? Let us know how you fixed it in the comments below.

Featured Image via alexdndz / shutterstock.com

Each and every one of your gauss variables are missing the multiplication operator in two places. Check every line at it will run. For example, this:

gauss1=(1/(y*sqrt(2*%pi)))exp(-0.5(bb/y)^2)

should be this:

gauss1=(1/(y*sqrt(2*%pi))) * exp(-0.5 * (bb/y)^2)

As for the Gaussian bell, there is no standard function in Scilab. However, you could define a new function to make things more clear in your case:

function x = myGauss(s,b_)
    x = (1/(s*sqrt(2*%pi)))*exp(-0.5*(b_/s)^2)
endfunction

Actually, while we’re at it, your whole code is really difficult to read. You should define functions instead of repeating code: it helps clarify what you mean, and if there is a mistake, you need to fix only one place. Also, I personally do not recommend that you enclose everything in a function like bla7() because it makes things harder to debug. Your example could be rewritten like this:

  • The myGauss function;
  • A function w_ to calculate w1, w2, w10, w20, w100 and w200;
  • A function c_ to calculate c1, c2, c10, c20, c100 and c200;
  • A function normal_ to calculate normal1, normal2, normal10, normal20, normal100 and normal200;
  • Call all four functions as many times as needed with different inputs for different results.

If you do that, your could will look like this:

function x = myGauss(s,b_)
    x = (1 / (s * sqrt(2 * %pi))) * exp(-0.5 * (b_/s)^2);
endfunction

function [w1_,w2_] = w_(t_,l_,n_,p_)

    w1_ = zeros(t_,1);
    w2_ = zeros(t_,1);
    for I = 1 : t_
        a = (grand(n_,1,"unf",0,p_));
        x = l_ * cos(a);
        y = l_ * sin(a);
        z1 = zeros(n_,1);
        z2 = zeros(n_,1);
        for i = 2 : n_
            z1(i) = z1(i-1) + x(i);
            z2(i) = z2(i-1) + y(i);
        end
        w1_(I) = z1($);
        w2_(I) = z2($);
    end

endfunction

function [c1_,c2_] = c_(t_,k_,v_,w1_,x_)

    c1_ = zeros(k_,1)
    for r = 1 : t_
        c = w1_(r);
        m = -x_ + v_;
        n = -x_;
        for g = 1 : k_
            if (c < m & c >= n) then
                c1_(g) = c1_(g) + 1;
                m = m + v_;
                n = n + v_;
            else
                m = m + v_;
                n = n + v_;
            end
        end
    end
    c2_ = zeros(k_,1);
    c2_(1) = -x_ + (x_/k_);
    for b = 2 : k_
        c2_(b) = c2_(b-1) + v_;
    end

endfunction

function [normal1_,normal2_,normal3_] = normal_(k_,bb_,bc_,v_,w1_)

    y = stdev(w1_);

    normal1_ = zeros(k_,1);
    normal2_ = zeros(k_,1);

    for wa = 1 : k_ 
        bd_ = (bb_ + bc_) / 2;
        gauss1 = myGauss(y,bb_);
        gauss2 = myGauss(y,bc_);
        gauss3 = myGauss(y,bd_);
        gauss4 = ((bc_ - bb_) / 6) * (gauss1 + gauss2 + 4 * gauss3);
        bb_ = bb_ + v_;
        bc_ = bc_ + v_;
        normal2_(wa,1) = gauss4;
    end

    normal3_ = normal2_ * 4000;

endfunction

t = 4000;
l = 0.067;
p = 2 * %pi;

n = 1000;
k = 70;
v = 12 / k;
x = 6;
bb = -x;
bc = -x + v;
[w1,w2] = w_(t,l,n,p);
[c1,c2] = c_(t,k,v,w1,x);
[normal1,normal2,normal3] = normal_(k,bb,bc,v,w1);
bar(c2,c1,1.0,'white');
plot(c2, normal3, 'r-');

n = 10000;
k = 100;
v = 24 / k;
x = 12;
bb = -x;
bc = -x + v;
[w10,w20] = w_(t,l,n,p);
[c10,c20] = c_(t,k,v,w10,x);
[normal10,normal20,normal30] = normal_(k,bb,bc,v,w10);
bar(c20,c10,1.0,'white');
plot(c20, normal30, 'b-');

n = 100;
k = 70;
v = 12 / k;
x = 6;
bb = -x;
bc = -x + v;
[w100,w200] = w_(t,l,n,p);
[c100,c200] = c_(t,k,v,w100,x);
[normal100,normal200,normal300] = normal_(k,bb,bc,v,w100);
bar(c200,c100,1.0,'white');
plot(c200, normal300, 'm-');

poly1.thickness=3;
xlabel(["x / um"]);
ylabel("molecules");
gcf().axes_size=[500,500]
a=gca();
a.zoom_box=[-12,12;0,600];
a.font_size=4;
a.labels_font_size=5;
a.x_label.font_size = 5;
a.y_label.font_size = 5;
ticks = a.x_ticks
ticks.labels =["-12";"-10";"-8";"-6";"-4";"-2";"0";"2";"4";"6";"8";"10";"12"]
ticks.locations = [-12;-10;-8;-6;-4;-2;0;2;4;6;8;10;12]
a.x_ticks = ticks
  • Inclab

  • Scilab для новичков

  • Построение графиков Scilab

Математический пакет Scilab располагает широким и гибко настраиваемым аппаратом для построения двумерных графиков и трёхмерных изображений.

Данная статья получила продолжение: Как настраивать толщину и начертание графиков в Scilab и дополнительный разбор Настройки графиков: свойства осей и сетки.

Перечислим основные функции для оформления графика:

xgrid() — добавление сетки на график;
xtitle(«Название графика», «Название оси абсцисс», «Название оси ординат») — добавление подписей;
legend(.., , .. ) — создание легенды с перечнем всех отображенных графиков в системе координат;
subplot(mnk) — функция разделения окна на матрицу, содержащую ( m ) строк, (n столбцов), а (k )- это номер ячейки, в которой будет отображен график.

Например, subplot(312) разобъёт графичекое окно на 3 строки, 1 столбец и нарисует график во второй ячейке:

Расположение графика в графическом окне subplot(312).

Расположение графика в графическом окне subplot(312).

Например, subplot(234) разобъёт графичекое окно на 2 строки, 3 столбца и нарисует график в четвёртой ячейке:

Расположение графика в графическом окне subplot(234).

Расположение графика в графическом окне subplot(234).

5.1 Двумерные графики

Для построения графиков, в которых положение точки задаётся двумя величинами, в Scilab нужно воспользоваться функцией plot(x, y , s). Здесь первая переменная ( х ) — массив абсцисс, ( у ) — массив ординат, ( s ) — необязательный параметр, отвечающий за цвет графика, толщину и начертание линии.

Установить желаемый вид и цвет графика можно, указав строковый параметр ( s ), который может состоять из одного, двух или трёх символов, определяющие соответственно: цвет линии, тип маркера, тип линии графика. Возможные значения перечислены в таблицах 2-4.

Таблица 2. Символы, определяющие цвет линии графика.

Таблица 2. Символы, определяющие цвет линии графика.

Таблица 3. Символы, определяющие тип линии графика.

Таблица 3. Символы, определяющие тип линии графика.

Таблица 4. Символы, определяющие тип маркера

Таблица 4. Символы, определяющие тип маркера

Для демонстрации работы функции plot() построим графики траектории движения точки по заданным уравнениям ( x(t), y(t) ) на плоскости и в заданном диапазоне времени T (таблица 5). Определим внешний вид каждого из графиков, а также оформим систему координат со всеми необходимыми подписями (листинг 13). Результат работы программы представлен на рис. 7.

Таблица 5. Уравнения движения материальной точки и промежуток времени.

Таблица 5. Уравнения движения материальной точки и промежуток времени.

Рисунок 7. Построение графиков движения материальной точки.

Рисунок 7. Построение графиков движения материальной точки.


/* графики траектории движения материальной точки */

// очищаем область консоли и графического окна
clc; clf; 

// создаём пользовательскую функцию для координаты х
function z = X(t)
    z = 3 - 2*cos(%pi*t/2);
endfunction;

// создаём пользовательскую функцию для координаты y
function z = Y(t)
    z = 1 + 3*sin(%pi*t/3);
endfunction;


d = 1e-2;    // задаём шаг
T = 0:d:10;   // задаём диапазон времени

x = X(T);   // вызываем пользовательскую функцию X
y = Y(T);   // вызываем пользовательскую функцию Y

subplot(211);       // разделяем графическое окно на 2 строки 
plot(T, x, "k--");  // строим график x(t)
plot(T, y);         // строим график у(t) в той же системе координат
xgrid; 
xtitle("Траектория движения точки", "t", "x(t), y(t)"); 
legend("x(t)", "y(t)");

subplot(212);  
xgrid; 
xtitle("Траектория движения точки на фазовой плоскости", "x(t)", "y(t)"); 
comet(x, y);      // строим анимированную траекторию движения точки на фазовой плоскости

Листинг 13. Программа построения графиков движения материальной точки.

5.2 Построение трёхмерных изображений

Для построения поверхности в Scilab используются функции plot3d( plot3d1) и plot3d2(plot3d3). Их отличие состоит в том, что первая пара функций plot3d( plot3d1) строит поверхность из отдельно стоящих друг от друга грани (залитую одним цветом и залитую различными цветами соответсвенно), а вторая пара plot3d2(plot3d3) — цельное геометрическое тело.

Процесс построения графика функции вида ( Z(x,y) ) можно разделить на 3 этапа:
1. Создание прямоугольной сетки с помощью функции linspace();
2. Вычисление значений функции ( Z(x,y) ) в узлах сетки;
3. Вызов функции plot3d() или plot3d2().

В качестве примера, построим сферу в трехмерной системе координат с помощью функций plot3d1 и plot3d2.

Рисунок 8. Сфера, заданная параметрически, построенная с помощью функции plot3d1 (слева) и plot3d2 (справа).

Рисунок 8. Сфера, заданная параметрически, построенная с помощью функции plot3d1 (слева) и plot3d2 (справа).

Поверхность сферы в декартовых координатах ( (x,y,z) ) параметрически задаётся системой уравнений: ( f(n) = begin{cases}
x(u,v)=cos(u)cos(v) y(u,v)=cos(u)sin(v) z(u,v)=sin(u) end{cases} ),
независимые переменные ( u и v ) изменяются на промежутке ( [-pi; pi] ). Результат работы программы представлен на рис.8, исходный код на листинге 14.


/* работа с трёхмерными графиками */

u = linspace(-%pi, %pi, 40); // задаём сетку для параметра u с 40 значениями в указанном диапазоне
v = linspace(-%pi, %pi, 40); // задаём сетку для параметра v с 40 значениями в указанном диапазоне
/* массивы u и v должны иметь одиноковый размер! */

/* Формируем матрицы значения для каждой координаты */
X = cos(u)'*cos(v);
Y = cos(u)'*sin(v);
Z = sin(u)'*ones(v);

/* Строим трёхмерные графики */
subplot(121);
plot3d(X,Y,Z);
xtitle("Сфера, состоящая из граней", "x", "y", "z");

subplot(122);
plot3d2(X,Y,Z);
xtitle("Сфера, как геометрическое тело", "x", "y", "z");

Листинг 14. Программа, реализующая построения трехмерного изображения сферы с помощью функции plot3d1 и plot3d2.

Обратите внимание, что при построении графиков поверхностей заданных параметрически , (x(u,v), y(u,v) и z(u,v) ), необходимо сформировать матрицы ( X, Y и Z) одинакового размера. Для этого массивы ( u и v ) должны иметь одинаковый размер.

Кроме того, если какая-либо функция из ( X, Y или Z) зависит только от одного параметра ( u или v ), необходимо провести векторное умножение на единичный вектор ones() размерности, равной размерности параметра, от которого эта функция не зависит (см. строку 10 листинга 14).

Данная статья получила продолжение: Как настраивать толщину и начертание графиков в Scilab

Нравится
64
(лайкай без регистрации)

You are running a Bash script, and you see a syntax error: Unexpected end of file.

What does it mean?

This can happen if you create your script using Windows.

Why?

Because Windows uses a combination of two characters, Carriage Return and Line Feed, as line break in text files (also known as CRLF).

On the other side Unix (or Linux) only use the Line Feed character as line break.

So, let’s see what happens if we save a script using Windows and then we execute it in Linux.

Using the Windows notepad I have created a Bash script called end_of_file.sh:

#/bin/bash

if [ $# -gt 0 ]; then
  echo "More than one argument passed"
else
  echo "No arguments passed"
fi

And here is the output I get when I execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh 
./end_of_file.sh: line 2: $'r': command not found
./end_of_file.sh: line 8: syntax error: unexpected end of file 

How do we see where the problem is?

Edit the script with the vim editor using the -b flag that runs the editor in binary mode:

[ec2-user@localhost scripts]$ vim -b end_of_file.sh

(Below you can see the content of the script)

#/bin/bash^M
^M
if [ $# -gt 0 ]; then^M
  echo "More than one argument passed"^M
else^M
  echo "No arguments passed"^M
fi^M

At the end of each line we see the ^M character. What is that?

It’s the carriage return we have mentioned before. Used by Windows but not by Unix (Linux) in line breaks.

To solve both errors we need to convert our script into a format that Linux understands.

The most common tool to do that is called dos2unix.

If dos2unix is not present on your system you can use the package manager of your distribution to install it.

For instance, on my server I can use YUM (Yellowdog Updater Modified).

To search for the package I use the yum search command:

[root@localhost ~]$ yum search dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
====================== N/S matched: dos2unix =====================================
dos2unix.x86_64 : Text file format converters

And then the yum install command to install it:

[root@localhost ~]$ yum install dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                   | 2.4 kB  00:00:00
amzn2extra-docker                                            | 1.8 kB  00:00:00     
Resolving Dependencies
--> Running transaction check
---> Package dos2unix.x86_64 0:6.0.3-7.amzn2.0.2 will be installed
--> Finished Dependency Resolution 

Dependencies Resolved 

==================================================================================
  Package       Arch        Version            Repository            Size
==================================================================================
 Installing:
  dos2unix      x86_64      6.0.3-7.amzn2.0.2  amzn2-core            75 k
 
 Transaction Summary
==================================================================================
 Install  1 Package

 Total download size: 75 k
 Installed size: 194 k
 Is this ok [y/d/N]: y
 Downloading packages:
 dos2unix-6.0.3-7.amzn2.0.2.x86_64.rpm                      |  75 kB  00:00:00     
 Running transaction check
 Running transaction test
 Transaction test succeeded
 Running transaction
   Installing : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 
   Verifying  : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 

 Installed:
   dos2unix.x86_64 0:6.0.3-7.amzn2.0.2                                                                                                                         
 Complete! 

We are ready to convert our script using dos2unix!

[ec2-user@localhost scripts]$ dos2unix end_of_file.sh 
dos2unix: converting file end_of_file.sh to Unix format ... 

And now it’s time to execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh  No arguments passed

It works!

If you are interested I have written an article that explains the basics of Bash script arguments.

Conclusion

I have found myself having to use the dos2unix command several times over the years.

And now you know what to do if you see the syntax error “Unexpected end of file” while running a Bash script 🙂


Related FREE Course: Decipher Bash Scripting

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

function wooc_extra_register_fields() {?>
       <p class="form-row form-row-wide">
       <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?></label>
       <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />
       </p>
       <p class="form-row form-row-first">
       <label for="reg_billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?>*</label>
       <input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
       </p>
       <p class="form-row form-row-last">
       <label for="reg_billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?>*</label>
       <input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
       </p>
       <div class="clear"></div>
       <?php
 }
 add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

What I have tried:

function wooc_extra_register_fields() {?>
       <p class="form-row form-row-wide">
       <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?></label>
       <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />
       </p>
       <p class="form-row form-row-first">
       <label for="reg_billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?>*</label>
       <input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
       </p>
       <p class="form-row form-row-last">
       <label for="reg_billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?>*</label>
       <input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
       </p>
       <div class="clear"></div>
       <?php
 }
 add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

6 / 6 / 1

Регистрация: 23.04.2015

Сообщений: 340

1

05.10.2018, 10:07. Показов 14559. Ответов 4


Студворк — интернет-сервис помощи студентам

ДВ! Помогите пожалуйста . нужно решение в Scilab.

Для любого целого k обозначим количество цифр в его десятичной записи С(k). Например: С(1)=1, с(9)=1, с(10)=2.
Дано натуральное число n, действительное число x. Вычислить:

https://www.cyberforum.ru/cgi-bin/latex.cgi?frac{{10}^{c(1)}}{1}*(1-x)+frac{{10}^{c(2)}}{2}*{(1-x)}^{2}+...+frac{{10}^{c(n)}}{n}*{(1-x)}^{n}

Выдает ошибку. Ошибка: syntax error, unexpected end of file, expecting end

Код

function C(k)
n=input('n='); 
x=input('x='); 
m=n; 
while m>0
m=m/10;
s=0;
for k=1:n 
s=s+power(10,C(k))*power(1-x,k)/k; 
mprintf('s',s) 
end



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

05.10.2018, 10:07

Ответы с готовыми решениями:

Parse error: syntax error, unexpected end of file, expecting function (T_FUNCTION)
Выскакивает такая ошибка &quot;Parse error: syntax error, unexpected end of file, expecting function…

Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in W:domainslocalhostform4.php on li
&lt;?php
public static function getMacAlgoBlockSize($algorithm = ‘sha1’)
{

Syntax error: end of file unexpected (expecting «fi»)
Помогите разобраться, в чем ошибка
Скрипт брал тут…

Где ошибка syntax error, unexpected end of file ?
Доброго времени суток!
У меня не работает простой код. Помогите, плиз, понять в чём причина.

4

1265 / 901 / 440

Регистрация: 21.10.2012

Сообщений: 2,566

05.10.2018, 10:40

2

qwer77, вам нужно добавить в конце файла два end



0



6 / 6 / 1

Регистрация: 23.04.2015

Сообщений: 340

05.10.2018, 13:06

 [ТС]

3

добавила, все равно не считает сумму



0



Krasme

6653 / 4751 / 1983

Регистрация: 02.02.2014

Сообщений: 12,732

05.10.2018, 14:15

4

Лучший ответ Сообщение было отмечено qwer77 как решение

Решение

причешем…

Кликните здесь для просмотра всего текста

Matlab M
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//функция вычисления количества цифр
function [i]=C(k)
    i=0
    while k>=1
        //mprintf('%d %dn',k, i)
        k=k/10;
        i=i+1
     end
endfunction
 
// основной блок программы
n=15 //input('n='); 
x=0.01 //input('x='); 
s=0
for k=1:n
    //mprintf('%d %dn',k,C(k))
    s=s+10^C(k)*((1-x)^k)/k; 
end
mprintf('%fn',s)



1



qwer77

6 / 6 / 1

Регистрация: 23.04.2015

Сообщений: 340

09.10.2018, 11:14

 [ТС]

5

Matlab M
1
2
3
4
5
n=input('n=');
for i=1:n
s=4*((-1)^n*1/(2*n-1));
mprintf('%fn',s)
end

Вот так правильно??

Добавлено через 2 минуты
извините не туда



0



Есть такая строка, на которую ругается php7, но не ругается php5. Что надо исправить?
Код не мой, писанина 2005 года для CDR.
Ошибка

PHP Parse error:  syntax error, unexpected '=', expecting end of file in /var/www/cdr/call-log.php on line 282, referer:

282ая строка

<FORM METHOD=POST ACTION="<?php =$PHP_SELF ?>?s=<?php = $s ?>&t=<?php = $t ?>&order=<?php =$order ?>&sens=<?php =$sens ?>&current_page=<?php =$current_page ?>">

Понравилась статья? Поделить с друзьями:
  • Ошибка syntax error unexpected end of line scilab
  • Ошибка syntax error unexpected end of file scilab
  • Ошибка syntax error near unexpected token done
  • Ошибка syntactically invalid ehlo argument s
  • Ошибка sxstrace exe как исправить ошибку