What is “fix” in Haskell? And why does “fix error” print an infinite string? And why also “take 10 $ fix error” does the same too?

Long story short, I was watching this lecture from Simon Peyton-Jones, and at the time 21:41 he shows a quote:

I was squashing a bug, got frustrated, and typed “fix error” in ghci…

And I tried.

Result:

λ> import Data.Function -- here is fix
λ> fix error
"*** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: *** Exception: and goes on like this towards infinity

At first, I simply thought what the heck does this fix do?

So I looked at some types

λ> :t error
error :: [Char] -> a
λ> :t fix
fix :: (a -> a) -> a

hence

λ> :t fix error
fix error :: [Char]

but clearly, this still didn’t tell me much about the result.

The even stranger thing is, though, that even take 10 $ fix error or length $ take 10 $ fix error is such a neverending output as the one above (except that the output of the latter, length …, lacks the initial ").

What am I looking at?


To be clear, at the moment I still don’t understand much out of the docs on hackage. Not that I have dedicated more than 3 minutes to it, but I’m still lost at the first line of it

 

 

Answer:

 

fix calculates a fixed point of a function; a fixed point is a value you can feed to the function for which it will produce exactly the same value as the result.

For example, if you have the function f _ = "hello" (or const "hello"), then a fixed point of this function is the string "hello". And indeed fix f is "hello".

Many functions have multiple fixed points, so the documentation for fix needs to specify which one it returns. For example:

g :: Integer -> Integer
g x
  | even x = x
  | otherwise = x + 1

Every even number is a fixed point of g, but fix g promises (by its type) to be a specific Integer. Which one?

The documentation says that fix produces the least fixed point, and further clarifies that this means the least defined value that is a fixed point of the input function. Note that “least defined” does not mean the smallest value that is defined, it means the value that has the minimum “definedness”. This is a technical area I’m not quite as on top of as I’d like to be, in an informal sense: values like 1 :: IntegerTrue()Just 'a' etc a fully defined, because you can evaluate them fully without hitting an error. Bottom values (undefinedlet x = x in x, etc) are completely undefined. In-between are values like 1 : 2 : undefined, where you can look at some structure without hitting an error, but there is a bottom somewhere inside.

So fix g is just bottom (GHC detected an infinite loop and aborted it, when I tried), because g undefined is an error (and all bottoms are “the same value” for this purpose).

This turns out to be the case for most simple functions you might write when playing around with fix. For any strict function (one which examines its argument in any way), bottom will be a fixed point and that’s the one fix will calculate. So why do we care about it?

fix is of great theoretical interest because you can use it to implement recursion in a language that lacks direct support for it. In recursive definitions like this:

sum :: [Integer] -> Integer
sum [] = 0
sum (x : xs) = x + sum xs

There’s actually something slightly impressive going on. You’re defining, but sum is in scope within its own definition. Implementing that feature is a bit more difficult than compiling definitions which only use pre-existing definitions. Let’s imagine we couldn’t do that, but we still want to write sum. You can do it like this:

sum' :: ([Integer] -> Integer) -> [Integer] -> Integer
sum' _ [] = 0
sum' rec (x : xs) = x + rec xs

sum = fix sum'

Now every definition only uses things that have previously been defined; there is no self-reference. Instead of calling itself directly sum' receives an extra argument which is the function it should call on the tail of the list. That function argument has to have the same type we originally wanted to give sum, which makes the type of sum' an instance of a -> a, so we can call fix on it. And it turns out the least fixed point of sum' is a functional equivalent to the original sum!

The way it does this is by generating an “infinitely nested” expression of the form sum' (sum' (sum' (sum' ...))) (this is basically the way it finds the fixed point of any function; the answer is already getting pretty long so I won’t go over why exactly this works here). Each sum' receives an argument that says what to do with the tail of the list; that argument is itself another call to sum' that needs an argument saying what to do with the tail of the original list, and that argument is another call to, and so on. Eventually (if the list is finite) we hit the base case for the empty list and don’t need the next level of nested sum' call, and thus it doesn’t matter that there is no end to the nested expression! (This wouldn’t work in an eagerly evaluated language, obviously)

This turns out to be a general pattern you can apply to translate direct recursion into the usage of fix.

