PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label compiler-errors. Show all posts
Showing posts with label compiler-errors. Show all posts

Friday, November 4, 2022

[FIXED] Why visual c++ (latest) and gcc 12.1 accepted hiding this init capture for lambda, while clang 14.0.0 not? (c++20)

 November 04, 2022     c++, compiler-errors, lambda, language-lawyer     No comments   

Issue

Case 1

int main() {
    int x = 100;
    auto lamb_var = [y = x](){
                    int y = 10;
                    return y + 1;
    }; 

    assert (lamb_var() == 11);

    return 0; 
}

in https://godbolt.org/z/hPPParjnz

Both MSVC and GCC accepted shadowing the init-capture, while Clang accused y redefinition on the compound statement and throwed compiler error.

However, if we remove the init-capture and make a simple-capture, all compilers accept Shadowing:

Case 2

int main() {
    int x = 100;
    auto lamb_var = [x](){
                    int x = 10;
                    return x + 1;
    }; 

    assert (lamb_var() == 11);

    return 0; 
}

in https://godbolt.org/z/Gs4cadf5e


A simple-capture (case 2) leads to the creation of an attribute in the lambda-associated class, so shadowing should be normal.

From what I found,the expression "whose declarative region is the body of the lambda expression" of the quote below from cppreference could defend the implementation of CLANG ("redefinition"), but I'm not sure.

A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression (that is, it is not in scope within its initializer), except that: [...]

Who is right in implementation (GCC and MSVC or Clang), and how to understand this citation of cppreference?


Related questions

Lambda capture and parameter with same name - who shadows the other? (clang vs gcc)


Solution

I think that clang is correct in rejecting snippet 1 and accepting snippet 2 because in the first case the non-static data member is named y while in the second case the non-static data member is unnamed.

Case 1

Here we consider snippet 1:

int main() {
    int x = 100;
    auto lamb_var = [y = x](){  //the data member is "named" y
                    int y = 10; //error because we're defining y for second time 
                    return y + 1;
    }; 

    assert (lamb_var() == 11);

    return 0; 
}

Now, from expr.prim.lambda#capture-6:

An init-capture without ellipsis behaves as if it declares and explicitly captures a variable of the form auto init-capture ; whose declarative region is the lambda-expression's compound-statement, except that:

(emphasis mine)

This seems to indicate that the non-static data member has a name which in your given example is y. Now, by writing int y = 10; we're providing a redefinition of the same named variable y in the same declarative region and hence the error.


Note that we will get the same error(as expected due to the reason explained above), if we replace [y=x] with [x=x] and int y =10; with int x = 10; as shown below:

int main() {
    int x = 100;
    auto lamb_var = [x = x](){  //data member "named" x
                    int x = 10; //this will give same error 
                    return x + 1;
    }; 

    assert (lamb_var() == 11);

    return 0; 
}

Case 2

Here we consider the snippet 2:

int main() {
    int x = 100;
    auto lamb_var = [x](){         //data member is unnamed
                    int x = 10;   //ok because we're defining an int variable with "name" x for the first time in this region
                    return x + 1;
    }; 

    assert (lamb_var() == 11);

    return 0; 
}

Here from expr.prim.lambda#capture-10:

For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified....

(emphasis mine)

In this case, the non-static data member is unnamed and so writing int x = 10; is not a redefinition error because we're definining a variable named x for the first time in this region.



Answered By - Jason Liam
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] how to find out why webpage created by Symfony v2.8 isn't loading?

 October 28, 2022     compiler-errors, is-empty, symfony-2.8     No comments   

Issue

I'm sharing this issue, because it is a particularly tricky type of coding problem to resolve.

I've several in the past gotten an error saying:

This page isn’t working
website.com didn’t send any data.
ERR_EMPTY_RESPONSE

Which is different than what Symfony displays when there is an error in the code producing a webpages for the site, so isn't all that helpful.

This time I tracked down the cause of the error by setting breakpoints, not in the code that I was editing, because the php xdebugger never got that far, but deep in the Symfony code that runs before my code actually gets executed. Here is the code in which I put the breakpoint:

public static function handleFatalError(array $error = null)
{
    if (null === self::$reservedMemory) {
        return;
    }

    self::$reservedMemory = null;

    $handler = set_error_handler('var_dump');
    $handler = is_array($handler) ? $handler[0] : null;
    restore_error_handler();

    if (!$handler instanceof self) {
        return;
    }

    if ($exit = null === $error) {
        $error = error_get_last();
    }

    try {
        while (self::$stackedErrorLevels) {      <<<< I put the breakpoint here!
            static::unstackErrors();
        }
    } catch (\Exception $exception) {
        // Handled below
    } catch (\Throwable $exception) {
        // Handled below
    }

    if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
        // Let's not throw anymore but keep logging
        $handler->throwAt(0, true);
        $trace = isset($error['backtrace']) ? $error['backtrace'] : null;

        if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
            $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
        } else {
            $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
        }
    }

    try {
        if (isset($exception)) {
            self::$exitCode = 255;
            $handler->handleException($exception, $error);
        }
    } catch (FatalErrorException $e) {
        // Ignore this re-throw
    }

    if ($exit && self::$exitCode) {
        $exitCode = self::$exitCode;
        register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
    }
}

