text:
Q: How to close UIWebView created programmatically? I have the following code to create UIWebView programmatically and create UIButton on top of it to close it. The creation is OK, but the problem I can't refer back to the created UIWebView to close it from the button!
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Close" forState:UIControlStateNormal];
button.frame = CGRectMake(80, 210, 160, 40);
[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[webView addSubview:button];

- (IBAction)close:(id)sender {
????
}

Thanks for your help in advance :)

A: In ViewController.m
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

// tag will be used to get this webview later
webView.tag=55;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(close:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Close" forState:UIControlStateNormal];
button.frame = CGRectMake(80, 210, 160, 40);
[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[webView addSubview:button];

- (IBAction)close:(id)sender {

    [[self.view viewWithTag:55] removeFromSuperview];

}

A: Keep your webView as an ivar of your UIViewController.
Right now you have it as a local variable to the method so you can't refer to it outside that method.  Instead, declare it in your interface section of your .h file and you'll be able to access it from all your class methods.
And don't forget to release it in your dealloc method!

A: The web view is the button's superview so you should be able to get it like this,
UIWebView * webView = [(UIButton *)sender superview];

Now you can do removeFromSuperview or something else to make it disappear.
Edit
- (IBAction)close:(id)sender {
    UIWebView * webView = [(UIButton *)sender superview];
    [webView removeFromSuperview];
}

A: -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    NSLog(@"%@",request.URL.absoluteString);
    NSString *absoluteUrl = [[request URL] absoluteString];
    if ([absoluteUrl isEqualToString:@"https://google.com/login?"]) {
        NSLog(@"move to another view or close the web view");
        [portfolioWebView removeFromSuperview];

        return NO;
    }

    return YES;
}


text:
Q: standard deviation and coefficient of varriation A sample of 18 employees at a company is monitored to see how long they break for lunch on a particular day. The following data is the lunch break (in minutes) for each worker: ,25 ,25 ,32 ,45 ,22 ,34 ,56 ,51 ,35 ,30 ,33 ,38 ,44 ,31 ,48 ,36 ,26 ,36 ; Question  The standard deviation (in minutes) for this data is: (a) 91.60 (b) 10.07 (c) 9.57 (d) 9.54 (e) 9.27

A: First, you will want to calculate the mean, $E(X)$, by adding together the values and dividing by 18.
The next step is to find the variance. For this you will want to calculate $E(X^2)$, which can be found by summing the squares of each value and dividing by 18.  In other words: $E(X^2)=(25^2+25^2+32^2+45^2+...)/18$
$Var=E(X^2)-E(X)^2$ and standard deviation is the square root of the variance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to understand the Whitney Embedding Theorem I am trying to understand the Whitney Embedding Theorem.
It says that any $n$-manifold that is closed and smooth can be embedded as a smooth $n$-submanifold of $R^{2n}$.
Take a complicated looking knot in $\Bbb{R}^3$. Clearly it is a $1$-manifold that is smooth and closed. Is it obvious that it can be embedded as a closed $1$-submanifold of $\Bbb{R}^2$?
I am trying to imagine it, but cannot seem to find an embedding.

A: You are mixing up the imbedding into $\mathbb{R}^3$ and its implication on the topology of the complement with the manifold itself. A smooth closed $1$-manifold can always be diffeomorphically mapped onto the unit circle in $\mathbb{R}^2$.
You will not be able to recover it's embedding into three space from this (the knot), but that's not what Whitneys theorem is about.


text:
Q: How do I get sed to print a range of lines until it sees two consecutive blank lines? I'd like to use a sed script like this
#n
/^TODO/,/^$/p

except that sed should stop printing the range after it comes across two consecutive blank lines, rather than just one blank line. Then it should continue scanning for the next range of interest. In other words, the end of range of interest is defined by two blank lines. I'm not even sure that an address range can handle this sort of requirement, so if there's another way to do this, please let me know.

A: This should stop when it encounters two consecutive blank lines regardless of the odd/even pairing of the blank lines with non-blank lines:
Don't print the two blank lines:
sed -n 'N;/^\n$/q;P;D'

Print one of them:
sed -n 'N;/^\n$/{P;q};P;D'

Print both of them:
sed -n 'N;/^\n$/{p;q};P;D'

Edit:
And here's how you'd make that work in your range:
sed -n '/^TODO/,${N;/^\n$/q;P;D}'

Edit 2:
Per dan's (the OP) comments and edited requirements, this seems to work to find the pattern in a range that ends in two blank lines, multiple times in a file:
sed -n '/^TODO/,/^$/{H;N;/^\n$/{b};p}'

A: This may work for you:
sed -n '/TODO/{:a;N;/\n\n$/s///p;Ta}' file

This will strictly adhere to the OP question and only print the range less the two newlines if each range includes two consecutive newlines.
If an end of file will also signify the end of such a range, use:
sed -n '/TODO/{:a;p;n;/^$/!ba;n;//b;x;p;x;ba}' file

N.B. The use of the hold space to supply a single blank line when it is not followed by another.

Also the first solution can print either two newlines:
sed -n '/TODO/{:a;N;/\n\n$/!ba;p}' file

Or one newline:
sed -n '/TODO/{:a;N;/\n\n$/s//\n/p;Ta}' file

A: Don't use an address range
Instead, look for the start of the TODO block, then loop until you find the pair of blank lines.
Here is a test file.  After that is a comparison of some of the proposed solutions.
cat >tricky_todo.txt <<EOF
TODO block 1 line 1 (last line)

THIS LINE SHOULDN'T BE PRINTED #1
THIS LINE SHOULDN'T BE PRINTED #2
TODO block 2 line 1
     block 2 line 2
     block 2 line 3
     block 2 line 4

     block 2 line 6
     block 2 line 7
     block 2 line 8 (last line)

TODO block 3 line 1
     block 3 line 2
     block 3 line 3
     block 3 line 4
     block 3 line 5 (last line)

TODO block 4 line 1
     block 4 line 2
     block 4 line 3
     block 4 line 4
     block 4 line 5 (last line)

THIS LINE SHOULDN'T BE PRINTED #3
THIS LINE SHOULDN'T BE PRINTED #4
EOF

Output from @Paused's sed script
Unfortunately it is pretty much impossible to get an address range to work for this task.  Too many unwanted lines, and not all of the wanted lines :-(
sed -n '/^TODO/,/^$/{H;N;/^\n$/{b};p}' <tricky_todo.txt

TODO block 1 line 1 (last line)

THIS LINE SHOULDN'T BE PRINTED #1
TODO block 2 line 1
     block 2 line 2
     block 2 line 3
     block 2 line 4

     block 2 line 6
TODO block 3 line 1
     block 3 line 2
     block 3 line 3
     block 3 line 4
     block 3 line 5 (last line)

TODO block 4 line 1

Output from my script
Caveat: if the TODO block is the last thing in the file, it MUST end in two blank lines as specified in the OP or it will be dropped.
sed -n '/^TODO/{:a;N;s/\n\n$//;Ta;p}' <tricky_todo.txt

TODO block 1 line 1 (last line)
TODO block 2 line 1
     block 2 line 2
     block 2 line 3
     block 2 line 4

     block 2 line 6
     block 2 line 7
     block 2 line 8 (last line)
TODO block 3 line 1
     block 3 line 2
     block 3 line 3
     block 3 line 4
     block 3 line 5 (last line)
TODO block 4 line 1
     block 4 line 2
     block 4 line 3
     block 4 line 4
     block 4 line 5 (last line)

Tip of the hat to @potong
FWIW, when I came up with the script above, I had somehow overlooked potong's original answer (which had a minor flaw).  When I mentioned it, potong completely rewrote that answer using other strategies.  Because of that and the caveat on my script, I am going to include a corrected version of potong's original answer here:
sed '/^TODO/!d;:a;$!{N;s/\n\n$//;t;ba}' <tricky_todo.txt

An "awk"ward solution?
Awk is certainly powerful, but I personally tend to use sed because it's more like the beloved vi, which I use on a daily basis.  Nevertheless, here we go:
awk -vRS="\n\n\n" -vFS="\n" '/TODO/{s=0;for(n=1;n<=NF;n++){if(s==1||$n~/^TODO/){print $n;s=1}}}' <tricky_todo.txt

A: use sed for simple substitution.
$ more file
1
2
blah blah
TODO
blah blah
4
5

6
7
8
9
10

11
end
$ awk -vRS="\n\n" '/TODO/{print;exit}' file
1
2
blah blah
TODO
blah blah
4
5

A: sed 'N;/^\n$/q;P;D'

Proof of Concept

$ cat double_blank.txt
foo
bar

baz

blah
one
two

three

Result

$ sed 'N;/^\n$/q;P;D' double_blank.txt
foo
bar

baz

A: Building on SiegeX's answer:
cat > lines <<'EOF'
a

c
d
EOF
sed '/^$/N; /^\n$/q' lines


text:
Q: SQL71561 Error on Schema compare after initial import from database I have created a new sql server project with SSDT 2012, then I went to import an existing database and it created all my scripts. After that I did a schema compare between the project and the database I just imported the objects from. And I got tons of errors, most of them SQL71561 "contains unresolved reverence to an object. Either the object does not exist or the reference is ambiguous because it could refere to any of the following objects.....
Am I expecting too much from SSDT that after an import a schema compare shouldn't return any errors ?


text:
Q: How do you rotate the 'player' in a Phaser game? I am developing an arena style zombie game. I am in very early stages and I can't find a way to rotate the player the way I want.
I want to be able to rotate the player using left-arrow and right-arrow and move forward with up-arrow.
This is my current player movement conditions:
 if(this.cursor.left.isDown){
        this.player.angle += -0.5;
    }
    else if(this.cursor.right.isDown){
        this.player.angle += 0.5;
    }
    else if(this.cursor.up.isDown){
        this.player.body.velocity.y = -75;
    }
    else{
        this.player.body.velocity.x = 0;
        this.player.body.velocity.y = 0;
    }

The problem with this approach is that, although I can change the rotation of the player with .angle, when I move forward it still just moves me 'up' the screen instead of 'forward' compared to my rotation.
Sorry if I have explained poorly.

A: I cant understand your question properly, but I think this code may be help you.you can use left and right key to rotate the car sprite and up key to move foreword.
    function preload(){
    game.load.image('car', 'assets/sprites/car90.png');
}

var car ;

function create(){
    game.physics.startSystem(Phaser.Physics.ARCADE);
        car = game.add.sprite(game.world.centerX,game.world.centerY,'car');
        car.anchor.setTo(0.5,0.5);
        game.physics.arcade.enable(game.global.car);
        car.body.allowRotation = true;
}

function update(){

            if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)){
                game.global.car.body.angularVelocity = -200;
            }
            else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)){
                game.global.car.body.angularVelocity = 200;
            }
            else if(game.input.keyboard.isDown(Phaser.Keyboard.UP)){
               game.global.car.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(game.global.car.angle, 200));
            }
            else{
                game.global.car.body.angularVelocity = 0;
                game.global.car.body.velocity.x = 0;
                game.global.car.body.velocity.y = 0;
            }
}


text:
Q: Compress JSON String Stored in PostgreSQL, such as MessagePack? JSON strings are currently being stored in a PostgreSQL 11 table in a text field. For example, a row can have the text field asks containing the string:
{"0.000295":1544.2,"0.000324":1050,"0.000325":40.1,"0.000348":0}

