PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 22, 2022

[FIXED] How can I solve the error -- error: invalid types ‘int[int]’ for array subscript?

 December 22, 2022     arrays, c++, error-handling, syntax     No comments   

Issue

#include <iostream>
#include <iomanip>
using namespace std;
int col=10;
int row=0;
void avg(int * ar,int row, int col)
{ 
    float size= row * col;
    int sum=0, ave;
    for(int i=0; i<row; i++)
    {
        for(int j=0; j<col; j++){
        
        sum+=ar[i][j];
        cout<<sum;}
        
    }
    ave=sum/size;
    cout<<sum<<endl;
    cout<<ave;

}

int main()
{
    int row, col;
    cout<<"How many rows does the 2D array have: ";
    cin>>row;
    cout<<"How many columns does the 2D array have: ";
    cin>>col;
    int ar[row][col];
    cout<<"Enter the 2D array elements below : \n";
    for(int i=0; i<row; i++){
        cout<<"For row "<<i + 1<<" : \n";
        for(int j=0; j<col; j++)
        cin>>ar[i][j];
    }
    cout<<"\n Array is: \n";
    for(int i=0; i<row; i++)
    {
        for(int j=0; j<col; j++)
        
            cout<<setw(6)<<ar[i][j];
        
        cout<<endl;
        
    }
  
    cout<<"\nAverage of all the elements of the given D array is: \n";
    avg((int*)ar,row,col);
    
    return 0;
}

Hi there, I have written this code to calculate the average of the elements of an 2D array. I am getting error while trying to access the array elements of a 2D array at line 12 -13 ar[i][j]

The error says- error: invalid types ‘int[int]’ for array subscript

How can I solve this error?

PS: I want to give row( no. of rows in 2D array) and col(no. of columns in 2D array) in the function parameter to make this more dynamic.


Solution

Your function parameter ar is a int*. But when you wrote sum+=ar[i][j] you're subscripting it as if we had a 2D array. You can only subscript it for one dimension like arr[i].

Additionally, row and col are not constant expressions. And in Standard C++ the size of an array must be a compile time constant(constant expression). So,

int ar[row][col]; //this statement is not standard c++

The above statement is not standard c++.

A better way(to avoid these problems) would be to use a 2D std::vector instead of a 2D array as shown below.

#include <iostream>
#include <iomanip>
#include <vector>

//this function takes a 2D vector by reference and returns a double value
double avg(const std::vector<std::vector<int>> &arr)
{ 
    int sum=0;
    for(const std::vector<int> &tempRow: arr)
    {
        for(const int &tempCol: tempRow){
        
        sum+=tempCol;
        //std::cout<<sum;
            
        }
        
    }
    
    return (static_cast<double>(sum)/(arr.at(0).size() * arr.size()));
  

}

int main()
{
    int row, col;
    std::cout<<"How many rows does the 2D array have: ";
    std::cin>>row;
    std::cout<<"How many columns does the 2D array have: ";
    std::cin>>col;
    
    //create a 2D vector instead of array
    std::vector<std::vector<int>> ar(row, std::vector<int>(col));
    
    std::cout<<"Enter the 2D array elements below : \n";
    for(auto &tempRow: ar){
        
        for(auto &tempCol: tempRow){
        std::cin>>tempCol;
        }
    }
    std::cout<<"\n Array is: \n";
    for(auto &tempRow: ar)
    {
        for(auto &tempCol: tempRow)
        
            std::cout<<std::setw(6)<<tempCol;
        
        std::cout<<std::endl;
        
    }
  
    std::cout<<"\nAverage of all the elements of the given D array is: \n";
    std::cout<<avg(ar);
    
    return 0;
}

The output of the above program can be seen here.



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

[FIXED] How do I perform a GROUP BY on an aliased column in SQL Server?

 December 22, 2022     sql, sql-server, syntax, tsql     No comments   

Issue

I'm trying to perform a group by action on an aliased column (example below) but can't determine the proper syntax.

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY     'FullName'

What is the correct syntax?

Extending the question further (I had not expected the answers I had received) would the solution still apply for a CASEed aliased column?

SELECT       
    CASE
        WHEN LastName IS NULL THEN FirstName
        WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
    END AS 'FullName'
FROM         customers
GROUP BY     
    LastName, FirstName

And the answer is yes it does still apply.


Solution

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName


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

[FIXED] How to do complex conditionals in Bash (mix of 'and' &&, 'or' || ...)

 December 22, 2022     bash, conditional-statements, syntax     No comments   

Issue

How do I accomplish something like the following in Bash?

if ("$a" == "something" || ($n == 2 && "$b" == "something_else")); then
  ...
fi

Solution

You almost got it:

if [[ "$a" == "something" || ($n == 2 && "$b" == "something_else") ]]; then

In fact, the parentheses can be left out because of operator precedence, so it might also be written as

if [[ "$a" == "something" || $n == 2 && "$b" == "something_else" ]]; then


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

[FIXED] What difference between passing an instance and a brace-enclosed initializer list to a function?

 December 22, 2022     c++, syntax     No comments   

Issue

Say I have the following code.

class A
{
public:
    float x, y, z;
    A(float x, float y, float z) : x(x), y(y), z(z) {}
};

float average(A a)
{
    return (a.x + a.y + a.z) / 3;
}

Are there any practical differences between calling the function in these two ways?

// a)
average(A(1, 2, 3))

// b)
average({1, 2, 3})

Solution

It depends on the C++ version you are using.

Copied (and sligthly modified) from copy elision @ cpprefrence (so, not an exact quote):

In C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from.

This means that the temporary A you visually show in average(A(1, 2, 3)) is not allowed to be copied or moved since C++17. In fact, there is no temporary. Before C++17, most compilers utilized copy (and move) elision (that has been allowed earlier too, but it wasn't mandatory) to the same effect - but you could not portably rely on it.

In C++17, this form of copy elision was made mandatory and is since called Return Value Optimization, or RVO for short. You will also read about Named RVO (or NRVO), which is similar, but does not follow the same rules. It's a bit more complicated and outside the scope of this answer.

Before C++17, average(A(1, 2, 3)) could actually mean that a temporary instance of A is created and that the move or copy constructor of the A in the function would have to move (or for a non-movable, copy) the resources from that temporary - which is usually cheap, but doesn't have to be - and it could come with side effects.

Some types are neither copyable nor movable. In such cases, the call would not be valid before C++17. In C++17, deleted move and copy constructors does not matter in this case since there is no instance to move or copy from - and the call is therefore undoubtedly valid.

When using the brace enclosed initializer list, as you do in this example, not even C++11 is allowed to create (and move) a temporary instance of A. The values are passed directly to the constructor in A(float x, float y, float z).

Other that that, I can't spot a difference in your example.



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

[FIXED] What difference between passing an instance and a brace-enclosed initializer list to a function?

 December 22, 2022     c++, syntax     No comments   

Issue

Say I have the following code.

class A
{
public:
    float x, y, z;
    A(float x, float y, float z) : x(x), y(y), z(z) {}
};

float average(A a)
{
    return (a.x + a.y + a.z) / 3;
}

Are there any practical differences between calling the function in these two ways?

// a)
average(A(1, 2, 3))

// b)
average({1, 2, 3})

Solution

It depends on the C++ version you are using.

Copied (and sligthly modified) from copy elision @ cpprefrence (so, not an exact quote):

In C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from.

This means that the temporary A you visually show in average(A(1, 2, 3)) is not allowed to be copied or moved since C++17. In fact, there is no temporary. Before C++17, most compilers utilized copy (and move) elision (that has been allowed earlier too, but it wasn't mandatory) to the same effect - but you could not portably rely on it.

In C++17, this form of copy elision was made mandatory and is since called Return Value Optimization, or RVO for short. You will also read about Named RVO (or NRVO), which is similar, but does not follow the same rules. It's a bit more complicated and outside the scope of this answer.

Before C++17, average(A(1, 2, 3)) could actually mean that a temporary instance of A is created and that the move or copy constructor of the A in the function would have to move (or for a non-movable, copy) the resources from that temporary - which is usually cheap, but doesn't have to be - and it could come with side effects.

Some types are neither copyable nor movable. In such cases, the call would not be valid before C++17. In C++17, deleted move and copy constructors does not matter in this case since there is no instance to move or copy from - and the call is therefore undoubtedly valid.

When using the brace enclosed initializer list, as you do in this example, not even C++11 is allowed to create (and move) a temporary instance of A. The values are passed directly to the constructor in A(float x, float y, float z).

Other that that, I can't spot a difference in your example.



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

[FIXED] What does it mean to pass `_` (i.e., underscore) as the sole parameter to a Dart language function?

 December 22, 2022     dart, syntax     No comments   

Issue

I'm learning Dart and see the following idiom a lot:

someFuture.then((_) => someFunc());

I have also seen code like:

someOtherFuture.then(() => someOtherFunc());

Is there a functional difference between these two examples? A.k.a., What does passing _ as a parameter to a Dart function do?

This is particularly confusing given Dart's use of _ as a prefix for declaring private functions.


Solution

It's a variable named _ typically because you plan to not use it and throw it away. For example you can use the name x or foo instead. The difference between (_) and () is simple in that one function takes an argument and the other doesn't.

DON’T use a leading underscore for identifiers that aren’t private.

Exception: An unused parameter can be named _, __, ___, etc. This happens in things like callbacks where you are passed a value but you don’t need to use it. Giving it a name that consists solely of underscores is the idiomatic way to indicate the value isn’t used.

https://dart.dev/guides/language/effective-dart/style



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

[FIXED] What does %>% function mean in R?

 December 22, 2022     dplyr, magrittr, r, r-faq, syntax     No comments   

Issue

I have seen the use of %>% (percent greater than percent) function in some packages like dplyr and rvest. What does it mean? Is it a way to write closure blocks in R?


Solution

%...% operators

%>% has no builtin meaning but the user (or a package) is free to define operators of the form %whatever% in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.

"%,%" <- function(x, y) paste0(x, ", ", y)

# test run

"Hello" %,% "World"
## [1] "Hello, World"

The base of R provides %*% (matrix mulitiplication), %/% (integer division), %in% (is lhs a component of the rhs?), %o% (outer product) and %x% (kronecker product). It is not clear whether %% falls in this category or not but it represents modulo.

expm The R package, expm, defines a matrix power operator %^%. For an example see Matrix power in R .

operators The operators R package has defined a large number of such operators such as %!in% (for not %in%). See http://cran.r-project.org/web/packages/operators/operators.pdf

igraph This package defines %--% , %->% and %<-% to select edges.

lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .

Pipes

magrittr In the case of %>% the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html

magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%, %<>% and %$% and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.

dplyr The dplyr R package used to define a %.% operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>% which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>% : Differences between %.% (dplyr) and %>% (magrittr)

pipeR The R package, pipeR, defines a %>>% operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/

The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf

postlogic The postlogic package defined %if% and %unless% operators.

wrapr The R package, wrapr, defines a dot pipe %.>% that is an explicit version of %>% in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%. See https://winvector.github.io/wrapr/articles/dot_pipe.html

Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:

1:8 %>% sum %>% sqrt
## [1] 6

one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.) . We follow that with a semicolon.

1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6

Update Added info on expm package and simplified example at top. Added postlogic package.

Update 2 The development version of R has defined a |> pipe. Unlike magrittr's %>% it can only substitute into the first argument of the right hand side. Although limited, it works via syntax transformation so it has no performance impact.



Answered By - G. Grothendieck
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does ${ } mean in PHP syntax?

 December 22, 2022     php, syntax     No comments   

Issue

I have used PHP for a long time, but I just saw something like,

${  } 

To be precise, I saw this in a PHP Mongo page:

$m = new Mongo("mongodb://${username}:${password}@host");

So, what does ${ } do? It is quite hard to search with Google or in the PHP documentation for characters like $, { and }.


Solution

${ } (dollar sign curly bracket) is known as Simple syntax.

It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.


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

[FIXED] How to convert this function from javascript to python?

 December 22, 2022     function, javascript, python, syntax, syntax-error     No comments   

Issue

Does anybody know how to convert this javascript function to python ?

javascript:

function ding(t, a, e, n) {
  return t > a && t <= e && (t += n % (e - a)) > e && (t = t - e + a), t
}

This is my try on doing so:

def ding(t, a, e, n):
    return t > a and t <= e and (t + n % (e - a)) > e and (t = (t - e + a)), t

It returns a syntax error at the "=" in (t = (t - e + a)) and idk how to solve this right.

When giving it these values: ding(53, 47, 57, 97) it should return 50 in the original javascript function.


Solution

Does it have to be a one-liner? Why not just split it into a few lines:

def ding(t, a, e, n):
    if t > a and t <= e:
        t += n % (e - a)

        if t > e:
            t -= e - a
    
    return t
    
print(ding(53, 47, 57, 97)) # 50


Answered By - lusc
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is "0is" notation in Rust?

 December 22, 2022     rust, rust-obsolete, syntax     No comments   

Issue

As seen in this repository:

https://github.com/ReactiveX/RxRust/blob/master/src/lib.rs#L110

let gen = move |:| {
    let it = range(0is, 20is);
    //             ~~~  ~~~~
    let q   = Box::new(Decoupler::new(dtx.clone()));
    let mut map1 = Box::new(Map::new(|i : isize| {i * 10}));
    let mut map2 = Box::new(Map::new(|i : isize| {i + 2}));
    let mut iter = Box::new(IterPublisher::new(it));


    map2.subscribe(q);
    map1.subscribe(map2);
    iter.subscribe(map1);
};

(squiggly emphasis mine)

I'm trying to figure out what is after a numeral is. The Book says about literal suffixes only briefly:

Note that all number literals except the byte literal allow a type suffix, such as 57u8, and _ as a visual separator, such as 1_000.

— https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types

And the compiler (1.53) only understands a set of specific suffixes, so I could not even get the original crate built on my machine:

invalid suffix `is`
help: the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)