When Symfony tries to load my bundle file with a require $file statement in another part of its code, the above function is called. Unfortunately, I couldn't watch the $error or any other variable, but when the breakpoint was encountered, my debugger does show the content of the $error variable up on the line where it is assigned the value of error_get_last();. Even though the content is an array so extends beyond the right edge of my screen, it displays enough to make out the problem. No line number shows, but the text of the error does.

Another thing that I found while looking for the error is that all of the PHP files in the server's src/AppBundle./Controller/ and below are processed by Symfony, so if you keep your code in files ending with *.php it will be loaded, even though it isn't referenced by your code. In my case I had a bundle file that I renamed from bundle.php to bundle.24.php, intending to keep it as a fallback while I continued working on new changes to bundle.php, but bundle.24.php had a syntax error, which stopped Symfony from loading the project, but I wasn't aware of this because I got the error that I showed at the top of this issue.

Anyway, I thought I'd share this with anyone who runs into the same error while working with Symfony v2.8. I hope that later versions of Symfony don't continue to work this way, but if they do, well then here is a clue to where to look or what might be causing the problem. Note, in later versions, I'm sure that the handler function could be different than what I'm showing, but it should be some what similar.

Good luck.


Solution

The solution when you get this kind of error in Symfony is to place breakpoints in the code that is called by the app_dev.php's $response->send(); line, and then walk the code until you fine the require $file; line. Use the your PHP debugger to watch the $file and $class variables and you'll see that the require statement is about to load your code file. If it jumps to the error handler function, you'll know that the code didn't load, and as I said in the issue, you won't be able to watch the $error variable, but you should be able to see its contents as I described, so have a pretty good idea of the code error that is causing the bundle file to not load.



Answered By - user2505564
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, June 26, 2022

[FIXED] How do you compile a java program from the command line while using selenium in the source code?

 June 26, 2022     compiler-errors, java, selenium     No comments   

Issue

I am working on a final project for my Computer Science course. I built an program using the Selenium library to automate the process of creating a github repo and linking it to a local folder. I am only able to run the program inside of VS Code using their "Run" feature. I want to be able to run this from the Command Line in Windows, but I am not able to compile it since Java doesn't recognize Selenium object types like WebDriver and WebElement. How would I compile it using this outside library?


Solution

It is strongly recommended to use Maven for java projects. It can fetch all the needed dependencies if you have added the maven dependency to the pom.xml file.

Otherwise download the Selenium jar file and use the following command to compile your code.

javac -cp .:jarfile1.jar:jarfile2.jar <MainClass>.java

and run the following to execute

java MainClass



Answered By - shmsi
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why AVR-GCC compiler throws an error when overloading with the same variables but as PROGMEM?

 June 26, 2022     avr-gcc, c++, compiler-errors, progmem     No comments   

Issue

My question is more like: Why the compiler "thinks" that a "PROGMEM variable" is the same as a "plain Variable"? is it because PROGMEM-keyword is "just" a macro and nothing more? or is it for some other reason too? and is there any workaround..?

ISSUE demonstration:

Lets consider the below example:

class object {
public:
  object(int* variable);
  object(int* variable PROGMEM);
};

it throws error: 'object::object(int*)' cannot be overloaded as if it is the same.

sketch_jul31a:4:3: error: 'object::object(int*)' cannot be overloaded

   object(int* variable PROGMEM)

   ^~~~~~

sketch_jul31a:3:3: error: with 'object::object(int*)'

   object(int* variable)

   ^~~~~~

exit status 1
'object::object(int*)' cannot be overloaded

Outro:

I came across this issue a while ago when i was developing a library, I've asked about it on the arduino-forum but i had not any answer and so i've thought after a long period to ask about it once again, here.


Solution

You can't expect the compiler to treat linker sections as type qualifiers, but you can define an overload for a const int*, which is pretty close to the semantics of PROGMEM (a ROM location).

I wonder what you plan on doing with a const int* though. All you will ever be able to do is read it, so it's basically equivalent to a plain constant int value, with the added cost of two bytes of ROM.



Answered By - kuroi neko
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a print("{}") with another File?

 June 26, 2022     compiler-errors, file, python     No comments   

Issue

I want to make the print({}) display something from another File. What I have been trying:

main.py:

with open("Filename.txt", "tr") as f:
  data = f.readlines()
 if "print({})" in data:
  print("{}".format(data))

Filename.txt:

print("Hello world")

result:

This means I have made an error. But there were no error messages. What did I do wrong?


Solution

It will search for the exact string print({}). It seems like you need the text within that print statement, its better to use regex and find text between print( and ). See https://stackoverflow.com/a/3369000/7334699

I don't know what your goal exactly is, but you can also take a look at the eval() function which just runs python code within a string.



Answered By - ToTheMax
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to force Werror=declaration-after-statement with -std=c99 in clang

 June 26, 2022     c, c99, clang, compiler-errors, gcc     No comments   

Issue