Question: Is it possible to store it in a format that consumes lesser space? Using some CPU cycles to serialize/deserialize the JSON string is acceptable as a compromise for using lesser storage space. The JSON data does not need to be searchable. The JSON object keys are almost always different in different rows.
I am particularly interested in using JSON encoding/compression algorithms like MessagePack with zlib, but how can we use this when inserting the record into the PostgreSQL table?
Note: Also using Node.js with Knex.js to communicate with PostgreSQL. Currently converting JSON objects to strings using Node's JSON.stringify function.

A: Individual PostgreSQL fields over 2000 bytes are automatically compressed, for TOAST storage.  However, this compression is not very good, and is local to just that one PostgreSQL value, so can't compress out repetition that occurs between values (like the same keys being used repeatedly, but only once in each JSON structure).  You might want to look at ZSON for compression that uses the whole column for compression context (I've never use it myself).

I am particularly interested in using JSON encoding/compression algorithms like MessagePack with zlib, but how can we use this when inserting the record into the PostgreSQL table?

You could always compress it on the client, then pass it to and from the database as bytea. Of course then you can't do JSON manipulation inside the database.  Also working with bytea is generally unpleasant.
If you can find an implementation of MessagePack in Perl or Python, you could use those pl languages to allow compression and decompression inside the database.


text:
Q: SQL recursive get BOM from PSP I am having a MS SQL Server (2016) and a database which contains i.a. table like this : (it´s a view created in an Autodesk PSP Database - please don´t ask why ... :-) )

CHILD_AIMKEY
QUANTITY
PARENT_AIMKEY
StatusOfParent
StatusOfChild

5706657
1
5664344
100
103

5706745
1
5664344
100
103

5707104
1
5664344
100
103

5707109
1
5664344
100
100

5801062
1
5664344
100
103

The "children" can contain other "children" and in that case they would be their "parents".
So it´s a standard structured BOM table from a CAD PDM System.
If I do the following "Select Statement" I get all the children of the top level parent:
SELECT [CHILD_AIMKEY] , [POSITION], [QUANTITY] ,[PARENT_AIMKEY],[StatusOfParent],[StatusChild] FROM database_table where Parent_aimkey = '5664344'

(as shown in the table above)
My first question is : How to recursivly process all children of each parent from that table ? (Could be an other table or direct output)
The format should be: Parent_Aimkey, Child_Aimkey, Quantity
The second question is a bit more complicated:
I try it with some "pseudo code":
If Tree_Level_of_DIRECT_Parent < 3 then show CHILD_AIMKEY,QUANTITY in queryresult_above
If Tree_Level_of_DIRECT_Parent > 2 and StatusOf_DIRECT_Parent = 103 and StatusOf_DIRECT_Child = 103 then show CHILD_AIMKEY,QUANTITY in queryresult_above

Is that in some way possible ? (If there is a need to extend the database view of an other field or another table, that´s no problem)
I know this looks a bit confusing, but what I need is the Autodesk Inventor structured BOM in an SQL Statement or stored procedure.
Any would be really much appreciated
Thanks
Alex.


text:
Q: Atmeg16 USART communication problem In my project, I use a atmega16 to send data to PC via USB to TTL converter at baud rate of 9600 and internal RC of 4Mhz. If I power the atmega16 using my laptop through a usb cable I can receive the data perfectly, but when I power the same using a 9v DC battery and 7805 regulator, I get garbage value on the PC. Please help me out.

A: You must connect Rx, Tx and ground.
When you supply power from USB then they both PC and mcu operate on a common ground, when you use a battery that ground connection between mcu and PC doesn't exist.
Connect the grounds of USB and battery(-pole) and it should get fixed.


text:
Q: The simplest non-trivial case of unramified Fontaine-Mazur conjecture Let $ p $ be a fixed prime and $ \mathbb{Q}_{p} $ be the $ p $-adic number field. Let $ G_{\mathbb{Q},\{\ell\}} $ be the Galois group of the maximal extension of $ \mathbb{Q} $ unramified outside $ \{\ell\} $ for some prime $ \ell $. Then a special case of unramified Fontaine-Mazur conjecture [Conjecture 5a, Fontaine and Mazur. "Geometric Galois representations." Elliptic curves, modular forms, & Fermat's last theorem (Hong Kong, 1993).] states that:
Conjecture: If $ \ell\neq p $, then any continuous homomorphism $ \rho:G_{\mathbb{Q},\{\ell\}}\to {\rm GL}_{n}(\mathbb{Q}_{p}) $ has finite image.
My question is that: is it still open in the case? What results are known?


text:
Q: Couchbase 1.8.0 concurrency (number of concurrent req support in java client/server): scalability
*

*Is there any limit on server on serving number of requests per second or number of requests serving simultaneously. [in configuration, not due to RAM, CPU etc hardware limitations]

*Is there any limit on number of simultaneous requests on an instance of CouchbaseClient in Java servlet.

*Is it best to create only one instance on CouchbaseClient and keep it open or to create multiple instances and destroy.

*Is Moxi helpful with Couchbase 1.8.0 server/Couchbase java client 1.0.2

I need this info to setup application in production.
Thanks you

A: *

*The memcached instance that runs behind Couchbase has a hard
connection limit of 10,000 connections. Couchbase in general
recommends that you should increase the number of nodes to address
the distrobution of traffic on that level.

*The client itself does not have a hardcoded limit in regards to how
many connections it makes to a Couchbase cluster.

*Couchbase generally recommends that you create a connection pool
from your application to the cluster and just re-use those
connections versus creation and destroying them over and over. On
heavier load applications, the creation and destruction of these
connections over and over can get very expensive from a resource
perspective.

*Moxi is an integrated piece of Couchbase. However, it is generally
in place as an adapter layer for clients developers to specifically
use it or to give legacy access to applications designed to directly
access a memcached interface. If you are using the Couchbase client
driver you won't need to use the Moxi interface.


text:
Q: How to add Debian experimental repo to Ubuntu? I would like to install cups-1.6.1-2 (link) from the experimental repository.
I suppose I have to add something to /etc/apt/sources.list but I can't figure out what.
Can anyone figure out (or know) how to add the experimental repo?

A: The Experimental repository is a Debian repository, not an Ubuntu repository.
I would NOT RECOMMEND using the Experimental repository as a source for anything.  It has a lot of packages which can break everything, hence the name "Experimental".
CUPS 1.6.1-2 exists in Raring.  Once raring is released, you can use Raring.

A: Edit sources.list:
                    '/etc/apt/sources.list'
Add the repo URL like below.
                    'deb http://dev.zenoss.org/deb main stable'

A: You probably shouldn't mix Debian and Ubuntu repositories:

Mixing Debian and Ubuntu repositories will likely render your system unmaintainable. The package dependencies may introduce contradictions which leads to a deadlock situation.

Please read further in the following answers: https://askubuntu.com/a/240654/58950 and https://askubuntu.com/a/264766/58950


text:
Q: deleting an element from all embedded lists in a list in R I have a list (g) of lists as shown below. To delete element k from one of the embedded lists (ex. 1st list), I can do: g[[1]]$k <- NULL.
But when I try to delete element k from all embedded lists, my lapply code fails? Is there a Base R fix?
g <- list(b1 = list(data.frame(a = 1:3), k = 4:6), b2 = list(data.frame(a = 8:9), k = 7:9))

lapply(1:length(g), function(i) g[[i]]$k <- NULL) ## FAILS to delete `k` from all embedded lists

A: You can do
lapply(g, function(x) x[names(x) != "k"])
#$b1
#$b1[[1]]
#  a
#1 1
#2 2
#3 3

#$b2
#$b2[[1]]
#  a
#1 8
#2 9

Or alternatively
lapply(g, function(x) { x[names(x) == "k"] <- NULL; x })

A: R is a functional language and as such copies of arguments are passed rather than pointers to them. Functions are not supposed to make modifications on the "originals" of the arguments. So you should not assume that modifications to values accessed inside function will be "visible" outside that function's environment unless there is an assignment back to the original name (or to an alternate name such as is done here):
> g2 <- lapply(g, function(i){ i$k <- NULL; i})
> g2
$b1
$b1[[1]]
  a
1 1
2 2
3 3

$b2
$b2[[1]]
  a
1 8
2 9

Note also: the need to return the modified element after the "k" value is nulled out. Seemed more direct to pass the actual elements rather than using an index. There is an implicit exception to the rule of "no modifying of arguments" allowed to the <- and <<- functions.

A: Here is an option with discard
library(purrr)
map(g, ~ discard(.x, names(.x) == "k"))
#$b1
#$b1[[1]]
#  a
#1 1
#2 2
#3 3

#$b2
#$b2[[1]]
#  a
#1 8
#2 9

A: Similar to @42-:
lapply(g, '[[<-', 'k', NULL)

# $b1
# $b1[[1]]
#   a
# 1 1
# 2 2
# 3 3

# $b2
# $b2[[1]]
#   a
# 1 8
# 2 9


text:
Q: How to keep a ftp server in sync with mac folder So I have a folder on my mac that I want to be synced with my ftp server.
So far all the solutions i have found were for windows only. Are there any for mac?

A: Syncovery
Professional version supports FTP >  Matrix

Back up your data and synchronize PCs, Macs, servers, notebooks, and
online storage space. You can set up as many different jobs as you
need and run them manually or using the scheduler. Syncovery works
with local hard drives, network drives and any other mounted volumes.
In addition, it comes with support for FTP, SSH, HTTP, WebDAV, Amazon
S3, and Google Docs. You can use ZIP compression and data encryption.
On Windows, the scheduler can run as a service – without users having
to log on. There are powerful synchronization modes, including
Standard Copying, Exact Mirror, and SmartTracking.

A: I've tried Fetch, Interarchy, and Yummy over the years, in that order, with Yummy being my current favorite FTP/sync tool.  At $15, it's a lot cheaper than Matrix, but does a TON of stuff.
There is also FileZilla as a decent free tool too.


text:
Q: How do I list all files of a directory? How can I list all files of a directory in Python and add them to a list?

A: import os
os.listdir("somedirectory")

will return a list of all files and directories in "somedirectory".

A: Using generators
import os
def get_files(search_path):
     for (dirpath, _, filenames) in os.walk(search_path):
         for filename in filenames:
             yield os.path.join(dirpath, filename)
list_files = get_files('.')
for filename in list_files:
    print(filename)

A: Preliminary notes

*

*Although there's a clear differentiation between file and directory terms in the question text, some may argue that directories are actually special files

*The statement: "all files of a directory" can be interpreted in two ways:

*

*All direct (or level 1) descendants only

*All descendants in the whole directory tree (including the ones in sub-directories)

*When the question was asked, I imagine that Python 2, was the LTS version, however the code samples will be run by Python 3(.5) (I'll keep them as Python 2 compliant as possible; also, any code belonging to Python that I'm going to post, is from v3.5.4 - unless otherwise specified).
That has consequences related to another keyword in the question: "add them into a list":

*

*In pre Python 2.2 versions, sequences (iterables) were mostly represented by lists (tuples, sets, ...)

*In Python 2.2, the concept of generator ([Python.Wiki]: Generators) - courtesy of [Python.Docs]: Simple statements - The yield statement) - was introduced. As time passed, generator counterparts started to appear for functions that returned / worked with lists