Is it some sort of archaic syntax, or is it me missing something?


Solution

In the old, pre 1.0, times, integer suffixes were a little different.

Thanks to the Wayback Machine, we can take a peek to the past:

There are 10 valid values for an integer suffix: \

  • The is and us suffixes give the literal type isize or usize, respectively.
  • Each of the signed and unsigned machine types u8, i8, u16, i16, u32, i32, u64 and i64 give the literal the corresponding machine type.

But in Rust 1.0 the first bullet went away and now you write 20isize instead of 20is.



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

[FIXED] What does 'wb' mean in this code, using Python?

 December 22, 2022     file, python, syntax     No comments   

Issue

Code:

file('pinax/media/a.jpg', 'wb')

Solution

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.



Answered By - YOU
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check TypeScript code for syntax errors from a command line?

 December 22, 2022     compilation, syntax, syntax-checking, typescript, verification     No comments   

Issue

I have a code that generates TypeScript classes, and as a build/test step, I would like to check the generated files for syntax correctness.

I have looked at TypeScript compiler options but see no such option.

  • How can I check the syntax?

I don't want a full compilation because the referred types are not reachable at that build step (they are in a different module to which the generated sources are added later).


Solution

If its just syntax checking you are after then you can use a linter like tslint which can be run from the command line or via many build tools



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

[FIXED] When to use : and = in javascript?

 December 22, 2022     function, javascript, object, syntax, typescript     No comments   

Issue

I have these code snippet.

 const initialAuthState = {
  isAuthenticated:false
};

and

function login(state){
      state.isAuthenticated=true;
    }

How do I know when to use '=' and when to use ':' in javascript?


Solution

= inside a function or code block (like inside an if/else/for/while etc.), : inside of objects.



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

[FIXED] How to select and view only a specific cell?

 December 22, 2022     excel, syntax, xpath     No comments   

Issue

I want to extract from the next code, only the first value. Unfortunately, I was unable and I didn't found similar answer for my question. So, here is the example of script:

**$1.61**

With bold I mark the value which I am interested to be visible. Only this value in one cell. Unfortunately I didn't have need the rest of values from table.

Here I will add my function (function will be use ):

=importxml("https://www.coingecko.com/en/coins/polygon","//td/span")

Please let me know how how to select to view only 1st line/value.

Thanks to all for support.


Solution

This should select 1st //td/span

=importxml("https://www.coingecko.com/en/coins/polygon","(//td/span)[1]")

Reference

https://librarycarpentry.org/lc-webscraping/02-xpath/index.html



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

[FIXED] what is the right way to check that an object is not null in react before assigning one of its properties to a variable

 December 22, 2022     javascript, reactjs, syntax     No comments   

Issue

In React it is very commong that as components get updated objects go from null to their intended content. This is a dynamic process that can create errors everytime you assing a property from those objects to another variable.

Lets say that user is the object that will go from null to the actual user object and that I want to extract the property uid from user:

const uid = user.uid

This can trigger a fatal error in react if user is null when I try to execute this operation.

I have tried to use:

user && const uid = user.uid, but it doesn't work at all.

Would the right way to do this be:

const uid = user && user.uid

any comments/ sugestions?


Solution

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined

So do this

const uid = user?.uid // will be undefined if not there else the actually value


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

[FIXED] How to swap text based on patterns at once with sed?

 December 22, 2022     replace, sed, syntax     No comments   

Issue

Suppose I have 'abbc' string and I want to replace:

  • ab -> bc
  • bc -> ab

If I try two replaces the result is not what I want:

echo 'abbc' | sed 's/ab/bc/g;s/bc/ab/g'
abab

So what sed command can I use to replace like below?

echo abbc | sed SED_COMMAND
bcab

EDIT: Actually the text could have more than 2 patterns and I don't know how many replaces I will need. Since there was a answer saying that sed is a stream editor and its replaces are greedily I think that I will need to use some script language for that.


Solution

Maybe something like this:

sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g'

Replace ~ with a character that you know won't be in the string.



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

Wednesday, December 21, 2022

[FIXED] How to copy a map in golang?

 December 21, 2022     dictionary, go, syntax     No comments   

Issue

I can offer decomposition of map to 2 slices example:

func decomposeMap(m map[string]int) ([]string, []int) {
  var i uint
  l := len(m)
  keys, values := make([]string, l), make([]int, l)
  for keys[i], values[i] = range m {
    i++
  }
  return keys, values
}

but I am failing to write map copying:

func copyMap(m map[string]int) map[string]int {
  m2 := make(map[string]int, len(m))
  for id, m2[id] = range m {} // error - id is not declared
  for id, m2[id] := range m {} // error with m2[id] already declared
  // id should not be accessible here, it should exist only inside loop
  return m2
}

I can declare id as a var, but I dont want it to be available outside for loop. How can i mix assigment and declaration, eg: for id:=, m[id]= range m {} ? So it will declare index just inside for loop, and will be not accessible outside?


Solution

The id variable must be declared before for, because you can't use short variable declaration with m2[id].

func copyMap(m map[string]int) map[string]int {
    m2 := make(map[string]int, len(m))
    var id string
    for id, m2[id] = range m {
    }
    return m2
}

But! This won't duplicate the map! The key is only assigned to id after m2[id] is already evaluated, so this loop will assign values to keys of the previous iteration, this is not duplicating, this is "shuffling"!

This is basically a tuple assignment (key and value are assigned to id, m2[id]). Spec: Assignments:

The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

So first id and m2[id] are evaluated (including the index expression), so id is not "yet" changed, so the value from the previous iteration is used, and only after this are the new key and values assigned.

To demonstrate, see:

m := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}
m2 := copyMap(m)
fmt.Println(m2)

Output (try it on the Go Playground):

map[:1 one:2 two:3]

The values are assigned to different keys (different than in the source map), and one value is assigned to the empty string key in the first iteration (the default, zero value of id).

To duplicate the map, simply use:

for id, v := range m {
    m2[id] = v
}

Or if you want to avoid the temporary assignment:

for id := range m {
    m2[id] = m[id]
}


Answered By - icza
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to escape single quotes within single quoted strings

 December 21, 2022     bash, quoting, syntax     No comments   

Issue

Let's say, you have a Bash alias like:

alias rxvt='urxvt'

which works fine.

However:

alias rxvt='urxvt -fg '#111111' -bg '#111111''

won't work, and neither will:

alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''

So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?

alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''

seems ungainly although it would represent the same string if you're allowed to concatenate them like that.


Solution

If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:

 alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
 #                     ^^^^^       ^^^^^     ^^^^^       ^^^^
 #                     12345       12345     12345       1234

Explanation of how '"'"' is interpreted as just ':

  1. ' End first quotation which uses single quotes.
  2. " Start second quotation, using double-quotes.
  3. ' Quoted character.
  4. " End second quotation, using double-quotes.
  5. ' Start third quotation, using single quotes.

If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.



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

[FIXED] Why should I use a semicolon after every function in javascript?

 December 21, 2022     javascript, syntax     No comments   

Issue

I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?

function weLikeSemiColons(arg) {
   // bunch of code
};

or

function unnecessary(arg) {
  // bunch of code
}

Solution

Semicolons after function declarations are not necessary.

The grammar of a FunctionDeclaration is described in the specification as this:

function Identifier ( FormalParameterListopt ) { FunctionBody }

There's no semicolon grammatically required, but might wonder why?

Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.

FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.

The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.

However, semicolons are always recommended where you use FunctionExpressions. For example:

var myFn = function () {
  //...
};

(function () {
  //...
})();

If you omit the semicolon after the first function in the above example, you will get completely undesired results:

var myFn = function () {
  alert("Surprise!");
} // <-- No semicolon!

(function () {
  //...
})();

The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.

Recommended lectures:

  • Named function expressions demystified (great article)
  • Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)


Answered By - Christian C. Salvadó
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to concatenate strings in twig

 December 21, 2022     string-concatenation, syntax, templating, twig     No comments   

Issue

Anyone knows how to concatenate strings in twig? I want to do something like:

{{ concat('http://', app.request.host) }}

Solution

This should work fine:

{{ 'http://' ~ app.request.host }}

To add a filter - like 'trans' - in the same tag use

{{ ('http://' ~ app.request.host) | trans }}

As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:

{{ "http://#{app.request.host}" }}


Answered By - Alessandro Desantis
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why don't associated types for protocols use generic type syntax in Swift?

 December 21, 2022     generics, oop, swift, syntax     No comments   

Issue

I'm confused about the difference between the syntax used for associated types for protocols, on the one hand, and generic types on the other.

In Swift, for example, one can define a generic type using something like

struct Stack<T> {
    var items = [T]()
    mutating func push(item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}

while one defines a protocol with associated types using something like

protocol Container {
    associatedtype T
    mutating func append(item: T)
    var count: Int { get }
    subscript(i: Int) -> T { get }
}

Why isn't the latter just:

protocol Container<T> {
    mutating func append(item: T)
    var count: Int { get }
    subscript(i: Int) -> T { get }
}

Is there some deep (or perhaps just obvious and lost on me) reason that the language hasn't adopted the latter syntax?


Solution

This has been covered a few times on the devlist. The basic answer is that associated types are more flexible than type parameters. While you have a specific case here of one type parameter, it is quite possible to have several. For instance, Collections have an Element type, but also an Index type and a Generator type. If you specialized them entirely with type parameterization, you'd have to talk about things like Array<String, Int, Generator<String>> or the like. (This would allow me to create arrays that were subscripted by something other than Int, which could be considered a feature, but also adds a lot of complexity.)

It's possible to skip all that (Java does), but then you have fewer ways that you can constrain your types. Java in fact is pretty limited in how it can constrain types. You can't have an arbitrary indexing type on your collections in Java. Scala extends the Java type system with associated types just like Swift. Associated types have been incredibly powerful in Scala. They are also a regular source of confusion and hair-tearing.

Whether this extra power is worth it is a completely different question, and only time will tell. But associated types definitely are more powerful than simple type parameterization.



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

[FIXED] How to print a variable within an array using its index

 December 21, 2022     arrays, python, syntax, variables     No comments   

Issue

I am practicing with for in loops and having trouble with this.

places = ["phuket", "athens", "doha"]

for places in range(5):
    if places == 0:
        print("thailand," + places 0 + "is a cool place")
    else:
        print("not thailand")

When I try this, I get a syntax error with 'places 0'. I want it to print thailand, phuket, is a cool place. But no matter how I seem to format places 0 (with the 0 in [], with it in ()) I just keep getting syntax errors.


Solution

If you use enumerate you can get the index of the for loop. i will be 0, 1, 2 and place will be phuket, athens, doha. And you can use different logic depends on what you want.

places = ["phuket", "athens", "doha"]

for i,place in enumerate(places):
    if i == 0:
        print("thailand," + place + "is a cool place")
    else:
        print("not thailand")

You can understand more here - https://realpython.com/python-enumerate/



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

[FIXED] What is the difference between '/' and '//' when used for division?

 December 21, 2022     floor-division, math, operators, python, syntax     No comments   

Issue

Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2

Solution

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at PEP 238: Changing the Division Operator.



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

[FIXED] What is the equivalent of the Bash ` (backquote/backtick) in Windows PowerShell?

 December 21, 2022     powershell, syntax     No comments   

Issue

I need the result of a command to be taken as a parameter in another command.

command /opt <another command output>

On Bash Linux I would do

command /opt `another command`

What is the equivalent of the ` symbol that works in Windows Terminal?

In particular, I am using the command

'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}

where findstr is the windows equivalent to grep and the final command in the pipe is the equivalent to sed. The output of this command will be 1, 2 or 3, and I need this to be passed to the %HERE in the following line

'C:\Program Files\Display\display64.exe' /device %HERE /rotate 90

The following minimal example, does not work:

FOR /F %a in ('"C:\Program Files\Display\display64.exe"  /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}') do echo "%a"

What I am doing wrong? (I am new in Windows).


Solution

Use (...), the grouping operator to pass output from a command as an argument to another command:

'C:\Program Files\Display\display64.exe' /device (
  'C:\Program Files\Display\display64.exe' /listdevices | findstr 22MP55 | %{$_ -replace "- .*",""}
) /rotate 90

Note: $(...), the subexpression operator, works too, but (...) is usually sufficient and has no side effects; you only need $(...) for multiple (;-separated) statements - see this answer for details.


As for what you tried:

  • In POSIX-compatible shells such as Bash, `...` is the legacy form of a command substitution whose modern syntax is $(...) - while PowerShell supports $(...) too, (...) is usually preferable, as noted.