I would like to have compiler throw an error every time there is a declaration after statement because that is the coding style I want to enforce, but I also want to compile with -std=c99 since I use some of the specific c99 features.

The problem is that in c99 declarations are allowed anywhere in the code, not just at the beginning of a block.

Take a look at the following program:

// prog.c
#include <stdio.h>

int main(void)
{
    printf("hello world\n");
    int i = 0;

    return 0;
}

If I compile this code with gcc like this:

gcc -std=c99 -Werror=declaration-after-statement prog.c

it throws the following error:

prog.c: In function ‘main’:
prog.c:6:9: error: ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]
    6 |         int i = 0;
      |         ^~~
cc1: some warnings being treated as errors

This is the behavior I would like to have when compiling with clang, but clang behaves differently.

If I compile the same code with clang like this:

clang -std=c99 -Werror=declaration-after-statement prog.c

it throws no errors.

Only if I compile the code with clang like this it throws the error I want:

clang -std=c90 -Werror=declaration-after-statement prog.c

prog.c:6:6: error: ISO C90 forbids mixing declarations and code [-Werror,-Wdeclaration-after-statement]
        int i = 0;
            ^
1 error generated.

But this is not good for me because I need to use -std=c99.

Is it possible to force -Werror=declaration-after-statement along with -std=c99 when compiling with clang?


Solution

Looking at the source code of clang it seems like not supported.

The diagnostic is defined in clang/include/clang/Basic/DiagnosticSemaKind.td

def ext_mixed_decls_code : Extension<
  "ISO C90 forbids mixing declarations and code">,
  InGroup<DiagGroup<"declaration-after-statement">>;

And its only usage is in clang/lib/Sema/SemaStmt.cpp

StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
                                   ArrayRef<Stmt *> Elts, bool isStmtExpr) {
  const unsigned NumElts = Elts.size();

  // If we're in C89 mode, check that we don't have any decls after stmts.  If
  // so, emit an extension diagnostic.
  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
    // Note that __extension__ can be around a decl.
    unsigned i = 0;
    // Skip over all declarations.
    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
      /*empty*/;

    // We found the end of the list or a statement.  Scan for another declstmt.
    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
      /*empty*/;

    if (i != NumElts) {
      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
      Diag(D->getLocation(), diag::ext_mixed_decls_code); // <-- here
    }
  }
  ...

Note the !getLangOpts().C99 in the if. The diagnose code will never execute with a standard above c90.

Well one thing you can surely try is build clang by yourself and delete that part of the if so end up with if (!getLangOpts().CPlusPlus).

I tried and it worked for me.

You can configure the clang build with cmake -G "Ninja" -DCMAKE_BUILD_TYPE="Release" -DLLVM_ENABLE_PROJECTS="clang" -DLLVM_TARGETS_TO_BUILD="X86" -DCMAKE_C_COMPILER="/usr/bin/gcc" -DCMAKE_CXX_COMPILER="/usr/bin/g++" -DLLVM_PARALLEL_LINK_JOBS=2 -DLLVM_OPTIMIZED_TABLEGEN=ON path/to/llvm-project/llvm



Answered By - Eraklon
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is there no Typescript compile error when I treat a number as an array?

 June 26, 2022     compiler-errors, typescript     No comments   

Issue

I'm wondering why there's no error when I do something blatantly wrong like this:

const test : number = 123;
const test2 = test[3];

This is the tsconfig I'm using:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

Solution

You need to add

"strict": true

to your tsconfig.



Answered By - Ferruccio
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How does Clang's "did you mean ...?" variable name correction algorithm work?

 June 26, 2022     c++, clang, compiler-errors     No comments   

Issue

I am compiling C++ code with Clang. (Apple clang version 12.0.5 (clang-1205.0.22.11)).

Clang can give tips in case you misspell a variable:

#include <iostream>

int main() {
    int my_int;
    std::cout << my_it << std::endl;
}
spellcheck-test.cpp:5:18: error: use of undeclared identifier 'my_it'; did you mean 'my_int'?
    std::cout << my_it << std::endl;
                 ^~~~~
                 my_int
spellcheck-test.cpp:4:9: note: 'my_int' declared here
    int my_int;
        ^
1 error generated.

My question is:

What is the criterion Clang uses to determine when to suggest another variable?

My experimentation suggests it is quite sophisticated:

  • If there is another similarly named variable that you might have meant (e.g. int my_in;) it does not give a suggestion
  • If the suggested variable has the wrong type for the operation (e.g. by trying to print my_it.size() instead) it does not give a suggestion
  • Whether or not it gives the suggestion depends on a non-trivial comparison of variable names: it allows for both deletions and insertions of characters, and longer variable names allow for more insertion/deletions to be considered "similar".

Solution

You will not likely find it documented, but as Clang is open-source you can turn to the source to try to figure it out.

Clangd?

The particular diagnostic (from DiagnosticSemaKinds.td):

def err_undeclared_var_use_suggest : Error<
  "use of undeclared identifier %0; did you mean %1?">;