*In Python 3, generator is the default behavior

*Not sure if returning a list is still mandatory (or a generator would do as well), but passing a generator to the list constructor, will create a list out of it (and also consume it). The example below illustrates the differences on [Python.Docs]: Built-in functions - map(function, iterable, *iterables)

>>> import sys
>>>
>>> sys.version
'2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>> m = map(lambda x: x, [1, 2, 3])  # Just a dummy lambda function
>>> m, type(m)
([1, 2, 3], <type 'list'>)
>>> len(m)
3

>>> import sys
>>>
>>> sys.version
'3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)]'
>>> m = map(lambda x: x, [1, 2, 3])
>>> m, type(m)
(<map object at 0x000001B4257342B0>, <class 'map'>)
>>> len(m)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'map' has no len()
>>> lm0 = list(m)  # Build a list from the generator
>>> lm0, type(lm0)
([1, 2, 3], <class 'list'>)
>>>
>>> lm1 = list(m)  # Build a list from the same generator
>>> lm1, type(lm1)  # Empty list now - generator already exhausted
([], <class 'list'>)

*The examples will be based on a directory called root_dir with the following structure (this example is for Win, but I'm using the same tree on Nix as well). Note that I'll be reusing the console:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q003207219]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]>
[prompt]> tree /f "root_dir"
Folder PATH listing for volume Work
Volume serial number is 00000029 3655:6FED
E:\WORK\DEV\STACKOVERFLOW\Q003207219\ROOT_DIR
¦   file0
¦   file1
¦
+---dir0
¦   +---dir00
¦   ¦   ¦   file000
¦   ¦   ¦
¦   ¦   +---dir000
¦   ¦           file0000
¦   ¦
¦   +---dir01
¦   ¦       file010
¦   ¦       file011
¦   ¦
¦   +---dir02
¦       +---dir020
¦           +---dir0200
+---dir1
¦       file10
¦       file11
¦       file12
¦
+---dir2
¦   ¦   file20
¦   ¦
¦   +---dir20
¦           file200
¦
+---dir3

Solutions
Programmatic approaches
1. [Python.Docs]: os.listdir(path='.')

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' ...

>>> import os
>>>
>>> root_dir = "root_dir"  # Path relative to current dir (os.getcwd())
>>>
>>> os.listdir(root_dir)  # List all the items in root_dir
['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1']
>>>
>>> [item for item in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, item))]  # Filter items and only keep files (strip out directories)
['file0', 'file1']

A more elaborate example (code_os_listdir.py):
#!/usr/bin/env python

import os
import sys
from pprint import pformat as pf

def _get_dir_content(path, include_folders, recursive):
    entries = os.listdir(path)
    for entry in entries:
        entry_with_path = os.path.join(path, entry)
        if os.path.isdir(entry_with_path):
            if include_folders:
                yield entry_with_path
            if recursive:
                for sub_entry in _get_dir_content(entry_with_path, include_folders, recursive):
                    yield sub_entry
        else:
            yield entry_with_path

def get_dir_content(path, include_folders=True, recursive=True, prepend_folder_name=True):
    path_len = len(path) + len(os.path.sep)
    for item in _get_dir_content(path, include_folders, recursive):
        yield item if prepend_folder_name else item[path_len:]

def _get_dir_content_old(path, include_folders, recursive):
    entries = os.listdir(path)
    ret = list()
    for entry in entries:
        entry_with_path = os.path.join(path, entry)
        if os.path.isdir(entry_with_path):
            if include_folders:
                ret.append(entry_with_path)
            if recursive:
                ret.extend(_get_dir_content_old(entry_with_path, include_folders, recursive))
        else:
            ret.append(entry_with_path)
    return ret

def get_dir_content_old(path, include_folders=True, recursive=True, prepend_folder_name=True):
    path_len = len(path) + len(os.path.sep)
    return [item if prepend_folder_name else item[path_len:] for item in _get_dir_content_old(path, include_folders, recursive)]

def main(*argv):
    root_dir = "root_dir"
    ret0 = get_dir_content(root_dir, include_folders=True, recursive=True, prepend_folder_name=True)
    lret0 = list(ret0)
    print("{:} {:d}\n{:s}".format(ret0, len(lret0), pf(lret0)))
    ret1 = get_dir_content_old(root_dir, include_folders=False, recursive=True, prepend_folder_name=False)
    print("\n{:d}\n{:s}".format(len(ret1), pf(ret1)))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Notes:

*

*There are two implementations:

*

*One that uses generators (of course here it seems useless, since I immediately convert the result to a list)

*The classic one (function names ending in _old)

*Recursion is used (to get into subdirectories)

*For each implementation there are two functions:

*

*One that starts with an underscore (_): "private" (should not be called directly) - that does all the work

*The public one (wrapper over previous): it just strips off the initial path (if required) from the returned entries. It's an ugly implementation, but it's the only idea that I could come with at this point

*In terms of performance, generators are generally a little bit faster (considering both creation and  iteration times), but I didn't test them in recursive functions, and also I am iterating inside the function over inner generators - don't know how performance friendly is that

*Play with the arguments to get different results
Output:

[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.05.04_test0\Scripts\python.exe" ".\code_os_listdir.py"
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] 064bit on win32

<generator object get_dir_content at 0x000002C080418F68> 22
['root_dir\\dir0',
 'root_dir\\dir0\\dir00',
 'root_dir\\dir0\\dir00\\dir000',
 'root_dir\\dir0\\dir00\\dir000\\file0000',
 'root_dir\\dir0\\dir00\\file000',
 'root_dir\\dir0\\dir01',
 'root_dir\\dir0\\dir01\\file010',
 'root_dir\\dir0\\dir01\\file011',
 'root_dir\\dir0\\dir02',
 'root_dir\\dir0\\dir02\\dir020',
 'root_dir\\dir0\\dir02\\dir020\\dir0200',
 'root_dir\\dir1',
 'root_dir\\dir1\\file10',
 'root_dir\\dir1\\file11',
 'root_dir\\dir1\\file12',
 'root_dir\\dir2',
 'root_dir\\dir2\\dir20',
 'root_dir\\dir2\\dir20\\file200',
 'root_dir\\dir2\\file20',
 'root_dir\\dir3',
 'root_dir\\file0',
 'root_dir\\file1']

11
['dir0\\dir00\\dir000\\file0000',
 'dir0\\dir00\\file000',
 'dir0\\dir01\\file010',
 'dir0\\dir01\\file011',
 'dir1\\file10',
 'dir1\\file11',
 'dir1\\file12',
 'dir2\\dir20\\file200',
 'dir2\\file20',
 'file0',
 'file1']

Done.

2. [Python.Docs]: os.scandir(path='.')
In Python 3.5+ only, backport: [PyPI]: scandir:

Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries '.' and '..' are not included.
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

>>> import os
>>>
>>> root_dir = os.path.join(".", "root_dir")  # Explicitly prepending current directory
>>> root_dir
'.\\root_dir'
>>>
>>> scandir_iterator = os.scandir(root_dir)
>>> scandir_iterator
<nt.ScandirIterator object at 0x00000268CF4BC140>
>>> [item.path for item in scandir_iterator]
['.\\root_dir\\dir0', '.\\root_dir\\dir1', '.\\root_dir\\dir2', '.\\root_dir\\dir3', '.\\root_dir\\file0', '.\\root_dir\\file1']
>>>
>>> [item.path for item in scandir_iterator]  # Will yield an empty list as it was consumed by previous iteration (automatically performed by the list comprehension)
[]
>>>
>>> scandir_iterator = os.scandir(root_dir)  # Reinitialize the generator
>>> for item in scandir_iterator :
...     if os.path.isfile(item.path):
...             print(item.name)
...
file0
file1

Notes:

*

*Similar to os.listdir

*But it's also more flexible (and offers more functionality), more Pythonic (and in some cases, faster)
3. [Python.Docs]: os.walk(top, topdown=True, onerror=None, followlinks=False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

>>> import os
>>>
>>> root_dir = os.path.join(os.getcwd(), "root_dir")  # Specify the full path
>>> root_dir
'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir'
>>>
>>> walk_generator = os.walk(root_dir)
>>> root_dir_entry = next(walk_generator)  # First entry corresponds to the root dir (passed as an argument)
>>> root_dir_entry
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir', ['dir0', 'dir1', 'dir2', 'dir3'], ['file0', 'file1'])
>>>
>>> root_dir_entry[1] + root_dir_entry[2]  # Display dirs and files (direct descendants) in a single list
['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1']
>>>
>>> [os.path.join(root_dir_entry[0], item) for item in root_dir_entry[1] + root_dir_entry[2]]  # Display all the entries in the previous list by their full path
['E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0', 'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir1', 'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir2', 'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir3', 'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\file0', 'E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\file1']
>>>
>>> for entry in walk_generator:  # Display the rest of the elements (corresponding to every subdir)
...     print(entry)
...
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0', ['dir00', 'dir01', 'dir02'], [])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir00', ['dir000'], ['file000'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir00\\dir000', [], ['file0000'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir01', [], ['file010', 'file011'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir02', ['dir020'], [])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir02\\dir020', ['dir0200'], [])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir0\\dir02\\dir020\\dir0200', [], [])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir1', [], ['file10', 'file11', 'file12'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir2', ['dir20'], ['file20'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir2\\dir20', [], ['file200'])
('E:\\Work\\Dev\\StackOverflow\\q003207219\\root_dir\\dir3', [], [])

Notes:

*

*Under the scenes, it uses os.scandir (os.listdir on older (Python) versions)

*It does the heavy lifting by recurring in subfolders
4. [Python.Docs]: glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)
Or glob.iglob:

Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell)....Changed in version 3.5: Support for recursive globs using "**".

>>> import glob, os
>>>
>>> wildcard_pattern = "*"
>>> root_dir = os.path.join("root_dir", wildcard_pattern)  # Match every file/dir name
>>> root_dir
'root_dir\\*'
>>>
>>> glob_list = glob.glob(root_dir)
>>> glob_list
['root_dir\\dir0', 'root_dir\\dir1', 'root_dir\\dir2', 'root_dir\\dir3', 'root_dir\\file0', 'root_dir\\file1']
>>>
>>> [item.replace("root_dir" + os.path.sep, "") for item in glob_list]  # Strip the dir name and the path separator from begining
['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1']
>>>
>>> for entry in glob.iglob(root_dir + "*", recursive=True):
...     print(entry)
...
root_dir\
root_dir\dir0
root_dir\dir0\dir00
root_dir\dir0\dir00\dir000
root_dir\dir0\dir00\dir000\file0000
root_dir\dir0\dir00\file000
root_dir\dir0\dir01
root_dir\dir0\dir01\file010
root_dir\dir0\dir01\file011
root_dir\dir0\dir02
root_dir\dir0\dir02\dir020
root_dir\dir0\dir02\dir020\dir0200
root_dir\dir1
root_dir\dir1\file10
root_dir\dir1\file11
root_dir\dir1\file12
root_dir\dir2
root_dir\dir2\dir20
root_dir\dir2\dir20\file200
root_dir\dir2\file20
root_dir\dir3
root_dir\file0
root_dir\file1