  • In PowerShell, ` serves as the escape character (only), analogous to \ in POSIX-compatible shells - see the conceptual about_Special_Characters help topic.

  • Your attempts to use FOR /F %a in ... and %HERE (which should be %HERE%) relate to the legacy cmd.exe shell on Windows, not to its successor, PowerShell, whose syntax differs fundamentally.



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

[FIXED] How do I modify a MySQL column to allow NULL?

 December 21, 2022     alter, mysql, syntax     No comments   

Issue

MySQL 5.0.45

What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this:

ALTER mytable MODIFY mycolumn varchar(255) null;

I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.


Solution

You want the following:

ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

Columns are nullable by default. As long as the column is not declared UNIQUE or NOT NULL, there shouldn't be any problems.



Answered By - Daniel Spiewak
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use locals in terraform to repeat and merge blocks?

 December 21, 2022     syntax, terraform     No comments   

Issue

I have multiple docker_container resources:

resource "docker_container" "headerdebug" {
  name  = "headerdebug"
  image = "${docker_image.headerdebug.latest}"

  labels {
    "traefik.frontend.rule" = "Host:debug.in.bb8.fun"
    "traefik.port" = 8080
    "traefik.enable" = "true"
    "traefik.frontend.passHostHeader" = "true"
    "traefik.frontend.headers.SSLTemporaryRedirect" = "true"
    "traefik.frontend.headers.STSSeconds" = "2592000"
    "traefik.frontend.headers.STSIncludeSubdomains" = "false"
    "traefik.frontend.headers.customResponseHeaders" = "${var.xpoweredby}"
    "traefik.frontend.headers.customFrameOptionsValue" = "${var.xfo_allow}"
  }
}

And another one:

resource "docker_container" "cadvisor" {
  name  = "cadvisor"
  image = "${docker_image.cadvisor.latest}"

  labels {
    "traefik.frontend.rule" = "Host:cadvisor.bb8.fun"
    "traefik.port" = 8080
    "traefik.enable" = "true"
    "traefik.frontend.headers.SSLTemporaryRedirect" = "true"
    "traefik.frontend.headers.STSSeconds" = "2592000"
    "traefik.frontend.headers.STSIncludeSubdomains" = "false"
    "traefik.frontend.headers.contentTypeNosniff" = "true"
    "traefik.frontend.headers.browserXSSFilter" = "true"
    "traefik.frontend.headers.customFrameOptionsValue" = "${var.xfo_allow}"
    "traefik.frontend.headers.customResponseHeaders" = "${var.xpoweredby}"
  }
}

I'm trying to use locals to re-use the common labels between both the containers. I have the following local defined:

locals {
  traefik_common_labels {
    "traefik.frontend.passHostHeader" = "true"
    "traefik.frontend.headers.SSLTemporaryRedirect" = "true"
    "traefik.frontend.headers.STSSeconds" = "2592000"
    "traefik.frontend.headers.STSIncludeSubdomains" = "false"
    "traefik.frontend.headers.customResponseHeaders" = "${var.xpoweredby}"
    "traefik.frontend.headers.customFrameOptionsValue" = "${var.xfo_allow}"
  }
}

But the documentation doesn't mention how to use locals for merging entire blocks, only maps.

I've tried the following:

labels "${merge(
    local.traefik_common_labels,
    map(
      "traefik.frontend.rule", "Host:debug.in.bb8.fun",
      "traefik.port", 8080,
      "traefik.enable", "true",
    )
  )}"

which gives the following error:

tf11 plan

Error: Failed to load root config module: Error loading modules: module docker: Error parsing .terraform/modules/2f3785083ce0d0ac2dd3346cf129e795/main.tf: key 'labels "${merge(
    local.traefik_common_labels,
    map(
      "traefik.frontend.rule", "Host:debug.in.bb8.fun",
      "traefik.port", 8080,
      "traefik.enable", "true",
    )
  )}"' expected start of object ('{') or assignment ('=')

There is a pretty diff of my attempts at this PR: https://git.captnemo.in/nemo/nebula/pulls/4/files


Solution

In Terraform 1.x+ you can use a dynamic block to achieve this

variable "xpoweredby" { default = "" }
variable "xfo_allow" { default = "" }

locals {
  traefik_common_labels = {
    "traefik.frontend.passHostHeader"                  = "true"
    "traefik.frontend.headers.SSLTemporaryRedirect"    = "true"
    "traefik.frontend.headers.STSSeconds"              = "2592000"
    "traefik.frontend.headers.STSIncludeSubdomains"    = "false"
    "traefik.frontend.headers.customResponseHeaders"   = var.xpoweredby
    "traefik.frontend.headers.customFrameOptionsValue" = var.xfo_allow
  }
}

resource "docker_image" "cadvisor" {
  name = "google/cadvisor:latest"
}

resource "docker_container" "cadvisor" {
  name  = "cadvisor"
  image = docker_image.cadvisor.latest

  dynamic "labels" {
    for_each = merge(local.traefik_common_labels,
      {
        "traefik.frontend.rule" = "Host:debug.in.bb8.fun",
        "traefik.port"          = 8080,
        "traefik.enable"        = "true",
      }
    )

    content {
      label = labels.key
      value = labels.value
    }
  }
}

In Terraform 0.11 etc, this could be accomplised with the following:

You need to assign the value to labels like so

locals {
  traefik_common_labels {
    "traefik.frontend.passHostHeader"                  = "true"
    "traefik.frontend.headers.SSLTemporaryRedirect"    = "true"
    "traefik.frontend.headers.STSSeconds"              = "2592000"
    "traefik.frontend.headers.STSIncludeSubdomains"    = "false"
    "traefik.frontend.headers.customResponseHeaders"   = "${var.xpoweredby}"
    "traefik.frontend.headers.customFrameOptionsValue" = "${var.xfo_allow}"
  }
}

resource "docker_container" "cadvisor" {
  name  = "cadvisor"
  image = "${docker_image.cadvisor.latest}"

  labels = "${merge(
    local.traefik_common_labels,
    map(
      "traefik.frontend.rule", "Host:debug.in.bb8.fun",
      "traefik.port", 8080,
      "traefik.enable", "true",
    ))}"
}


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

[FIXED] What does an exclamation mark (!) before a statement do?

 December 21, 2022     jupyter-notebook, syntax     No comments   

Issue

I was trying to install the dark theme in Jupyter notebook by typing this in notebook

pip install jupyterthemes
jt -t chesterish

The first command worked but I got some error in the 2nd one. Then I wrote this

!jt -t chesterish

And it worked. What did the exclamation mark do?

P.S. I am extremely new to python, just started last week


Solution

Any command prepended by exclamation point is run by your operating system shell instead of python. jt is actually a separate app called by your shell.



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

[FIXED] What does "null!" default value of property mean?

 December 21, 2022     c#, operators, properties, syntax     No comments   

Issue

I have seen this below code in somewhere. There is a TodoItems property in the TodoContext class and it has a default value of "null!". I know this is a default value set for intended property but what does the exclamation mark(!) do at the end of the "null" value?

public class TodoContext : DbContext
{
    public TodoContext(DbContextOptions<TodoContext> options)
        : base(options)
    {
    }

    public DbSet<TodoItem> TodoItems { get; set; } = null!;
}

Solution

null! basically means null but the ! symbol suppresses the warning since your intentions are that it will be changed in a constructor or other places.



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

[FIXED] Why a new call of a method with exclamation mark affects all previous calls of that method?

 December 21, 2022     ruby, syntax     No comments   

Issue

I'm sorry if this is a duplicate - I couldn't find anything similar in the existing posts.

I understand the difference between methods like shuffle and shuffle!. However, I am confused why calling the method more than once would result in changing the variables of all objects that previously referred to it? I'd expect once we apply a method, that the variable gets a value and we're done with it. Not that it continues to refer to the method call and the argument passed and that it would get re-evaluated later on.

I thought it's best to demonstrate with an example:

irb(main):001:1* def shuffle(arr)
irb(main):002:1*   arr.shuffle!
irb(main):003:0> end
=> :shuffle
irb(main):004:0> arr = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):005:0> one = shuffle(arr)
=> [4, 2, 3, 1]
irb(main):006:0> two = shuffle(arr)
=> [1, 2, 4, 3]
irb(main):007:0> one
=> [1, 2, 4, 3]

So, here I'd expect one to stay [4, 2, 3, 1]. However, with each new call, all previous ones would get equated to the latest result of the method call. I realise it should have something to do with calling it with the same argument arr, but still doesn't quite make sense.


Solution

Array#shuffle! shuffles the array in-place and returns its receiver:

ary = [1, 2, 3, 4]
ary.equal?(ary.shuffle!) #=> true

Assigning the result from shuffle! to another variable doesn't change this. It merely results in two variables referring to the same array:

a = [1, 2, 3, 4]
b = a.shuffle!

a #=> [2, 4, 1, 3]
b #=> [2, 4, 1, 3]

a.equal?(b) #=> true

You probably want a new array. That's what Array#shuffle (without !) is for:

a = [1, 2, 3, 4]
b = a.shuffle

a #=> [1, 2, 3, 4]
b #=> [2, 4, 1, 3]

Even if shuffle returns the element in the original order, you'll get another array instance:

a = [1, 2, 3, 4]
b = a.shuffle until b == a

a #=> [1, 2, 3, 4]
b #=> [1, 2, 3, 4]

a.equal?(b) #=> false


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

[FIXED] Why does an exclamation mark before a variable return 'true' if the variable value is zero?

 December 21, 2022     javascript, operators, syntax, variables     No comments   

Issue

I looked a lot, but I couldn't find an answer for this especific case.

Why does this expression return true?

let variable = 0
!variable // true

I understand that the ! mark checks if a value is null or undefined, but in this case variable is defined. This is tricking me. Isn't 0 really considered a valid value?


Solution

! is known as the logical NOT operator. It reverses the boolean result of the operand (or condition)

0 is also considered as the boolean false, so when you use !variable you are using the logical operator and saying it to change the value of the variable to its opposite, that in boolean is true

0 == false == !1 == !true

1 == true == !0 == !false

in Javascript are considered false: false, null, undefined, "", 0, NaN

are considered true: true, 1, -0, "false". <- the last one is a not empty string, so its true

if( false || null || undefined || "" || 0 || NaN) //never enter
if( true && 1 && -1 && "false") //enter

https://developer.mozilla.org/en-US/docs/Glossary/Falsy



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

[FIXED] What is the := operator?

 December 21, 2022     colon-equals, operator-keyword, programming-languages, syntax     No comments   

Issue

In some programming languages, I see (ex.):

x := y

What is this := operator generally called and what does it do?


Solution

In all languages that support an operator := it means assignment.

  • In languages that support an operator :=, the = operator usually means an equality comparison.
  • In languages where = means assignment, == is typically used for equality comparison.

does := mean =?

I can't recall any languages where := means the same as =.


In MySQL := and = are both used for assignment, however they are not interchangeable and selecting the correct one depends on the context. To make matters more confusing the = operator is also used for comparison. The interpretation of = as either assignment or comparison also depends on context.



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

[FIXED] What is this Kotlin type: (String..String?)

 December 21, 2022     kotlin, kotlin-null-safety, nullable, syntax, types     No comments   

Issue

IntelliJ is showing me context hints that my variables are of type (String..String?). I cannot find any mention of it on the internet, what is this type?

enter image description here


Solution

(String..String?) represents a flexible type with lower bound String and upperbound String? (nullable string). This is not valid Kotlin code (it's not denotable) but it is used in the compiler internals and thus in IntelliJ's hints sometimes.

(On the JVM we often see platform types using ! as in String!, which are a more specific case of flexible types)

It's Kotlin's way of saying it doesn't know whether the String type declared for payload.email is nullable or not (for instance if this is declared in Java, which doesn't distinguish those), and yet it doesn't want to enforce either of those, for convenience (hence "flexible").

As the name suggests, flexible types are flexible — a value of type (L..U) can be used in any context, where one of the possible types between L and U is needed

This means that even though the actual type of the value is "somewhere between String and String?", values of this type can be used even in places expecting String, even though the real type of that value may be String? and thus the value could be null.

This is useful because assuming it is String would mean that null checks would be marked as redundant, and assuming it is String? would force the developer to write null checks everywhere, even though they might know that this particular Java method cannot return null.

In general, it's a good practice to explicitly declare the type of a variable that you get from Java, to avoid the propagation of the platform type and the uncertainty (and unsafety) that comes with it:

val email: String = payload.email // if you know it cannot be null
val email: String? = payload.email // if you don't know


Answered By - Joffrey
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you detect if a list has exactly 3 items in Haskell?

 December 21, 2022     haskell, list, syntax     No comments   

Issue

I have this but I got an error:

-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs   | [_ , _ , _] = True
          | otherwise = False

Solution

Pattern matching happens on the left side of the vertical bar. Thus:

test :: [Char] -> Bool
test [_, _, _] = True
test _         = False

As Norman Ramsey rightly notes below, the following code is not a robust alternative solution (because it is very inefficient when applied to (long) finite lists and does not halt on infinite lists) and should thus not be used:

test :: [Char] -> Bool
test xs = length xs == 3

Moreover, length xs == 0 should always be replaced with null xs.

Edit: the question which naturally arises is: how do we generalize this? What if we want to test whether a list has exactly n elements? What if the input may be infinite? Here's a solution where the cost is either n or the length of the list, whichever is smaller—and that's as efficient a solution, asymptotically, as we can possibly hope for:

hasLength :: Int -> [a] -> Bool
hasLength n []     = n == 0
hasLength 0 (x:xs) = False
hasLength n (x:xs) = hasLength (n-1) xs

Usage:

*Main> hasLength 3 [1..2]
False
*Main> hasLength 3 [1..3]
True
*Main> hasLength 3 [1..4]
False
*Main> hasLength 3 [1..] 
False

It is unsafe to call this function with a negative length; if the list is infinite, the function won't terminate, and if the list is finite, it will return False with cost proportional to the length of the list. An easy fix would be to check in advance (on the first call only) that n is nonnegative, but this fix would ugly up the code.



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

[FIXED] How do I syntax check a Bash script without running it?

 December 21, 2022     bash, gnu, linux, syntax, unix     No comments   

Issue

Is it possible to check a bash script syntax without executing it?

Using Perl, I can run perl -c 'script name'. Is there any equivalent command for bash scripts?


Solution

bash -n scriptname

Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello.



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

[FIXED] How do you say not equal to in Ruby?

 December 21, 2022     equals, ruby, syntax     No comments   

Issue

This is a much simpler example of what I'm trying to do in my program but is a similar idea. In an, if statement how do I say not equal to?

Is != correct?

def test
  vara = 1
  varb = 2
  if vara == 1 && varb != 3
    puts "correct"
  else
    puts "false"
  end
end

Solution

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.



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

[FIXED] How to change the colour of region/endregion in VS Code?

 December 21, 2022     customization, syntax, visual-studio-code     No comments   

Issue

Does anyone know how to change the colour of #region/#endregion? This is greyish in VS Community but not on VS Code.

Thank you in advance.


Solution

Because the terms #region/#endregion are part of a comment, looking at their scopes with the command Developer: Inspect TM Scopes gives you only a comment scope so if you change the comment scope by the following tokenColorCustomization:

"editor.tokenColorCustomizations": {
    "comments": "#ffa600b0"
}

will change all comments - probably not what you want. Plus you can only change the fontColor and fontStyle (like italics) there.

Better is using the extension Highlight to find, via a regex, what you want to highlight.

Using //#region - your language may have different comment indicators at the start. If so, modify the first capture group (//\\s*) below.

  "highlight.regexes": {

    "(//\\s*)(#region|#endregion)": [

      // the first capture group, the '//' uncolored here, but must have the entry below
      //  you could color those separately if you wish
      {},

      // capture group: #region or #endregion
      {
        // "overviewRulerColor": "#ffcc00",
        "backgroundColor": "#f00",
        "color": "#fff",
        // "fontWeight": "bold",
        "borderRadius": "3px",
      },
    ]
  }


Answered By - Mark
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, December 20, 2022

[FIXED] What happens when you run deprecated code in swift?

 December 20, 2022     deprecated, swift, syntax     No comments   

Issue

For example in iOS 10 there's UserNotifications framework. Prior to that you just have to use:

let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
 application.registerUserNotificationSettings(settings)
 application.registerForRemoteNotifications()

(I ran the code above on iOS 10 and nothing happened).

My generic question is: would running deprecated syntax crash all the time, just do nothing (as now) or how it treats is unknown?

I'm asking to get a better debugging understanding.


Solution

how it treats is unknown

Basically, that's right. It wouldn't crash, probably, but it isn't guaranteed to work either.

In the case of the UILocalNotification world, experience shows that if you link against iOS 10 your code won't work properly. You must switch over to the new UNUserNotificationCenter code.

But this is determined not by rule but by experimentation.

The one reliable general rule is that if something is deprecated for the current iOS version, don't use it. That is precisely what deprecation means.

Of course, if you want your code to link against iOS 10 but to run on both iOS 10 and iOS 9, say, you might have to include two completely different sets of code, taking advantage of Swift's if #available() syntax to respond to what system we're actually running under. In this particular case, you would have to do that in order to manage local notifications. But that is the price of progress. Apple (deliberately?) makes it hard for you to write backwards-compatible code.



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

[FIXED] What does the ampersand (&) before `self` mean in Rust?

 December 20, 2022     rust, syntax, variables     No comments   

Issue

I've seen this code in the Rust documentation:

fn eat(&self) {
    println!("{} is done eating.", self.name);
}

what does the & in &self mean?


Solution

This means you'll be passing in a reference to the object, as opposed to moving the object itself. It's important to distinguish this because if your function looked like:

fn eat(self) {
    println!("{} is done eating.", self.name);
}

and you tried calling it then using the variable after, you'd get an error

object = Foo::new();
object.eat();
object.something(); // error, because you moved object in eat

because when you don't specify &, rust moves the value into the function and your original binding no longer has ownership. check out this minimal example I created (playground version):

struct Foo {
    x : u32
}

impl Foo {

    fn eat(self) {
        println!("eating");
    }

    fn something(&self) {
        println!("else");
    }

}

fn main() {
    println!("Hello, world!");

    let g = Foo { x: 5 };
    g.eat();
    g.something();  // if this comes before eat, no errors because we arent moving
}

Now switch something to be called before eat. Because something only takes a reference, g still has ownership and you can continue on. eat on the other hand moves g and you no longer can use g.



Answered By - Syntactic Fructose
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

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