So with that, all said, hopefully, you can see why fix error behaves the way it does. Willem Van Onsem’s answer is good here, so I won’t repeat it at length. But basically fix error has to come up with a string s such that error s is equivalent to s. This is, of course, impossible for any non-bottom string, since error always produces a bottom (that’s the whole point of it), so fix error has to be some form of the bottom. In searching for the fixed point it generates an infinitely nested expression error (error (error ...)), and when GHC is printing an error message which itself generates an error whose message is another error, etc, what you have seen is the output that gets produced.

Error in new.session() : Could not establish session after 5 attempts

I’ve been facing in R the error message Error in new.session() : Could not establish session after 5 attempts. for days using getSymbols of the quantmod package:

getSymbols(tick, from = date_from, to = date_to, warnings = FALSE, auto.assign = TRUE)

The same issue applies to: getSymbols(tick, from = date_from, to = date_to, warnings = FALSE, auto.assign = TRUE, src="yahoo")

 

Answer:

 

Update QuantMod and try again:

install.packages('quantmod')

This was a bug that was fixed very swiftly. Thank you Joshua Ulrich!


History (2022-04-29):

This was an issue on 2022-04-29 that Joshua Ulrich promptly published a fix for. You could install the patched version with:

remotes::install_github("joshuaulrich/quantmod@358-getsymbols-new.session")

But the changes are now into CRAN, so you should just be able to update QuantMod and continue with your day.

Link to fix: GitHub: joshuaulrich/quantmod@358-getsymbols-new.session

GitHub issue here.

MySQL installation on Ubuntu 20.04 error when using mysql_secure_installation

I’m trying to install MySQL on Ubuntu 20.04 and when I run the command sudo mysql_secure_installation, it fails with the error below:

… Failed! Error: SET PASSWORD has no significance for user ‘root’@’localhost’ as the authentication method used doesn’t store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.`

I have seen the documentation and I’m stuck on how I can solve this.

Any help will be appreciated.

 

Answer

 

Had the same error, solved it by running sudo mysql which logged me in as root without a password, then I ran ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';

Following this I was able to run mysql_secure_installation again and this time I got to choose to use existing password (the one I set with above SQL command).

However now I can no longer login without a password, running sudo mysql now denies root user access.

1 WARNING in child compilations (Use ‘stats.children: true’ resp. ‘–stats-children’ for more details)

How can I solve this warning when creating laravel project?

1 WARNING in child compilations (Use ‘stats.children: true’ resp. ‘–stats-children’ for more details)

Steps to replicate:

  1. composer create-project –prefer-dist laravel/laravel example
  2. cd example
  3. composer requires laravel/ui
  4. php artisan ui vue –auth
  5. npm install vue@next vue-router@next vue-loader@next
  6. npm install
  7. npm run dev

 

Answer

https://github.com/twbs/bootstrap/issues/36259 The color-adjust shorthand is currently deprecated and it depends on the autoprefixer@10.4.6.

I was able to fix this by reverting the autoprefixer package aswell as @Benno to version 10.4.5, run this:

npm install autoprefixer@10.4.5 –save-exact

importerror: attempted relative import with no known parent package

I want to import a function from another file in the same directory.

Sometimes it works for me  from .mymodule import myfunction but sometimes I get a:

SystemError: Parent module '' not loaded, cannot perform relative import

Sometimes it works with from mymodule import myfunction, but sometimes I also get a:

SystemError: Parent module '' not loaded, cannot perform relative import

I don’t understand the logic here and I couldn’t find any explanation. This looks completely random.

Could someone explain to me what’s the logic behind all this?

 

Answer:

 

unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that?

It’s quite common to have a layout like this…

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

…with a mymodule.py like this…

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

…a myothermodule.py like this…

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

…and a main.py like this…

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

…which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import…

from .mymodule import as_int

The way you’re supposed to run it is…

python3 -m mypackage.myothermodule

…but it’s somewhat verbose and doesn’t mix well with a shebang line like #!/usr/bin/env python3.

The simplest fix for this case, assuming the name mymodule is globally unique, would be to avoid using relative imports, and just use…

from mymodule import as_int

…although, if it’s not unique, or your package structure is more complex, you’ll need to include the directory containing your package directory in PYTHONPATH, and do it like this…

from mypackage.mymodule import as_int

…or if you want it to work “out of the box”, you can frob the PYTHONPATH in code first with this…

import sys
import os

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))

from mypackage.mymodule import as_int

It’s kind of a pain, but there’s a clue as to why in an email written by a certain Guido van Rossum…

I’m -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module’s directory, which I’ve always seen as an antipattern. To make me change my mind you’d have to convince me that it isn’t.

Whether running scripts inside a package is an antipattern or not is subjective, but personally, I find it really useful in a package I have that contains some custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame containing only that widget for testing purposes.

Python Math – TypeError: ‘NoneType’ object is not subscriptable

I’m making a small program for math (no particular reason, just kind of wanted to) and I ran into the error “TypeError: ‘NoneType’ object is not subscriptable.

I have never before seen this error, so I have no idea what it means.

import math

print("The format you should consider:")
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

print("Do not include the letters in the input, it automatically adds them")

v1 = input("Value 1: ")
v2 = input("Value 2: ")
v3 = input("Value 3: ")
v4 = input("Value 4: ")

lista = [v1, v3]
lista = list.sort(lista)

a = lista[1] - lista[0]

list = [v2, v4]
list = list.sort(list)

b = list[1] = list[0]

print str(a)+str("a")+str(" = ")+str(b)

The error:

Traceback (most recent call last):
  File "C:/Users/Nathan/Documents/Python/New thing", line 16, in <module>
    a = lista[1] - lista[0]
TypeError: 'NoneType' object is not subscriptable,

valueerror: too many values to unpack (expected 2)


Answer:

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don’t call your lists list. That clobbers the builtin list type.

Aside #2: I’m not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don’t know why you’re calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don’t want to get in the habit or you’ll wind up printing tuples, with extra parentheses. I admit that it’ll work well enough here, because if there’s only one element in the parentheses it’s not interpreted as a tuple, but it looks strange to the pythonic eye..

SyntaxError: Cannot use import statement outside a module

I’ve got an ApolloServer project that’s giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My “index.js” is:

require('dotenv').config()
import {startServer} from './server'
startServer()

And when I run it I get the error

SyntaxError: Cannot use import statement outside a module

Answer:

Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

Option 1

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

// package.json
{
  "type": "module"
}

Option 2

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

java eclipse error: javafx runtime components are missing, and are required to run this application

I have this classical issue: Using JavaFX 11 with OpenJDK 11 together with Eclipse IDE.

Error: JavaFX runtime components are missing, and are required to run this application

I have OpenJDK 11.0.2

dell@dell-pc:~$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
dell@dell-pc:~$ 

Answer:

Your problem is not compiling the project, but running it. Since your main is defined in your Application-extension, running the project will require JavaFX in your module path on startup.

So either outsource your main into a class different from your Application or add the JavaFX modules with VM arguments:

--module-path="<javafx-root>\lib" --add-modules="javafx.base,javafx.controls,..."

See this for some more info.

Errors such as: ‘Solving environment: failed with initial frozen solve. Retrying with flexible solve’ & ‘unittest’ tab

I am working with spyder – python. I want to test my codes. I have followed the pip install spyder-unittest and pip install pytest. I have restarted the kernel and restarted my MAC as well. Yet, the Unit Testing tab does not appear. Even when I drop down Run cannot find the Run Unit test. Does someone know how to do this?

So, I solved the issue by running the command:

conda config --set channel_priority false.

And then proceeded with the unittest download with the command run:

conda install -c spyder-ide spyder-unittest.

The first command run conda config --set channel_priority false may solve other issues such as:

Solving environment: failed with initial frozen solve. Retrying with flexible solve

The unauthenticated git protocol on port 9418 is no longer supported

I have been using GitHub actions for quite some time but today my deployments started failing. Below is the error from GitHub action logs

Command: git
Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
Directory: /home/runner/work/stackstream-fe/stackstream-fe
Output:
fatal: remote error: 
  The unauthenticated git protocol on port 9418 is no longer supported.

Upon investigation, it appears that the below section in my yml file is causing the issue.

    - name: Installing modules
      run: yarn install

Answer:

 

Try using the following command before installing:

git config --global url."https://".insteadOf git://

better use the reduced version git config --global url."https://github.com/".insteadOf git://github.com/