Notes:

*

*Uses os.listdir

*For large trees (especially if recursive is on), iglob is preferred

*Allows advanced filtering based on name (due to the wildcard)
5. [Python.Docs]: class pathlib.Path(*pathsegments)
Python 3.4+, backport: [PyPI]: pathlib2.

>>> import pathlib
>>>
>>> root_dir = "root_dir"
>>> root_dir_instance = pathlib.Path(root_dir)
>>> root_dir_instance
WindowsPath('root_dir')
>>> root_dir_instance.name
'root_dir'
>>> root_dir_instance.is_dir()
True
>>>
>>> [item.name for item in root_dir_instance.glob("*")]  # Wildcard searching for all direct descendants
['dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1']
>>>
>>> [os.path.join(item.parent.name, item.name) for item in root_dir_instance.glob("*") if not item.is_dir()]  # Display paths (including parent) for files only
['root_dir\\file0', 'root_dir\\file1']

Notes:

*

*This is one way of achieving our goal

*It's the OOP style of handling paths

*Offers lots of functionalities
6. [Python 2.Docs]: dircache.listdir(path)

*

*Python 2 only

*But, according to [GitHub]: python/cpython - (2.7) cpython/Lib/dircache.py, it's just a (thin) wrapper over os.listdir with caching

def listdir(path):
    """List directory contents, using cache."""
    try:
        cached_mtime, list = cache[path]
        del cache[path]
    except KeyError:
        cached_mtime, list = -1, []
    mtime = os.stat(path).st_mtime
    if mtime != cached_mtime:
        list = os.listdir(path)
        list.sort()
    cache[path] = mtime, list
    return list

7. Native OS APIs
POSIX specific:

*

*[Man7]: OPENDIR(3)

*[Man7]: READDIR(3)

*[Man7]: CLOSEDIR(3)
Available via [Python.Docs]: ctypes - A foreign function library for Python:

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Not directly related, but check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) out before working with CTypes.
code_ctypes.py:
#!/usr/bin/env python3

import ctypes as cts
import sys

DT_DIR = 4
DT_REG = 8

class NixDirent64(cts.Structure):
    _fields_ = (
        ("d_ino", cts.c_ulonglong),
        ("d_off", cts.c_longlong),
        ("d_reclen", cts.c_ushort),
        ("d_type", cts.c_ubyte),
        ("d_name", cts.c_char * 256),
    )

NixDirent64Ptr = cts.POINTER(NixDirent64)

libc = this_process = cts.CDLL(None, use_errno=True)

opendir = libc.opendir
opendir.argtypes = (cts.c_char_p,)
opendir.restype = cts.c_void_p
readdir = libc.readdir
readdir.argtypes = (cts.c_void_p,)
readdir.restype = NixDirent64Ptr
closedir = libc.closedir
closedir.argtypes = (cts.c_void_p,)

def get_dir_content(path):
    ret = [path, [], []]
    pdir = opendir(cts.create_string_buffer(path.encode()))
    if not pdir:
        print("opendir returned NULL (errno: {:d})".format(cts.get_errno()))
        return ret
    cts.set_errno(0)
    while True:
        pdirent = readdir(pdir)
        if not pdirent:
            break
        dirent = pdirent.contents
        name = dirent.d_name.decode()
        if dirent.d_type & DT_DIR:
            if name not in (".", ".."):
                ret[1].append(name)
        elif dirent.d_type & DT_REG:
            ret[2].append(name)
    if cts.get_errno():
        print("readdir returned NULL (errno: {:d})".format(cts.get_errno()))
    closedir(pdir)
    return ret

def main(*argv):
    root_dir = "root_dir"
    entries = get_dir_content(root_dir)
    print("Entries:\n{:}".format(entries))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Notes:

*

*It loads the three functions from LibC (libc.so - loaded in the current process) and calls them (for more details check [SO]: How do I check whether a file exists without exceptions? (@CristiFati's answer) - last notes from item #4.). That would place this approach very close to the Python / C edge

*NixDirent64 is the CTypes representation of struct dirent64 from [Man7]: dirent.h(0P) (so are the DT_ constants) from my Ubuntu OS. On other flavors / versions, the structure definition might differ, and if so, the CTypes alias should be updated, otherwise it will yield Undefined Behavior

*It returns data in the os.walk's format. I didn't bother to make it recursive, but starting from the existing code, that would be a fairly trivial task

*Everything is doable on Win as well, the data (libraries, functions, structs, constants, ...) differ
Output:

[cfati@cfati-5510-0:/mnt/e/Work/Dev/StackOverflow/q003207219]> python3.5 ./code_ctypes.py
Python 3.5.10 (default, Jan 15 2022, 19:53:00) [GCC 9.3.0] 064bit on linux

Entries:
['root_dir', ['dir0', 'dir1', 'dir2', 'dir3'], ['file0', 'file1']]

Done.

8. [TimGolden]: win32file.FindFilesW
Win specific:

Retrieves a list of matching filenames, using the Windows Unicode API. An interface to the API FindFirstFileW/FindNextFileW/Find close functions.

>>> import os, win32file as wfile, win32con as wcon
>>>
>>> root_dir = "root_dir"
>>> root_dir_wildcard = os.path.join(root_dir, "*")
>>> entry_list = wfile.FindFilesW(root_dir_wildcard)
>>> len(entry_list)  # Don't display the whole content as it's too long
8
>>> [entry[-2] for entry in entry_list]  # Only display the entry names
['.', '..', 'dir0', 'dir1', 'dir2', 'dir3', 'file0', 'file1']
>>>
>>> [entry[-2] for entry in entry_list if entry[0] & wcon.FILE_ATTRIBUTE_DIRECTORY and entry[-2] not in (".", "..")]  # Filter entries and only display dir names (except self and parent)
['dir0', 'dir1', 'dir2', 'dir3']
>>>
>>> [os.path.join(root_dir, entry[-2]) for entry in entry_list if entry[0] & (wcon.FILE_ATTRIBUTE_NORMAL | wcon.FILE_ATTRIBUTE_ARCHIVE)]  # Only display file "full" names
['root_dir\\file0', 'root_dir\\file1']

Notes:

*

*win32file.FindFilesW is part of [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions, which is a Python wrapper over WinAPIs

9. Use some (other) 3rd-party package that does the trick
Most likely, will rely on one (or more) of the above (maybe with slight customizations).
Notes:

*

*Code is meant to be portable (except places that target a specific area - which are marked) or cross:

*

*OS (Nix, Win, )

*Python version (2, 3, )

*Multiple path styles (absolute, relatives) were used across the above variants, to illustrate the fact that the "tools" used are flexible in this direction

*os.listdir and os.scandir use opendir / readdir / closedir ([MS.Learn]: FindFirstFileW function (fileapi.h) / [MS.Learn]: FindNextFileW function (fileapi.h) / [MS.Learn]: FindClose function (fileapi.h)) (via [GitHub]: python/cpython - (main) cpython/Modules/posixmodule.c)

*win32file.FindFilesW uses those (Win specific) functions as well (via [GitHub]: mhammond/pywin32 - (main) pywin32/win32/src/win32file.i)

*_get_dir_content (from point #1.) can be implemented using any of these approaches (some will require more work and some less)

*

*Some advanced filtering (instead of just file vs. dir) could be done: e.g. the include_folders argument could be replaced by another one (e.g. filter_func) which would be a function that takes a path as an argument: filter_func=lambda x: True (this doesn't strip out anything) and inside _get_dir_content something like: if not filter_func(entry_with_path): continue (if the function fails for one entry, it will be skipped), but the more complex the code becomes, the longer it will take to execute

*Nota Bene! Since recursion is used, I must mention that I did some tests on my laptop (Win 10 pc064), totally unrelated to this problem, and when the recursion level was reaching values somewhere in the (990 .. 1000) range (recursionlimit - 1000 (default)), I got StackOverflow :). If the directory tree exceeds that limit (I am not an FS expert, so I don't know if that is even possible), that could be a problem.
I must also mention that I didn't try to increase recursionlimit, but in theory there will always be the possibility for failure, if the dir depth is larger than the highest possible recursionlimit (on that machine).
Check [SO]: _csv.Error: field larger than field limit (131072) (@CristiFati's answer) for more details on the topic

*Code samples are for demonstrative purposes only. That means that I didn't take into account error handling (I don't think there's any try / except / else / finally block), so the code is not robust (the reason is: to keep it as simple and short as possible). For production, error handling should be added as well
Other approaches:
1. Use Python only as a wrapper

*

*Everything is done using another technology

*That technology is invoked from Python

*The most famous flavor that I know is what I call the SysAdmin approach:

*

*Use Python (or any programming language for that matter) in order to execute Shell commands (and parse their outputs)

*Some consider this a neat hack

*I consider it more like a lame workaround (gainarie), as the action per se is performed from Shell (Cmd in this case), and thus doesn't have anything to do with Python

*Filtering (grep / findstr) or output formatting could be done on both sides, but I'm not going to insist on it. Also, I deliberately used os.system instead of [Python.Docs]: subprocess - Subprocess management routines (run, check_output, ...)

[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.05.04_test0\Scripts\python.exe" -c "import os;os.system(\"dir /b root_dir\")"
dir0
dir1
dir2
dir3
file0
file1

[cfati@cfati-5510-0:/mnt/e/Work/Dev/StackOverflow/q003207219]> python3.5 -c "import os;os.system(\"ls root_dir\")"
dir0  dir1  dir2  dir3  file0  file1

In general, this approach is to be avoided, since if some command output format slightly differs between OS versions / flavors, the parsing code should be adapted as well - not to mention differences between locales.

A: Another very readable variant for Python 3.4+ is using pathlib.Path.glob:
from pathlib import Path
folder = '/foo'
[f for f in Path(folder).glob('*') if f.is_file()]

It is simple to make more specific, e.g. only look for Python source files which are not symbolic links, also in all subdirectories:
[f for f in Path(folder).glob('**/*.py') if not f.is_symlink()]

A: os.listdir() returns everything inside a directory -- including both files and directories.
os.path's isfile() can be used to only list files:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

Alternatively, os.walk() yields two lists for each directory it visits -- one for files and one for dirs. If you only want the top directory you can break the first time it yields:
from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

or, shorter:
from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

A: I really liked adamk's answer, suggesting that you use glob(), from the module of the same name. This allows you to have pattern matching with *s.
But as other people pointed out in the comments, glob() can get tripped up over inconsistent slash directions. To help with that, I suggest you use the join() and expanduser() functions in the os.path module, and perhaps the getcwd() function in the os module, as well.
As examples:
from glob import glob

# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')

The above is terrible - the path has been hardcoded and will only ever work on Windows between the drive name and the \s being hardcoded into the path.
from glob    import glob
from os.path import join

# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))

The above works better, but it relies on the folder name Users which is often found on Windows and not so often found on other OSs. It also relies on the user having a specific name, admin.
from glob    import glob
from os.path import expanduser, join

# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))

This works perfectly across all platforms.
Another great example that works perfectly across platforms and does something a bit different:
from glob    import glob
from os      import getcwd
from os.path import join

# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))

Hope these examples help you see the power of a few of the functions you can find in the standard Python library modules.

A: def list_files(path):
    # returns a list of names (with extension, without full path) of all files
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files

A: For Python 2:
pip install rglob

Then do
import rglob
file_list = rglob.rglob("/home/base/dir/", "*")
print file_list

A: Here's my general-purpose function for this.  It returns a list of file paths rather than filenames since I found that to be more useful.  It has a few optional arguments that make it versatile.  For instance, I often use it with arguments like pattern='*.txt' or subfolders=True.
import os
import fnmatch

def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
    """Return a list of the file paths matching the pattern in the specified
    folder, optionally including files inside subfolders.
    """
    match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
    walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
    return [os.path.join(root, f)
            for root, dirnames, filenames in walked
            for f in filenames if match(f, pattern)]

A: I will provide a sample one liner where sourcepath and file type can be provided as input. The code returns a list of filenames with csv extension. Use . in case all files needs to be returned. This will also recursively scans the subdirectories.
[y for x in os.walk(sourcePath) for y in glob(os.path.join(x[0], '*.csv'))]
Modify file extensions and source path as needed.

A: If you are looking for a Python implementation of find, this is a recipe I use rather frequently:
from findtools.find_files import (find_files, Match)

# Recursively find all *.sh files in **/usr/bin**
sh_files_pattern = Match(filetype='f', name='*.sh')
found_files = find_files(path='/usr/bin', match=sh_files_pattern)

for found_file in found_files:
    print found_file

So I made a PyPI package out of it and there is also a GitHub repository. I hope that someone finds it potentially useful for this code.

A: I prefer using the glob module, as it does pattern matching and expansion.
import glob
print(glob.glob("/home/adam/*"))

It does pattern matching intuitively
import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt"))
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt"))

It will return a list with the queried files and directories:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

Note that glob ignores files and directories that begin with a dot ., as those are considered hidden files and directories, unless the pattern is something like .*.
Use glob.escape to escape strings that are not meant to be patterns:
print(glob.glob(glob.escape(directory_name) + "/*.txt"))

A: dircache is  "Deprecated since version 2.6: The dircache module has been removed in Python 3.0."
import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
  if len(list[i]) != check:
     temp.append(list[i-1])
     check = len(list[i])
  else:
    i = i + 1
    count = count - 1

print temp

A: A one-line solution to get only list of files (no subdirectories):
filenames = next(os.walk(path))[2]

or absolute pathnames:
paths = [os.path.join(path, fn) for fn in next(os.walk(path))[2]]

A: For greater results, you can use listdir() method of the os module along with a generator (a generator is a powerful iterator that keeps its state, remember?). The following code works fine with both versions: Python 2 and Python 3.
Here's a code:
import os

def files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file

for file in files("."):
    print (file)

The listdir() method returns the list of entries for the given directory. The method os.path.isfile() returns True if the given entry is a file. And the yield operator quits the func but keeps its current state, and it returns only the name of the entry detected as a file. All the above allows us to loop over the generator function.

A: Getting Full File Paths From a Directory and All Its Subdirectories
import os

def get_filepaths(directory):
    """
    This function will generate the file names in a directory
    tree by walking the tree either top-down or bottom-up. For each
    directory in the tree rooted at directory top (including top itself),
    it yields a 3-tuple (dirpath, dirnames, filenames).
    """
    file_paths = []  # List which will store all of the full filepaths.

    # Walk the tree.
    for root, directories, files in os.walk(directory):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)  # Add it to the list.

    return file_paths  # Self-explanatory.

# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")

*

*The path I provided in the above function contained 3 files— two of them in the root directory, and another in a subfolder called "SUBFOLDER."  You can now do things like:

*print full_file_paths which will print the list:

*

*['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']
If you'd like, you can open and read the contents, or focus only on files with the extension ".dat" like in the code below:
for f in full_file_paths:
  if f.endswith(".dat"):
    print f

/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat

A: list in the current directory
With listdir in os module you get the files and the folders in the current dir
import os

arr = os.listdir()

Looking in a directory
arr = os.listdir('c:\\files')

with glob you can specify a type of file to list like this
import glob

txtfiles = []
for file in glob.glob("*.txt"):
    txtfiles.append(file)

or
mylist = [f for f in glob.glob("*.txt")]

get the full path of only files in the current directory
import os
from os import listdir
from os.path import isfile, join

cwd = os.getcwd()
onlyfiles = [os.path.join(cwd, f) for f in os.listdir(cwd) if
os.path.isfile(os.path.join(cwd, f))]
print(onlyfiles)

['G:\\getfilesname\\getfilesname.py', 'G:\\getfilesname\\example.txt']

Getting the full path name with os.path.abspath
You get the full path in return
 import os
 files_path = [os.path.abspath(x) for x in os.listdir()]
 print(files_path)

 ['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']

Walk: going through sub directories
os.walk returns the root, the directories list and the files list, that is why I unpacked them in r, d, f in the for loop; it, then, looks for other files and directories in the subfolders of the root and so on until there are no subfolders.
import os

# Getting the current work directory (cwd)
thisdir = os.getcwd()

# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
    for file in f:
        if file.endswith(".docx"):
            print(os.path.join(r, file))

To go up in the directory tree
# Method 1
x = os.listdir('..')

# Method 2
x= os.listdir('/')

Get files of a particular subdirectory with os.listdir()
import os

x = os.listdir("./content")

os.walk('.') - current directory
 import os
 arr = next(os.walk('.'))[2]
 print(arr)

 >>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']

next(os.walk('.')) and os.path.join('dir', 'file')
 import os
 arr = []
 for d,r,f in next(os.walk("F:\\_python")):
     for file in f:
         arr.append(os.path.join(r,file))

 for f in arr:
     print(files)

>>> F:\\_python\\dict_class.py
>>> F:\\_python\\programmi.txt

next... walk
 [os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]

 >>> ['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']

os.walk
x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
print(x)

>>> ['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']

os.listdir() - get only txt files
 arr_txt = [x for x in os.listdir() if x.endswith(".txt")]

Using glob to get the full path of the files
from path import path
from glob import glob

x = [path(f).abspath() for f in glob("F:\\*.txt")]

Using os.path.isfile to avoid directories in the list
import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]

Using pathlib from Python 3.4
import pathlib

flist = []
for p in pathlib.Path('.').iterdir():
    if p.is_file():
        print(p)
        flist.append(p)

With list comprehension:
flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]

Use glob method in pathlib.Path()
import pathlib

py = pathlib.Path().glob("*.py")

Get all and only files with os.walk: checks only in the third element returned, i.e. the list of the files
import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
    for f in t:
        y.append(f)

Get only files with next in a directory: returns only the file in the root folder
 import os
 x = next(os.walk('F://python'))[2]

Get only directories with next and walk in a directory, because in the [1] element there are the folders only
 import os
 next(os.walk('F://python'))[1] # for the current dir use ('.')

 >>> ['python3','others']

Get all the subdir names with walk
for r,d,f in os.walk("F:\\_python"):
    for dirs in d:
        print(dirs)

os.scandir() from Python 3.5 and greater
import os
x = [f.name for f in os.scandir() if f.is_file()]

# Another example with `scandir` (a little variation from docs.python.org)
# This one is more efficient than `os.listdir`.
# In this case, it shows the files only in the current directory
# where the script is executed.

import os
with os.scandir() as i:
    for entry in i:
        if entry.is_file():
            print(entry.name)

A: Returning a list of absolute filepaths, does not recurse into subdirectories
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]

A: A wise teacher told me once that:

When there are several established ways to do something, none of them is good for all cases.

I will thus add a solution for a subset of the problem: quite often, we only want to check whether a file matches a start string and an end string, without going into subdirectories. We would thus like a function that returns a list of filenames, like:
filenames = dir_filter('foo/baz', radical='radical', extension='.txt')

If you care to first declare two functions, this can be done:
def file_filter(filename, radical='', extension=''):
    "Check if a filename matches a radical and extension"
    if not filename:
        return False
    filename = filename.strip()
    return(filename.startswith(radical) and filename.endswith(extension))

def dir_filter(dirname='', radical='', extension=''):
    "Filter filenames in directory according to radical and extension"
    if not dirname:
        dirname = '.'
    return [filename for filename in os.listdir(dirname)
                if file_filter(filename, radical, extension)]

This solution could be easily generalized with regular expressions (and you might want to add a pattern argument, if you do not want your patterns to always stick to the start or end of the filename).

A: Since version 3.4 there are builtin iterators for this which are a lot more efficient than os.listdir():
pathlib: New in version 3.4.
>>> import pathlib
>>> [p for p in pathlib.Path('.').iterdir() if p.is_file()]

According to PEP 428, the aim of the pathlib library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.
os.scandir(): New in version 3.5.
>>> import os
>>> [entry for entry in os.scandir('.') if entry.is_file()]

Note that os.walk() uses os.scandir() instead of os.listdir() from version 3.5, and its speed got increased by 2-20 times according to PEP 471.
Let me also recommend reading ShadowRanger's comment below.

A: import os
import os.path

def get_files(target_dir):
    item_list = os.listdir(target_dir)

    file_list = list()
    for item in item_list:
        item_dir = os.path.join(target_dir,item)
        if os.path.isdir(item_dir):
            file_list += get_files(item_dir)
        else:
            file_list.append(item_dir)
    return file_list

Here I use a recursive structure.


text:
Q: An error occurred while running cordova build android I want to check GPS is enabled or no in user device so for that I installed ionic 2 native diagnostic plugin and tried to build apk using

ionic cordova build android

but getting below error while doing so, I have installed Google Support Repository in Android studio, I have attached the screenshot of the error, tried most possible ways published in stackoverflow but could not resolve the issue, please someone guide me achieving this. Thanks.

A: Open Android SDK Manager and update android support repository to resolve the issue. Please refer this link


text:
Q: A pair of changes, to NaGE viewing and example deletion, that might encourage elimination of weak examples Proposal:

*

*Give users a view that ranked their question examples by the number of NaGE votes received (cf. Add "not a good example" to my profile proposal), and

*Let reputation be immediately recovered from NaGE votes on deletion of questions.

This would, I think, both encourage the withdrawal of weak question examples and encourage more application of NaGE votes to weak questions.  If both these things happened, then the list of question examples would correspond more closely with the list of question examples deserving consideration.


text:
Q: Get content div to hit bottom of the page On http://audioaffair.co.uk why does the content div #pageSurround not hit the bottom of the browser window when there is sufficient content? (the black background shows through at the bottom even though all margins are 0px. So why does the body end early?)
On pages with less content like (https://www.audioaffair.co.uk/cart.php?act=cart)
how can I get the #pageSurround div to hit the bottom of the browser window.

A: As to your first problem: that is because in CSS there is
.clearfix:after {
content: ".";
    /* ... */
}

So there's a dot between your pageSurround div (with clearfix class) and the bottom of the page.
As to your second problem: the link that trevor posted should help you.


text:
Q: Integrate Apache Cassandra Logging with Spring Web Application I've this requirement where I need to make use of Cassandra 2.0.x built-in Logging functionality within my spring web application.
Can somebody tell me what all steps do I need to follow to achieve the same?
Thanks in advance


text:
Q: What is the determinant of 2d discrete cosine transform? Suppose the image matrix $X\in R^{N\times N}$, the 2D DCT can be expressed as $dct(X)=AXA^T$, where
$$
A=
\begin{bmatrix}
\sqrt{1/N} & \sqrt{1/N}&\cdots&\sqrt{1/N} \\
\sqrt{2/N}\cos(\pi/2N) & \sqrt{2/N}\cos(3\pi/2N)&\cdots&\sqrt{2/N}\cos((2N-1)\pi/2N) \\
\sqrt{2/N}\cos(2\pi/2N) & \sqrt{2/N}\cos(6\pi/2N)&\cdots&\sqrt{2/N}\cos(2(2N-1)\pi/2N) \\
\vdots & \vdots & \ddots &\vdots \\
\sqrt{2/N}\cos((N-1)\pi/2N) & \sqrt{2/N}\cos((N-1)3\pi/2N)&\cdots&\sqrt{2/N}\cos((N-1)(2N-1)\pi/2N) \\
\end{bmatrix}
$$
We can also get a vectorized version. Denote $x=vec(X)$, then $dct(x)=Vx$, where $V\in R^{N^2\times N^2}$. What is the determinant of $V$?


text:
Q: PHP: order a multi-dimensional array according to a list of values Given this array:
Array
(
    [0] => Array
        (
            [status] => closed
            [userModifiedAt] => 2015-12-09T11:47:46Z
        )

    [1] => Array
        (
            [status] => active
            [userModifiedAt] => 2016-02-08T16:43:26Z
        )

    [2] => Array
        (
            [status] => closed
            [userModifiedAt] => 2016-03-31T03:47:19Z
        )

    [3] => Array
        (
            [status] => pending
            [userModifiedAt] => 2015-12-08T14:09:58Z
        )

I'd like to order it by [status] with this order:
- pending
- active
- closed
And for each status, order by [userModifiedAt].
I'm using this code:
usort($array, function($a,$b){ return strcmp($a['status'], $b['status']);} );

But it works alphabetically, so the status is ordered as:
- active
- closed
- pending
How can I order an array according to a predefined order list?

A: This would be a trick -
## A array with the orders to be considered
$order = array('active' => 1, 'closed' => 2, 'pending' => 3);

usort($array, function($a, $b) use($order) { // Use the order array to compare
    return $order[$a[status]] - $order[$b[status]];
});

var_dump($array);

Output
array(4) {
  [0]=>
  array(2) {
    ["status"]=>
    string(6) "active"
    ["userModifiedAt"]=>
    string(20) "2016-02-08T16:43:26Z"
  }
  [1]=>
  array(2) {
    ["status"]=>
    string(6) "closed"
    ["userModifiedAt"]=>
    string(20) "2015-12-09T11:47:46Z"
  }
  [2]=>
  array(2) {
    ["status"]=>
    string(6) "closed"
    ["userModifiedAt"]=>
    string(20) "2016-03-31T03:47:19Z"
  }
  [3]=>
  array(2) {
    ["status"]=>
    string(7) "pending"
    ["userModifiedAt"]=>
    string(20) "2015-12-08T14:09:58Z"
  }
}

Change the order array if you want different order. Key with lowest value will be first on the array. If you want closed to be first then provide the lowest value to it in $order array.
DEMO


text:
Q: Limits of composite functions where the function is discontinuous Limit of a composite function that isn't continuous: Take $$\lim_{x\to 0}f(g(x))$$ where $f$ is discontinuous at $0$. What should I do if I know the graphs of these functions and as I said $f$ is discontinuous at $0$ but the whole limit does exist?
My question rather is, how do I show the steps? Like I don't want to just directly put this equal to 0, but rather follow steps, how should I write the steps? because I can't write $\lim_{x\to 0}f(g(x))=f(\lim_{x\to 0}g(x))$ since $f$ isn't continuous at $0$.

A: We have that
$$\lim_{x\to 0}g(x)=2$$
and $f(x)$ has a removable discontinuity at $x=2$ therefore the limit exists with
$$\lim_{x\to 2}f(x)=0$$
and then we can conclude that
$$\lim_{x\to 0}f(g(x))=0$$
Note that continuity is not a necessary condition to determine the limit, what we need is that limits exist and that $g(x)\neq 2$ in a certain neighborhood of zero.
For related and detailed discussion on that point refer to:

*

*Finding a limit using change of variable- how come it works?

*Limit of the composition of two functions with f not necessarily being continuous.

A: Given real functions $f, g$, we can say
$$\lim_{x \to a} f(g(x)) = f\left(\lim_{x \to a} g(x)\right) \tag{$\star$}$$
in the following circumstances:

*

*If $L = \lim_{x \to a} g(x)$ exists and $f$ is continuous at $L$, or

*If $L = \lim_{x \to a} g(x)$ exists, $g(x) \neq L$ for $x$ sufficiently close to $L$, and $\lim_{x \to L} f(x)$ exists.

The second case holds in the given question (note how $g(x) \neq 2$ for $x$ close to $0$), so we can still indeed use $(\star)$.
There are finer versions of this that may be helpful in certain circumstances. Consider the following limit given the above graphs:
$$\lim_{x \to 3} f(g(x)).$$
Neither of the above conditions hold, since the limit $\lim_{x \to 1} f(x)$ does not exist. But, since $g(x) < 1$ for $x$ close to, but not equal to $3$, this tells us that
$$\lim_{x \to 3} f(g(x)) = \lim_{x \to 1^-} f(x) = 2,$$
since $g(x)$ is producing function values close to but less than $1$, and we are substituting them into $f$.
I wouldn't look for a complete set of steps to solve problems like these. Try to build an intuition for what is going on.


text:
Q: Given circle that is centered on bottom-left corner of a rect, calculate width of circle's bounding rect so its radius touches the top-right corner Given a circle that is centered on the bottom-left corner of any rectangle (square, horizontal, vertical), calculate the width of the circle's bounding rectangle so its radius touches the top-right corner of the sizing rectangle in JavaScript.
Considering the image below, I am looking for 1 JS function that can handle all 3 scenarios, given the known width and height of the rectangle.
function getCircleWidth(width: number, height: number): number {
    // return width of circle's bounding rectangle
}

UPDATE:
See the accepted answer below for the bullet proof logic for this problem, Ended up with the following with help from here https://www.omnicalculator.com/math/diagonal-of-rectangle:
function getCircleWidth(width: number, height: number): number {
    return (Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) * 2);
}

A: The width of a circle's bounding rectangle, is the circle's diameter (and that bounding rectangle is a square).
A circle's diameter is the double of its radius.
The diagonal of the given rectangle has a length that is equal to that radius.
The length of the diagonal can be derived from the right triangle it forms with the sides of that rectangle, using the Pythagorean theorem
So:
function getCircleWidth(width: number, height: number): number {
    return (width**2 + height**2)**0.5 * 2;
}


text:
Q: What are the available PHP extensions for TCP Socket Networking? I'm looking for a PHP extension that allows me to connect, bind/listen, send, and receive data on a TCP socket.
There is a PEAR package Net_Socket:
http://pear.php.net/package/Net_Socket
But this would require PEAR to be installed which we wouldn't want to do as this increases memory consumption.
Is there an available purely C extension of this?
Thanks,
Kenneth

A: a few options:

*

*PHP Sockets (available in most builds)

*PHP Streams (5+)


text:
Q: How to match text with jquery or partial matching I have this hyperlink in anchor tag
 Text

Now i want that when that page is clicked i have the page with hyperlinks like
rule-power

Is it possible that i can grab the var1 using jquery . even if its partial match it willl be good and then remove that  tag
something like
NewVar =getParameter(var1);
$.find(a).withtext(NewVar).hide()

A: You can use Artem Barger's answer here to get the querystring variable, then you can use :contains() to do a partial match, like this:
var var1 = getParameterByName('var1'); //from linked answer
$('a:contains("' + var1 + '")').hide();

Or, if you wanted an exact match, use .filter() and .text(), like this:
var var1 = getParameterByName('var1');
$('a').filter(function() {
  return $(this).text() == var1;
}).hide();


text: Q: ubuntu installed using wubi is not working I have 04 in my win7 64bit pc using wubi installer. I downloaded wubi and followed the instructions.  It worked for a few days and now Ubuntu is not booting, it shows a black screen. I uninstalled Ubuntu from the Windows control panel and re-installed but it's not working.


text:
Q: Delete and protect workbook Need your help badly
I have code that is assigned to "button" to delete the current sheet. Sheet and workbook are password protected. I am able to use the button to delete the sheet but the problem, its not protecting the workbook back. Please suggest.
Sub Deletetab()
    Application.DisplayAlerts = False
    If MsgBox("Deleting Current Sheet, Data entered on this sheet will be lost", vbOKCancel) = vbOK Then
           ThisWorkbook.Unprotect Password:="xyz"
           Application.DisplayAlerts = False
           ActiveWindow.SelectedSheets.Delete
           ThisWorkbook.Protect Password:="xyz"
           Application.DisplayAlerts = True
           Else: Exit Sub
    End If
    Application.DisplayAlerts = True
    ThisWorkbook.Protect Password:="xyz"
    End Sub

Please help.

A: You have ThisWorkbook.Protect Password:="xyz" twice in your code.
Please try the modified code below (tested and ran ok on my Excel):
Sub Deletetab()

Application.DisplayAlerts = False
If MsgBox("Deleting Current Sheet, Data entered on this sheet will be lost", vbOKCancel) = vbOK Then
    ThisWorkbook.Unprotect Password:="xyz"
    ActiveWindow.SelectedSheets.Delete
    ThisWorkbook.Protect Password:="xyz"
    Application.DisplayAlerts = True
End If
Application.DisplayAlerts = True

End Sub


text:
Q: python pickle.load() pkl file throws EOFError a friend generates a pickle file for me. As he works on python 3 while I work on python 2, so he generated the file with
pickle.dump(some_file_to_be_pickled,open("path_to_that_file","wb+"),protocol=2)

While I tried to load it with
the_file = pickle.load(open("path_to_that_file","rb"))

However, I met the EOFError, which looks like:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/pickle.py", line 1378, in load
   return Unpickler(file).load()
File "/usr/lib64/python2.7/pickle.py", line 858, in load
   dispatch[key](self)
File "/usr/lib64/python2.7/pickle.py", line 880, in load_eof
   raise EOFError
EOFError

My friend also tried to load this file on his computer with python 2 and he didn't have any problem doing that...
Any idea to fix this problem?
By the way, I am using python 2.7.5 while he is using python 2.7.10 and python 3.5.

A: I believe I had tried a something very similar and received the same result you are having; I was also running 2.7.5. When I updated to 3.4, I didn't receive the error anymore and my function ran properly, so more than likely I would say the problem is your python is outdated.


text:
Q: Parent child component event handler in loop I have created one child component and one parent component the child component gets called in from loop and event handlers also get called from prop but when i click on navlink from child component every click event is called
if first navlink is called then only handler for first navlink should be called.
import { NavLink } from "react-router-dom";
import React, { Component } from "react";
import axios from "axios";
// import SearchComponent from "../Common/SearchComponent";
// import Navbar from "../Common/Navbar";
import { CompanyId } from "../../locales/global.json";
import CategoryComponent from "./CategoryComponent";

class CategoryPageComponent extends Component {
state = {
    Categories: []
};
componentDidMount() {
    if (this.state.Categories.length === 0) this.bindCategoryData();
}
onCategorySearch = e => {
    if (this.state.Categories.length === 0 && e === "")
    this.bindCategoryData(0);
};

bindCategoryData = () => {
    var $this = this;
    axios
    .post(
        "http://fstrumplifyml.azurewebsites.net/api/ApiCategory/GetCategories",
        {
        companyid: CompanyId,
        languageid: 1
        }
    )
    .then(function(response) {
        $this.setState({
        Categories: response.data.Data
        });
    });
};
UpdateSubCategories = (categories, categoryId) => {
    console.log(categories);
};
renderCategoryComponent = category => {
    return (
    <CategoryComponent
        Category={category}
        OnUpdateSubCategories={this.UpdateSubCategories.bind(this)}
    />
    );
};
render() {
    return (
    <React.Fragment>
        {/* <Navbar /> */}

            {/* <SearchComponent onSearch={this.onCategorySearch} /> */}

            {this.state.Categories.map(this.renderCategoryComponent)}

    </React.Fragment>
    );
}
}
export default CategoryPageComponent;

import React, { Component } from "react";
import { NavLink } from "react-router-dom";

class CategoryComponent extends Component {
  render() {
    return (

          <NavLink
            to={this.props.OnUpdateSubCategories(
              this.props.Category.SubCategories,
              this.props.Category.CategoryId
            )}
          >

          </NavLink>
          <NavLink
            className="block"
            to={this.props.OnUpdateSubCategories(
              this.props.Category.SubCategories,
              this.props.Category.CategoryId
            )}
          >

{this.props.Category.CategoryName}

          </NavLink>

    );
  }
}

export default CategoryComponent;

A: <NavLink
  className="block"
  to={this.props.OnUpdateSubCategories(
     this.props.Category.SubCategories,
   this.props.Category.CategoryId
 )}
>

when you put a function call inside props, it will be called everytime when render() runs
you can use arrow functions in props
to={
()=>{this.props.OnUpdateSubCategories(
     this.props.Category.SubCategories,
   this.props.Category.CategoryId
 )}
}

but a function instance will be created in every render
so it is better to create a function inside CategoryComponent


text:
Q: VBA Access with Variables whats wrong to my code all I want is to update table using Name and Pin of the Employee on their corresponding ID but any pin is accessible to the other Employee please help me!
Dim CanteenPOS As DAO.Database
Dim tblEmployee As DAO.Recordset

Set CanteenPOS = CurrentDb

Dim ID As Integer

If IsNull(Me.txtName) Or IsNull(Me.txtPin) Then
    MsgBox "First! Please enter your EmployeeID before PinID", vbInformation
    Me.txtName.SetFocus
Else
    If (IsNull(DLookup("EmployeeID", "tblEmployeeID", "EmployeeID = '" & Me.txtName & "'"))) Or _
       (IsNull(DLookup("PinID", "tblEmployeeID", " PinID = '" & Me.txtPin & "'"))) Then
        MsgBox "Invalid EmployeeID or PinID!"
    Else
        Me.txtUsername = DLookup("[EmployeeID]", "tblEmployeeID", "[EmployeeID] = '" & Me.txtName.Value & "'")
        Me.txtPin = DLookup("[PinID]", "tblEmployeeID", " [EmployeeID] = '" & Me.txtName.Value & "'")

        MsgBox ("Your transaction is completed!")
        Set tblEmployee = CanteenPOS.OpenRecordset("tblEmployee")
        tblEmployee.AddNew
        tblEmployee("EmployeeName").Value = Me.txtName
        tblEmployee("OrderName").Value = Me.txtOrderType
        tblEmployee("Price").Value = Me.txtprice
        tblEmployee("Datetime").Value = lblDate.Caption
        tblEmployee("AddOn").Value = Me.txtAdd
        tblEmployee.Update
    End If
End If

A: I think the problem is after the "Or" in this second "If":
If (IsNull(DLookup("EmployeeID", "tblEmployeeID", "EmployeeID = '" & Me.txtName & "'"))) Or _
   (IsNull(DLookup("PinID", "tblEmployeeID", " PinID = '" & Me.txtPin & "'"))) Then
    MsgBox "Invalid EmployeeID or PinID!"

You are checking to see that both the EmployeeID and PinID are in the database, but you are NOT checking to see that they are on the SAME record! As long as SOMEBODY has the pin, the test will pass!
Compare that with the way you find the PinID on the record retrieved by looking up the EmployeeID in the Else that follows.
Just find the record using EmployeeID, then find the PinID to go with that EmployeeID. Then compare the PinID found with the PinID entered by the user to be sure they match before saving the new data.
By the way, DLookup is not the most efficient way to get this information. The Execute command used with SQL (or with a saved query) can get you the PinID when you look up the EmployeeID without having to do a second DLookup. (And if you are not sure how to write the SQL, create a regular Access query and then look at the SQL view. That will show you what you need.)
(C. Perkins' comment about security has some merit, but if you are merely trying to keep honest people from making honest mistakes - like mistyping their EmployeeID by one number - then making sure the EmployeeID and PinID match might be enough for your purposes. They probably keep their EmployeeID and PinID together where other employees can see them anyway ;-)


text:
Q: Microsoft SQL Server 2012 merge data of exactly two adjacent rows into one row current state of #master table:

I've been trying to formulate a SELECT query to achieve following by picking Value column of exactly two adjecent rows and then placing it on a single row in two columns.

My solution so far:
clone the master table.

*

*Select first row Value from master table.

*Then join master table with the clone on Id and pick the value from +1 incremented id...

*Skip the next Id from master

*repeat step 1-3 till end of master table
 select *
into #clone
from #master

Select Value AS Value1 from #master
       Value AS Value2 from #clone
inner join #clone
  ON #master.Id /*(incremented id)*/ = #clone.Id /*(incremented id)*/
-- skip the next id of #master```

stuck on increment and skipping the next id part of #master table...

A: For creating the table and inserting some values
create table mastertable
(
id int,
Name varchar(20),
ParentID int,
Value varchar(50)
)

insert into mastertable values(86, 'Description1',83,'021541-sds2-45515')
insert into mastertable values(87, 'value1',83, '$247.56')
insert into mastertable values(90, 'Description3',83, '021541-sds2-45567')
insert into mastertable values(91,'value3',83, '$66.72')
insert into mastertable values(94, 'Description5',83, '021541-sd72-47715')
insert into mastertable values(95,'value5',83, '$57.11')

Now, try this query:
with m1 as
(
SELECT *, RN = ROW_NUMBER() OVER (order by id) FROM mastertable
),
m2 as
(
SELECT *, RN = ROW_NUMBER() OVER (order by id) FROM mastertable
)

SELECT m1.id, m1.name, m1.parentid, m1.value as value1, m2.value as value2
FROM  m1 left join  m2
ON m1.RN = m2.RN-1
WHERE  m1.RN%2 != 0

EDIT:
For m2, instead of SELECT *, you could also use:
m2 as
(
SELECT id,value, RN = ROW_NUMBER() OVER (order by id) FROM mastertable
)


text:
Q: Unitils dataset - insert into sybase datetime column I have a unitils dataset attempting to enter data into a sybase datetime column, but it errors when I try and run the unit tests.
I cannot find anything online about inserting dates, so I tried declaring it as a String in the same way as the other columns, but I get the error:
org.unitils.core.UnitilsException: Error inserting test data from DbUnit dataset for method etc etc
    at org.unitils.dbunit.DbUnitModule.insertDataSet(DbUnitModule.java:156)
    at org.unitils.dbunit.DbUnitModule$DbUnitListener.beforeTestSetUp(DbUnitModule.java:556)
    at org.unitils.core.Unitils$UnitilsTestListener.beforeTestSetUp(Unitils.java:273)
    at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runBeforesThenTestThenAfters(UnitilsJUnit4TestClassRunner.java:151)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.unitils.UnitilsJUnit4TestClassRunner.invokeTestMethod(UnitilsJUnit4TestClassRunner.java:95)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
    at org.unitils.UnitilsJUnit4TestClassRunner.access$000(UnitilsJUnit4TestClassRunner.java:44)
    at org.unitils.UnitilsJUnit4TestClassRunner$1.run(UnitilsJUnit4TestClassRunner.java:62)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.unitils.UnitilsJUnit4TestClassRunner.run(UnitilsJUnit4TestClassRunner.java:68)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.unitils.core.UnitilsException: Error while executing DataSetLoadStrategy
    at org.unitils.dbunit.datasetloadstrategy.impl.BaseDataSetLoadStrategy.execute(BaseDataSetLoadStrategy.java:46)
    at org.unitils.dbunit.DbUnitModule.insertDataSet(DbUnitModule.java:230)
    at org.unitils.dbunit.DbUnitModule.insertDataSet(DbUnitModule.java:153)
    ... 18 more
Caused by: org.dbunit.dataset.datatype.TypeCastException: Error casting value for table 'USER' and column 'SUSPEND_SD'
    at org.dbunit.operation.AbstractBatchOperation.execute(AbstractBatchOperation.java:202)
    at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:78)
    at org.unitils.dbunit.datasetloadstrategy.impl.CleanInsertLoadStrategy.doExecute(CleanInsertLoadStrategy.java:45)
    at org.unitils.dbunit.datasetloadstrategy.impl.BaseDataSetLoadStrategy.execute(BaseDataSetLoadStrategy.java:44)
    ... 20 more

The only line inserting a date in my dataset is:
<USER ID="4" FULL_NAME="user3" SUSPEND_SD="25/12/2011 00:00" SUSPEND_ED="25/12/2013 00:00" PASSWORD="password3"/>

Can anyone help?
Thanks in advance.

A: Ok, it turns out it has to be in exactly the format YYYY-MM-DD HH:MM:SS", for example "2011-01-01 02:00:00".

A: I don't know how unitils works but assuming your dataset is editable why not change the dates to yyyy/mm/dd format.
That java stack mentions casting, and that'll be a failure getting dd/mm/yyyy to datetime I'd think.
Alternatively the middleware probably has some date config means - you can probably tell it dates are British (it might even be regional settings?)


text:
Q: mysql-connector-java update from 5 to 6 causes a timeshift In our java(1.8) / hibernate(4.3.2) / mysql (5.6.29-76.2) application we are using mysql-connector-java 5.1.40.
Timezones for all servers(java, mysql) is UTC.
When in the application we were inserting some datetimes '2016-10-26 08:00:00' into the DB, they were saved correctly as '2016-10-26 08:00:00'.
After upgrading mysql-connector-java to 6.0.4, we get the following behavior: in the java code we insert '2016-10-26 08:00:00', in the DB we get '2016-10-26 13:00:00', when we select those values in the java app we get the correct '2016-10-26 08:00:00' value. However, all previously saved values get shifted into the past.
So far, we have no idea, what is causing this shift. Any ideas?
Update
After running multiple tests with time zones, I have noticed the following:

Timezones for all servers(java, mysql) is UTC.
  This was wrong, and in fact it was a BST(British Summer Time)

Other time zones (CEST, UTC, GMT+6, Asia/Almaty, GMT-6 etc.. ) were working fine, BST causes those shifts. So, I am about to make a conclusion that there's some bug related to the BST time-zone in mysql-connector.
As a workaround - switching to some other time zones.


text:
Q: Lispy way to read user input from the keyboard in Clojure? I am writing a function for my Clojure program that reads user input from the keyboard.  If the user enters invalid input, the user is warned and then prompted again.  When using a procedural style in a language like Python, I would do something like this:
while 1:
    value = input("What is your decision?")
    if validated(value):
        break
    else:
        print "That is not valid."

The best I can come up with in Clojure is this:
(loop [value (do
               (println "What is your decision?")
               (read-line))]
  (if (validated value)
    value
    (recur (do
             (println "That is not valid.")
             (println "What is your decision?")
             (read-line)))))

This works, but it is redundant and seems verbose.  Is there a more Lispy/Clojurey way to do this?

A: Factor out the println/read-line combo into a get-line function:
(defn get-input [prompt]
  (println prompt)
  (read-line))

(defn get-validated-input []
  (loop [input (get-input "What is your decision?")]
    (if (valid? input)
      value
      (recur (get-input "That is not valid.\nWhat is your decision?")))))

This is basically what your Python version does; the difference is that get-input is built-in for Python.

A: (defn input []
   (println "What is your decision?")
   (if-let [v (valid? (read-line))]
      v
      (do
         (println "That is not valid")
         (recur)))


text:
Q: Box (div) is placed lower than the first? I'm trying to make different boxes that are placed in the same line using CSS.
However, without any style rule (at least that I've noticed) making it do so, the second box is lower than the first. Why is that? How can I fix it?
If you have any question, feel free to ask, I'll do my best to answer.
Thank you in advance.
Code snippet below.
JSFiddle

.index-links {
  width: 90%;
  position: relative;
  left: 5%;
  padding: 1%;
}
.index-link {
  display: table-cell;
  height: 150px;
  width: 150px;
  border: 2px solid black;
  margin: 1%;
  padding: 0.5%;
  text-align: center;
  vertical-align: middle;
  position: relative;
  cursor: pointer;
  float: left;
}
.index-link > .index-link-perms::before {
  content: " | "
}

Link 1Access: Everyone

Link 2Access: SM

A: Remove the br tag between the divs.

Link 1Access: Everyone

Link 2Access: SM

A: change the CSS as below
.index-links {
  display:flex;
  width: 90%;
  position: relative;
  left: 5%;
  padding: 1%;
}


text:
Q: How to know if model is used from Rake? In a model, I include a module used by a Rake task.
I would like to do this include only for rake and not for Rails.
I didn't find any method to know if the model is used by  Rails or Rake.
I use Rails3.0.beta3.
If you have any idea i would be glad to hear them :)
Thanks

A: You can solve your problem with defined variable.
You define a variable into your rake task
RAKE_TASK = true

And in your model you test it with defined?
if defined? RAKE_TASK
def your_method

end


text:
Q: How to get data from an api in r? I am new to api stuff and have come across a small piece of code in python to retrieve data which I would like to replicate in r:
python code:
import requests
import json
from datetime import date
import time
import smtplib, ssl

#API URL
url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'
headers = {'accept': 'application/json','Accept-Language' : 'hi_IN','User-Agent': 'Mozilla/4.0'}
result = requests.get(url, headers=headers)
#Print state ID
print(result.content.decode())

Results:

{"states":[{"state_id":1,"state_name":"Andaman and Nicobar
Islands"},{"state_id":2,"state_name":"Andhra
Pradesh"},{"state_id":3,"state_name":"Arunachal
Pradesh"},{"state_id":4,"state_name":"Assam"},{"state_id":5,"state_name":"Bihar"},{"state_id":6,"state_name":"Chandigarh"},{"state_id":7,"state_name":"Chhattisgarh"},{"state_id":8,"state_name":"Dadra
and Nagar Haveli"},{"state_id":37,"state_name":"Daman and
Diu"},{"state_id":9,"state_name":"Delhi"},{"state_id":10,"state_name":"Goa"},{"state_id":11,"state_name":"Gujarat"},{"state_id":12,"state_name":"Haryana"},{"state_id":13,"state_name":"Himachal
Pradesh"},{"state_id":14,"state_name":"Jammu and
Bengal"}],"ttl":24}

Info about API:
url: 'http://cdn-api.co-vin.in/api/v2/admin/location/states'
from: https://apisetu.gov.in/public/marketplace/api/cowin#/Metadata%20APIs/states

from: https://github.com/cowinapi/developer.cowin/issues/339
(Note: cowin API are restricted to be accessed only in INDIA. So I guess many of you will not be able to use it. But it will be still helpful if you could suggest some code changes.)
R
I have googled abit and tried below pieces of code but none of them worked so far:
library(tidyverse)
library(rjson)
library(jsonlite)
library(RCurl)
library(httr)

states_url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'

headers = c({'accept' = 'application/json'},
            {'Accept-Language' = 'hi_IN'},
            {'User-Agent' = 'Mozilla/4.0'})

url(states_url, headers = headers)

GET(states_url)$content

GET(states_url)$headers

Update
I have tried this and it didnt give error but not sure what to do next:
states_url = 'http://cdn-api.co-vin.in/api/v2/admin/location/states'

headers = c('accept' = {'application/json'},
            'Accept-Language' = {'hi_IN'},
            'User-Agent' = {'Mozilla/4.0'})

url(states_url, headers = headers)

A connection with
description "http://cdn-api.co-vin.in/api/v2/admin/location/states"
class       "url-wininet"
mode        "r"
text        "text"
opened      "closed"
can read    "yes"
can write   "no"

GET(states_url, header = headers)$content

1 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c  [20] 49 43 20 22 2d 2f 2f 57 33 43 2f 2f 44 54 44 20 48 54 4d  [39] 4c 20
34 2e 30 31 20 54 72 61 6e 73 69 74 69 6f 6e 61 6c  [58] 2f 2f 45 4e
22 20 22 68 74 74 70 3a 2f 2f 77 77 77 2e 77  [77] 33 2e 6f 72 67 2f
54 52 2f 68 74 6d 6c 34 2f 6c 6f 6f 73  [96] 65 2e 64 74 64 22 3e 0a
3c 48 54 4d 4c 3e 3c 48 45 41 44 [115] 3e 3c 4d 45 54 41 20 48 54 54
50 2d 45 51 55 49 56 3d 22 [134] 43 6f 6e 74 65 6e 74 2d 54 79 70 65
22 20 43 4f 4e 54 45 [153] 4e 54 3d 22 74 65 78 74 2f 68 74 6d 6c 3b
20 63 68 61 7

str(GET(states_url))

List of 10
 $ url        : chr "http://cdn-api.co-vin.in/api/v2/admin/location/states"
 $ status_code: int 403
 $ headers    :List of 9
  ..$ server        : chr "CloudFront"
  ..$ date          : chr "Tue, 25 May 2021 12:39:02 GMT"
  ..$ content-type  : chr "text/html"
  ..$ content-length: chr "919"
  ..$ connection    : chr "keep-alive"
  ..$ x-cache       : chr "Error from cloudfront"
  ..$ via           : chr "1.1 85ad220378d99bdabeb6c46016f1cf16.cloudfront.net (CloudFront)"
  ..$ x-amz-cf-pop  : chr "BOM51-C1"
  ..$ x-amz-cf-id   : chr "eeJq5ZtSJHZkLGoJZBTUL2xL5PcU2gjesnY7Qmg_kMnxZxZ1JUHPWA=="
  ..- attr(*, "class")= chr [1:2] "insensitive" "list"
 $ all_headers:List of 1
  ..$ :List of 3
  .. ..$ status : int 403
  .. ..$ version: chr "HTTP/1.1"
  .. ..$ headers:List of 9
  .. .. ..$ server        : chr "CloudFront"
  .. .. ..$ date          : chr "Tue, 25 May 2021 12:39:02 GMT"
  .. .. ..$ content-type  : chr "text/html"
  .. .. ..$ content-length: chr "919"
  .. .. ..$ connection    : chr "keep-alive"
  .. .. ..$ x-cache       : chr "Error from cloudfront"
  .. .. ..$ via           : chr "1.1 85ad220378d99bdabeb6c46016f1cf16.cloudfront.net (CloudFront)"
  .. .. ..$ x-amz-cf-pop  : chr "BOM51-C1"
  .. .. ..$ x-amz-cf-id   : chr "eeJq5ZtSJHZkLGoJZBTUL2xL5PcU2gjesnY7Qmg_kMnxZxZ1JUHPWA=="
  .. .. ..- attr(*, "class")= chr [1:2] "insensitive" "list"
 $ cookies    :'data.frame':    0 obs. of  7 variables:
  ..$ domain    : logi(0)
  ..$ flag      : logi(0)
  ..$ path      : logi(0)
  ..$ secure    : logi(0)
  ..$ expiration: 'POSIXct' num(0)
  ..$ name      : logi(0)
  ..$ value     : logi(0)
 $ content    : raw [1:919] 3c 21 44 4f ...
 $ date       : POSIXct[1:1], format: "2021-05-25 12:39:02"
 $ times      : Named num [1:6] 0 0.242 0.283 0.284 0.321 ...
  ..- attr(*, "names")= chr [1:6] "redirect" "namelookup" "connect" "pretransfer" ...
 $ request    :List of 7
  ..$ method    : chr "GET"
  ..$ url       : chr "http://cdn-api.co-vin.in/api/v2/admin/location/states"
  ..$ headers   : Named chr "application/json, text/xml, application/xml, */*"
  .. ..- attr(*, "names")= chr "Accept"
  ..$ fields    : NULL
  ..$ options   :List of 2
  .. ..$ useragent: chr "libcurl/7.64.1 r-curl/4.3.1 httr/1.4.2"
  .. ..$ httpget  : logi TRUE
  ..$ auth_token: NULL
  ..$ output    : list()
  .. ..- attr(*, "class")= chr [1:2] "write_memory" "write_function"
  ..- attr(*, "class")= chr "request"
 $ handle     :Class 'curl_handle' <externalptr>
 - attr(*, "class")= chr "response"
Show in New Window

http_status(GET(states_url))

$category
[1] "Client error"

$reason
[1] "Forbidden"

$message
[1] "Client error: (403) Forbidden"

stringi::stri_enc_detect(GET(states_url, header = headers)$content)

[[1]]
     Encoding Language Confidence
1  ISO-8859-1       en       0.54
2  ISO-8859-2       ro       0.26
3       UTF-8                0.15
4    UTF-16BE                0.10
5    UTF-16LE                0.10
6   Shift_JIS       ja       0.10
7     GB18030       zh       0.10
8      EUC-JP       ja       0.10
9      EUC-KR       ko       0.10
10       Big5       zh       0.10
11 ISO-8859-9       tr       0.06
12 IBM424_rtl       he       0.02
13 IBM424_ltr       he       0.01

content(GET(states_url, header = headers), encoding = "UTF-8")

{html_document}

[1] \n<meta http-equiv="Content-Type" content="text/htm ...
[2] \n
403 ERROR
\n
The request could not be  ...

content(GET(states_url, header = headers), encoding = "ISO-8859-1")

{html_document}

[1] \n<meta http-equiv="Content-Type" content="text/htm ...
[2] \n
403 ERROR
\n
The request could not be  ...

python code image:

A: You make headers but never include them in your call to GET. Use them there.
GET(states_url, add_headers(headers))