is ever only referred to from clang-tools-extra/clangd/IncludeFixer.cpp:

  // Try to fix unresolved name caused by missing declaration.
  // E.g.
  //   clang::SourceManager SM;
  //          ~~~~~~~~~~~~~
  //          UnresolvedName
  //   or
  //   namespace clang {  SourceManager SM; }
  //                      ~~~~~~~~~~~~~
  //                      UnresolvedName
  // We only attempt to recover a diagnostic if it has the same location as
  // the last seen unresolved name.
  if (DiagLevel >= DiagnosticsEngine::Error &&
      LastUnresolvedName->Loc == Info.getLocation())
    return fixUnresolvedName();

Now, clangd is a language server and t.b.h. I don't know how whether this is actually used by the Clang compiler frontend to yield certain diagnostics, but you're free to continue down the rabbit hole to tie together these details. The fixUnresolvedName above eventually performs a fuzzy search:

if (llvm::Optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
    return fixesForSymbols(**Syms);

If you want to dig into the details, I would recommend starting with the fuzzyFindCached function:

llvm::Optional<const SymbolSlab *>
IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
  auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str();
  auto I = FuzzyFindCache.find(ReqStr);
  if (I != FuzzyFindCache.end())
    return &I->second;

  if (IndexRequestCount >= IndexRequestLimit)
    return llvm::None;
  IndexRequestCount++;

  SymbolSlab::Builder Matches;
  Index.fuzzyFind(Req, [&](const Symbol &Sym) {
    if (Sym.Name != Req.Query)
      return;
    if (!Sym.IncludeHeaders.empty())
      Matches.insert(Sym);
  });
  auto Syms = std::move(Matches).build();
  auto E = FuzzyFindCache.try_emplace(ReqStr, std::move(Syms));
  return &E.first->second;
}

along with the type of its single function parameter, FuzzyFindRequest in clang/index/Index.h:

struct FuzzyFindRequest {
  /// A query string for the fuzzy find. This is matched against symbols'
  /// un-qualified identifiers and should not contain qualifiers like "::".
  std::string Query;
  /// If this is non-empty, symbols must be in at least one of the scopes
  /// (e.g. namespaces) excluding nested scopes. For example, if a scope "xyz::"
  /// is provided, the matched symbols must be defined in namespace xyz but not
  /// namespace xyz::abc.
  ///
  /// The global scope is "", a top level scope is "foo::", etc.
  std::vector<std::string> Scopes;
  /// If set to true, allow symbols from any scope. Scopes explicitly listed
  /// above will be ranked higher.
  bool AnyScope = false;
  /// The number of top candidates to return. The index may choose to
  /// return more than this, e.g. if it doesn't know which candidates are best.
  llvm::Optional<uint32_t> Limit;
  /// If set to true, only symbols for completion support will be considered.
  bool RestrictForCodeCompletion = false;
  /// Contextually relevant files (e.g. the file we're code-completing in).
  /// Paths should be absolute.
  std::vector<std::string> ProximityPaths;
  /// Preferred types of symbols. These are raw representation of `OpaqueType`.
  std::vector<std::string> PreferredTypes;

  bool operator==(const FuzzyFindRequest &Req) const {
    return std::tie(Query, Scopes, Limit, RestrictForCodeCompletion,
                    ProximityPaths, PreferredTypes) ==
           std::tie(Req.Query, Req.Scopes, Req.Limit,
                    Req.RestrictForCodeCompletion, Req.ProximityPaths,
                    Req.PreferredTypes);
  }
  bool operator!=(const FuzzyFindRequest &Req) const { return !(*this == Req); }
};

Other rabbit holes?

The following commit may be another leg to start from:

[Frontend] Allow attaching an external sema source to compiler instance and extra diags to TypoCorrections

This can be used to append alternative typo corrections to an existing diag. include-fixer can use it to suggest includes to be added.

Differential Revision: https://reviews.llvm.org/D26745

from which we may end up in clang/include/clang/Sema/TypoCorrection.h, which sounds like a more reasonably used feature by the compiler frontend than that of the (clang extra tool) clangd. E.g.:

  /// Gets the "edit distance" of the typo correction from the typo.
  /// If Normalized is true, scale the distance down by the CharDistanceWeight
  /// to return the edit distance in terms of single-character edits.
  unsigned getEditDistance(bool Normalized = true) const {
    if (CharDistance > MaximumDistance || QualifierDistance > MaximumDistance ||
        CallbackDistance > MaximumDistance)
      return InvalidDistance;
    unsigned ED =
        CharDistance * CharDistanceWeight +
        QualifierDistance * QualifierDistanceWeight +
        CallbackDistance * CallbackDistanceWeight;
    if (ED > MaximumDistance)
      return InvalidDistance;
    // Half the CharDistanceWeight is added to ED to simulate rounding since
    // integer division truncates the value (i.e. round-to-nearest-int instead
    // of round-to-zero).
    return Normalized ? NormalizeEditDistance(ED) : ED;
  }

used in clang/lib/Sema/SemaDecl.cpp:

// Callback to only accept typo corrections that have a non-zero edit distance.
// Also only accept corrections that have the same parent decl.
class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
 public:
  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
                            CXXRecordDecl *Parent)
      : Context(Context), OriginalFD(TypoFD),
        ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}

  bool ValidateCandidate(const TypoCorrection &candidate) override {
    if (candidate.getEditDistance() == 0)
      return false;
     // ...
  }
  // ...
};


Answered By - dfrib
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I check if value exists in array

 June 26, 2022     c#, compiler-errors, try-catch     No comments   

Issue

I'm new to programming and am currently working on a calculator program.

I want the program to give an error message if none of the listed operators are being mentioned in the user input.

Here's my code:

int Number = 0;
string operation = "0";
string[] func = { "+", "-", "*", "/", ":", "x^2", "%", "cos", "bin" };

 while (true)
 {
    try
    {
        Number = Int32.Parse(Console.ReadLine());
        Console.WriteLine("--------------------------------------------");
        Console.WriteLine("Choose your operation: \n \n + \n - \n * \n : \n x^2 \n % \n cos \n bin");
        Console.WriteLine("--------------------------------------------");
        operation = Console.ReadLine();

        if (operation != func)
        {
            throw new Exception();
        }

        Console.WriteLine("--------------------------------------------");
        break;
    }
    catch (Exception)
    {
        Console.Clear();
        Console.WriteLine("Error! Please try again:");
    }
}

But, it says cannot use the != operator with a string and an array. (Compiler Error CS0019)

How can I check if a user input (operator) is in an array, so I can throw a new exception?


Solution

Try

if (!func.contains(operation)) 
{ 
    throw new Exception("");
}


Answered By - Wellerman
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I check if value exists in array

 June 26, 2022     c#, compiler-errors, try-catch     No comments   

Issue

I'm new to programming and am currently working on a calculator program.

I want the program to give an error message if none of the listed operators are being mentioned in the user input.

Here's my code:

int Number = 0;
string operation = "0";
string[] func = { "+", "-", "*", "/", ":", "x^2", "%", "cos", "bin" };

 while (true)
 {
    try
    {
        Number = Int32.Parse(Console.ReadLine());
        Console.WriteLine("--------------------------------------------");
        Console.WriteLine("Choose your operation: \n \n + \n - \n * \n : \n x^2 \n % \n cos \n bin");
        Console.WriteLine("--------------------------------------------");
        operation = Console.ReadLine();

        if (operation != func)
        {
            throw new Exception();
        }

        Console.WriteLine("--------------------------------------------");
        break;
    }
    catch (Exception)
    {
        Console.Clear();
        Console.WriteLine("Error! Please try again:");
    }
}

But, it says cannot use the != operator with a string and an array. (Compiler Error CS0019)

How can I check if a user input (operator) is in an array, so I can throw a new exception?


Solution

Try

if (!func.contains(operation)) 
{ 
    throw new Exception("");
}


Answered By - Wellerman
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does the compiler is giving me this: undefined reference to function?

 June 26, 2022     c, compiler-errors, declaration, function, gcc     No comments   

Issue

Ok I have been trying to figure this out for 3 hours and I have search a bunch of stack overflow questions and answers but I have this same error:

/usr/bin/ld: /tmp/ccXbXNRV.o: in function 'main':
main.c:(.text+0x5a): undefined reference to 'plus'
/usr/bin/ld: main.c:(.text+0x67): undefined reference to `minus'
collect2: error: ld returned 1 exit status

And I cant figure this out because my code doesn't seem that he is the problem

main.c:

#include <stdio.h>
#include "funcs.c"

int main()
{
    int z = 0;
    int wh = 1;
    while (wh == 1)
    {
        printf("What you want?\n1-Plus\n2-Minus\n");
        scanf("%d", &z);
        if (z == 1)
        {
            plus();
        }
        if (z == 2)
        {
            minus();
        }
    }
    printf("The program ended\n");

    return 0;
}

funcs.c

#include <stdio.h>

inline void plus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a + b;
    printf("The result is: %d\n", a);
}

inline void minus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a - b;
    printf("The result is: %d\n", a);
}

help.h

extern int a;
extern int b;
extern int z;
extern int wh;
inline void minus(void);
inline void plus(void);

I have try to compile it with this command gcc funcs.c main.c I know that is a simple program but I really want to learn c

If you could help I would be very thankful!


Solution

You can fix this by doing three things:

  1. Don't include a .c file. You're already providing it to gcc on the command line.
  2. Include help.h in files where you use those functions.
  3. Not using inline. You can't use inline when the caller and callee are in different translation units.

main.c:

#include <stdio.h>
// #include "funcs.c"
#include "help.h"

int main()
{
    int z = 0;
    int wh = 1;
    while (wh == 1)
    {
        printf("What you want?\n1-Plus\n2-Minus\n");
        scanf("%d", &z);
        if (z == 1)
        {
            plus();
        }
        if (z == 2)
        {
            minus();
        }
    }
    printf("The program ended\n");

    return 0;
}

funcs.c

#include <stdio.h>

void plus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a + b;
    printf("The result is: %d\n", a);
}

void minus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a - b;
    printf("The result is: %d\n", a);
}

help.h:

extern int a;
extern int b;
extern int z;
extern int wh;
void minus(void);
void plus(void);

Compile and run like so:

$ gcc -Wall -Werror funcs.c main.c
$ ./a.out 
What you want?
1-Plus
2-Minus
^C

Other thoughts:

extern int a;
extern int b;
extern int z;
extern int wh;

You're already declaring these variables locally. This is unneeded. The extern keyword tells the compiler that these variables are defined in another translation unit that it can't see. This isn't true, so you should just remove these.



Answered By - Nick ODell
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to reference a folder by name?

 June 26, 2022     compiler-errors, outlook, type-mismatch, vba     No comments   

Issue

When I try to open a non-default mail folder I'm getting

Compile Error: Type Mismatch

It occurs at Set oMailBox.

Sub openSxxInbox()

Dim oOutlook As Outlook.Application
Dim oFolder As Outlook.Folder
Dim oMailBox As Outlook.Folder
Dim oFldr As Outlook.Folder

Set oOutlook = CreateObject("Outlook.Application")
Set oNS = oOutlook.GetNamespace("MAPI")
Set oMailBox = "Sxx"
Set oFldr = "Inbox"

oNS.Logon 'does not do anything if Outlook is already running

Set oFolder = oNS.Folders(oMailBox).Folders(oFldr)

    If (oOutlook.ActiveExplorer Is Nothing) Then
        oFolder.Display
        Else
        Set oOutlook.ActiveExplorer = oFolder
    End If

End Sub

Solution

In the code you may find the following line:

Dim oMailBox As Outlook.Folder

and later you are trying assign a string value which is not correct:

Set oMailBox = "Sxx"
Set oFldr = "Inbox"

There is no direct cast between folder objects and strings. You can use the NameSpace.GetDefaultFolder method which returns a Folder object that represents the default folder of the requested type for the current profile; for example, obtains the default Inbox folder for the user who is currently logged on.

Note, you may find the Store.GetDefaultFolder method helpful which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.

Also you can define the object as string in the code:

Sub openSxxInbox()

Dim oOutlook As Outlook.Application
Dim oFolder As Outlook.Folder
Dim oMailBox As string
Dim oFldr As string

Set oOutlook = CreateObject("Outlook.Application")
Set oNS = oOutlook.GetNamespace("MAPI")
oMailBox = "Sxx"
oFldr = "Inbox"

oNS.Logon 'does not do anything if Outlook is already running

Set oFolder = oNS.Folders(oMailBox).Folders(oFldr)

    If (oOutlook.ActiveExplorer Is Nothing) Then
        oFolder.Display
        Else
        Set oOutlook.ActiveExplorer = oFolder
    End If

End Sub


Answered By - Eugene Astafiev
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to call correctly base class constructor from inherited class in Delphi Phrism?

 June 26, 2022     class, compiler-errors, constructor, delphi-prism, inherited     No comments   

Issue

I have two classes - base class and inherited class as follows.

Base Class:

TAlarm = class(System.Object)
private:
protected:
public:
    constructor (tag:TTagname);
end;

inherited class:

  TAlarmMsg = class(TAlarm)
  public
    constructor (aname:string);
    method GetAlarmMsg:string; override;
    method SendMsg(msg:string);
  end;

constructors:

constructor TAlarm(tag:TTagname);
begin
  Tagname := tag;
end;

constructor TAlarmMsg(aname:string);
begin
  inherited TAlarm(aname); <========Here is my problem.
  name := aname.ToCharArray;
end;

No matter what or how I call or play around with inherited constructor, I keep getting the following error messages when I compile the source file.

- Self cannot be accessed before the inherited constructor has finished. And/OR - Cannot find appropriate constructor in base class so manual call to inherited is required

By the way, I have spent good half a day researching on this issue and have found good information online. Nothing helps so far. I even found the webpage that directly talks about constructors on Delphi Prism Wikipedia ( http://prismwiki.embarcadero.com/en/Constructors ).

So, how would you do it correctly? Thanks,


Solution

The statement inherited constructor(aName); should do it.



Answered By - Carlo Kok
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why slice could call into_iter directly and do not abort?

 June 26, 2022     compiler-errors, rust     No comments   

Issue

I am a Rust newbie, I tested following code and got a question. Is type of slice [T]?If so, [T] is unsized, but it passed when I compiled the code. Why is that?

#[test]
fn test_scilce(){
    let v = vec!['a', 'b', 'v'];
    let slice = (v[1..3]).into_iter();
    // let s: String = slice.collect();
    println!("{:?}", slice);
    println!("{:?}", v);
}

Solution

Since [T]::into_iter(self) doesn't exist, but [T]::into_iter(&self) does, the compiler inserts the missing reference and treats (v[1..3]).into_iter() as (&v[1..3]).into_iter(). That is in turn the same as (&v[1..3]).iter() and gives out references to the elements of the vector. (There is even a clippy lint warning you of using into_iter() on slice or other references.)

The same auto-referencing mechanism is what allows you to write v.len() instead of the "correct" (&v).len(), despite Vec::len taking &self.



Answered By - user4815162342
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to increase stack size when compiling a C++ program using MinGW compiler

 June 26, 2022     c++, compiler-errors, mingw, stack-overflow     No comments   

Issue

I am trying to compile a program that was provided to me. The program tests the run time of the algorithm quicksort when provided different values. I need to increase the size of the stack to run really large numbers.

I read to use the following command: g++ -Wl,--stack,<size>

where size is the number to increase the stack.

However, this isn't working for me. In command prompt when I typed exactly the following:

g++ -Wl,--stack,1000000000

and then hit enter, I get the following message:

C:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../libmingw32.a(main.o):(.text.startup+0xa0): undefined reference to 'WinMain@16' collect2.exe: error: ld returned 1 exit status

I am not allowed to change the code so my only option is to increase the stack size in command prompt and then run my code.

I don't know what I am doing wrong. Am I typing in the command incorrectly?

How do I increase the stack size in command prompt for a c++ program using MinGW compiler? I am using Windows 10, if that information is helpful.


Solution

In order to change the size of the stack to run a C++ program that may cause a stack overflow, use the following command.

g++ -Wl,--stack,16777216 -o file.exe file.cpp

This increases the stack size to 16MiB, if you need it to be bigger then increase the value from 16777216 bytes to whatever value you need.

Do be sure to replace file.exe and file.cpp with the corresponding names of the file and executable that you are running.

Also note that in the command its -Wl (lower case L)



Answered By - LiveToLearn
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why I'm getting segmentation violation error in Go

 June 26, 2022     compiler-errors, go     No comments   

Issue

I'm trying to import 2 png image and paste one on top of the other. The output will be jpeg.

When ever I run the code below, I got this error:

image: unknown format
image: unknown format
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x109d7a4]
goroutine 1 [running]:
main.main()

Error is coming whenever I use "Bounds()" method. What do you think is the cause.

code:

func main() {
    imgFile1, err := os.Open("./pics/00/body.png")
    if err != nil {
        fmt.Println(err)
    }
    defer imgFile1.Close()
    imgFile2, err := os.Open("./pics/01/face.png")
    if err != nil {
        fmt.Println(err)
    }
    defer imgFile2.Close()
    img1, _, err := image.Decode(imgFile1)
    if err != nil {
        fmt.Println(err)
    }
    img2, _, err := image.Decode(imgFile2)
    if err != nil {
        fmt.Println(err)
    }
    //new rectangle for the second image
    sp1 := image.Point{0,0}
    sp2 := image.Point{img1.Bounds().Dx(),img1.Bounds().Dy()}
    r2 := image.Rectangle{sp1, sp2}

    //create new image
    rgba := image.NewRGBA(r2)

    //draw the two images into this new image
    draw.Draw(rgba, r2, img1, image.Point{0, 0}, draw.Src)
    draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)

    //export it
    out, err := os.Create("./output.jpg")
    if err != nil {
        fmt.Println(err)
    }
    defer out.Close()

    var opt jpeg.Options
    opt.Quality = 80

    jpeg.Encode(out, rgba, &opt)
}

Solution

I'm not sure why Go has two ways to decode like this. If you know the file type, I think it's better to just use the specific package:

package main

import (
   "fmt"
   "image/png"
   "net/http"
)

const ava = "http://gravatar.com/avatar/5ec9c21c8d54825b04def7a41998d18d"

func main() {
   r, err := http.Get(ava)
   if err != nil {
      panic(err)
   }
   defer r.Body.Close()
   i, err := png.Decode(r.Body)
   if err != nil {
      panic(err)
   }
   dx := i.Bounds().Dx()
   fmt.Println(dx)
}

If you insist on using the other method, you will need to add an import (thanks to mkopriva):

import (
   "image"
   _ "image/png"
)

https://godocs.io/image/png#Decode



Answered By - Zombo
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does the "collect2.exe: error: ld returned 1 exit status" keep coming?

 June 26, 2022     c, compiler-errors, runtime-error     No comments   

Issue

I'm a beginner in Coding. I'm trying to write a code in C. Uptill this code every code was running smoothly. But after writing the following code the Visual Studio Code is giving errors. The most repeated was collect2.exe: error: ld returned 1 exit status. I saved the code before running. I tried reinstalling the gcc MinGW compiler and Visual Studio Code IDE but nothing happened. I also tried the Geany IDE but it is showing the same error. What should I do?

    #include<stdio.h>
    #include<stdlib.h>

    int mian(){
         int marks[4];
         marks[0]=34;
         printf("Marks of Student 4 is %d",marks[0]);
         return 0;
    }

PS D:\Codes> cd "d:\Codes\CPrograms\" ; if ($?) { gcc arrays.c -o arrays } ; if ($?) { .\arrays }
c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../libmingw32.a(main.o):(.text.startup+0xa0): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status

Solution

Error: Id returned 1 exit status (undefined reference to 'main') 

This error is occurred on following cases,

  1. If main() is not written in lowercase, like you used Main(), MAIN(), mAin() or anything else.
  2. If main() does not exist in the program or by mistake you mistyped the main().

In your case you mistyped the main() change mian()--> main()

#include<stdio.h>
#include<stdlib.h>

int main(){
     int marks[4];
     marks[0]=34;
     printf("Marks of Student 4 is %d",marks[0]);
     return 0;
}


Answered By - shrey deshwal
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to determine which compiler flag/option causes "--p" to be passed to assembler?

 June 26, 2022     compiler-errors, gcc, gnu-assembler, musl, riscv     No comments   

Issue

I am trying to build the musl C library using a custom risc-v toolchain that uses GNU gcc version 8.1.0, GNU assembler version 2.34.

The error I get is the following:

home/guillermo/toolchain/as: invalid option -- 'p'

However, using the verbose flags for gcc and as the last call to the assembler is as follows (which includes NO such "--p" flag):

/home/guillermo/toolchain/as -v -I ./arch/riscv64 -I ./arch/generic -I obj/src/internal -I ./src/include -I ./src/internal -I obj/include -I ./include -I /home/guillermo/toolchain/library/common --traditional-format -fpic -march=rv64imafdc -mabi=lp64d --noexecstack -o obj/crt/Scrt1.o

The invocation of gcc before that was:

 /home/guillermo/toolchain/riscv64-gcc -nostdinc -v -I ./arch/riscv64 -I ./arch/generic -I obj/src/internal -I ./src/include -I ./src/internal -I obj/include -I ./include -I /home/guillermo/toolchain/library/common -D _XOPEN_SOURCE=700 -D CRT crt/Scrt1.c -quiet -dumpbase Scrt1.c -march=rv64imafdc -mabi=lp64d -auxbase-strip obj/crt/Scrt1.o -g -Os -Werror=implicit-function-declaration -Werror=implicit-int -Werror=pointer-sign -Werror=pointer-arith -Wno-tautological-compare -Wall -std=c99 -version -ffreestanding -fexcess-precision=standard -frounding-math -fno-unwind-tables -fno-asynchronous-unwind-tables -ffunction-sections -fdata-sections -fPIC -fno-stack-protector -o - |

Any help would be greatly appreciated as to what compiler flag could be causing "--p" to be passed to the assembler.


Solution

-fpic is an option for the compiler in particular. It has no special meaning to the assembler, which treats it the same as -f -p -i -c.



Answered By - Joseph Sible-Reinstate Monica
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect postgreSQL to c++

 June 26, 2022     c++20, compiler-errors, postgresql     No comments   

Issue

I have been following this video to install the linkage between postgreSQL and C++ (https://www.youtube.com/watch?v=qDiC1Wja6Og), and after following all the steps, i get this error: "The code execution cannot proceed because LIBPQ.dll was not found." even though i went into the postgreSQL directory and found the file. I have no clue how to fix it, i've tried reinstalling postgres and i've restarted my pc each time it was needed. Any clues or solutions would be appreciated thanks


Solution

Try put libpq.dll into directory of your project build also you need to add libeay32.dll, libiconv-2.dll and libintl-8.dll. You can take all these libraries from Postgres installation

|---app.exe
|---libpq.dll
|---libeay32.dll
|---libiconv-2.dll
|---libintl-8.dll

or add path to libpq.dll into the path environment of your os



Answered By - arutar
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What causes error "error: '.class' expected"?

 June 26, 2022     compiler-errors, java, joptionpane, swing     No comments   

Issue

Please help me solve these errors.
These are the errors I'm getting after I have executed the java codes below.

/Deposit.java:15: error: '.class' expected
    double results=presentValue(double f, double r ,int n);
                                       ^
/Deposit.java:15: error: ';' expected
    double results=presentValue(double f, double r ,int n);
                                        ^
/Deposit.java:15: error: <identifier> expected
    double results=presentValue(double f, double r ,int n);
                                                    ^
/Deposit.java:15: error: ';' expected
    double results=presentValue(double f, double r ,int n);
                                                         ^
4 errors

import javax.swing.JOptionPane;

/*This program computes a customers present
deposit to make to obtain a desired future
value
*/
public class Deposit
{
  //Main method
  public static void main(String[] args)
  {

    //Calling the present value method
    double results=presentValue(double f, double r ,int n);

    //Displaying the present value 
    JOptionPane.showMessageDialog(null, "You have to deposit: $" +results);
  }

  public static double presentValue(double f, double r, int n)
  {
    //Declaring the input variable
    String input;

    //Taking inputs from the customer
    //Future value
    input = JOptionPane.showInputDialog("Enter your desired future value:");
    f = Double.parseDouble(input);

    //Annual Interest Rate
    input = JOptionPane.showInputDialog("Enter the annual interest rate:");
    r = Double.parseDouble(input);

    //Number of years
    input = JOptionPane.showInputDialog("Enter the number of years:");
    n = Integer.parseInt(input);

    //Calculating the present value the customer has to deposit
    double p = f/Math.pow((1+r), n);

    //Returning the value to the present value method
    return p;

    System.exit(0);
  }
}

Solution

Go with function without arguments, since yours doesn't do anything.

public class Deposit
{
  //Main method
  public static void main(String[] args)
  {
    double results=presentValue();
    ... // same code
  }

  public static double presentValue()
  {
    double f,r;
    int n;
    ... // same code
  }
}


Answered By - sittsering
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing