« first day (4316 days earlier)      last day (615 days later) » 

12:00 AM
stackoverflow.com/questions/51336185 Okay, I know we have like a million different takes on this lying around. But I have no idea how to round it up and canonicalize it properly.
I suppose the best way is to get Ned Batchelder to convert his essay into Stack Overflow QA form.
actually hmm, I guess stackoverflow.com/questions/575196 is our canonical.
although that doesn't neatly duplicate the first question at all.
 
12:37 AM
@HenryEcker re the reassigning-to-builtin thing, I kinda feel like just using stackoverflow.com/questions/6039605/… with a new title (again)
it isn't really possible to make a "generic" example, because there isn't a "generic builtin" to assign to.
but that isn't really ideal, because again there are plenty of existing answers that focus on the specific error and show other, completely different causes
the thing is, there's plenty of use for a dictionary that maps <error message> -> <list of common causes>. But there's also plenty of use for an encyclopedia that maps <general pattern of cause> -> <understanding of why there's a problem, what errors can happen, what to do instead>.
and these are completely separate things, that are both made worse by being tangled together
 
1:07 AM
I have some issues with csv module. I'm writing a file "open('output_file_1.csv', 'w', newline='\n', encoding='utf-8')" like this, but it's adding ^M character along with newline. I changed everything for universal encoding but I am still having issues. Any reasons why?
 
1:18 AM
^M is the "carriage feed" or "carriage return" character - see this ASCII table. It's also represented as \r. Windows uses \r\n as its line continuation characters, while Unix just uses \n.
Not sure why it's happening, though, when you specified newline='\n'.
Can you show some more of your code, specifically where you set up the CSVWriter? Check out the code formatting guide so it looks proper.
 
2:18 AM
https://chat.stackoverflow.com/transcript/message/55039975#55039975

We do have this; it is https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int
stackoverflow.com/questions/48607319/rotating-strings-in-python There are a lot of unmarked duplicates of this floating around. This is the best version I can find.
 
2:39 AM
in this line here selclient = webdriver.Chrome(options=opt) what aspect of the python language is it to pass an expression with an = sign in it, to a function?
 
3:16 AM
That's called a keyword argument. You can search for it in the Glossary: docs.python.org/3/glossary.html
 
 
5 hours later…
7:54 AM
hello everyone, I have a powershell script and I would like to extract the value of certain variables, $MyVariable = 1, 2, 3 in this case I would want 1, 2, 3 as an output, should I write regexes or is there a better way
the spaces between = and other things, would actually make something like line.split("=") break
 
If you just need it to work for simple cases, I'd select lines .startswith("$") then .partition("=").
 
I did try that, if it narrows down things, the variables I am interested are only strings and they might also have = as part of the string
 
Not sure if regex is sufficient if you want to handle complex cases, since it'll just fail a bit later; using a parser might be better then but also a bit of work.
Can you give an example of the most complex case?
 
sure, so far I am trying to at least "capture" these two `$variableOne = 'https://xxx.xxx.com/xxx/xxx/xxx?BundleId=xxx'`
and `$variable2='https://xxx.xxx.com/xxx/xxx/xxx?BundleId=xxx'`
 
That should be appropriate for regex.
 
8:03 AM
regex it is, thank you for your time
 
\$(.*)\s*=\s*('[^']*') should match both the variable name and the string.
 
wow, this even works with indented code, thought I would have to add \s* at both ends
 
You only need to add \s* if you use re.fullmatch. With re.match you only need it on the left, and with re.search you don't need it at all
 
I was just trying this with regex101, not sure what it uses
 
re.findall :P
 
8:10 AM
Not sure about Powershell syntax, it might be worth prepending ^\s* to avoid nested (if there are keyword arguments) or commented "assignments".
 
I can make do with re.findall, once its back to python land I can probably hack something up with startswith("#")
my biggest trouble here is (was) in getting things to python
 
8:30 AM
Coming back to my signal handler problem from a few days ago... how does one test Ctrl+C signal handlers?
I'm using pytest and when my test sends SIGINT to the process, pytest just aborts all tests even though it's wrapped in a with block to expect KeyboardInterrupt.
 
by test, do you mean like, catching it without being terminated by the said signal?
 
Monkeypatch a function and make it throw KeyboardInterrupt?
 
I don't recall if you can catch such signal with a try expect block, but I think it should be possible for Ctrl+C.
 
@Aran-Fey I want to explicitly test that my handling of signal handlers works, so monkey patching anything of that would defeat the point.
 
don't know if it'll help but: stackoverflow.com/a/26159031/12349101
the other answers could work better although they use unittest
 
8:39 AM
A subprocess sounds like a good idea, since apparently pytest is intercepting the signal
 
8:53 AM
@Valencia the bulletproof approach would be to search the script's abstract syntax tree for assignment statements that involve MyVariable. You'd have to write the AST searching code in PowerShell. I don't have any concrete advice there, but it shouldn't be too painful, going by the linked document.
You might not even need to use recursion! Luxury!
 
9:18 AM
You can't use regex to parse Powershell's double-quoted string literals, for the same reason you can't parse Python's f-string literals: they may contain embedded expressions, which are defined using recursive grammar rules. "foo $((((((((((1)))))))))) bar" is a valid PowerShell string. Delete one of the right parens, and it becomes invalid. Regex isn't smart enough to ensure the parens are balanced.
 
it's less "regex isn't smart enough" and more "the language is not regular"
 
Yes :-)
PowerShell's single-quoted string literals, on the other hand, do not allow embedded expressions, so you might have a chance of matching one with regex. You just need to implement the logic of verbatim-string-literal. You don't even need to watch out for escape sequences such as \n! Luxury!
 
@Kevin A lot of these problems go away if you just assume "it's valid syntax", which should work well if the script is already in use.
 
9:36 AM
You could probably get to 99.99% bulletproof by assuming away the hardest parts, but what if you get shot with 10,000 bullets the next day?
 
@Kevin Hopefully you've built your house of cards just right so that some early step catches the bullet instead of Paul from maintenance unit 3, who has to keep pushing the dead man switch for the doomsday device.
 
@MisterMiyagi Programmers should be the first line of one's defenses, because of their strange knack of getting shot in the foot instead of anywhere else
 
Armored boots fix everything!
 
@Kevin plus you don't need an age limit for them because we're all adults
 
Well, perhaps not bootstrapping problems...
 
9:47 AM
Question to all: In other programming language like "Dart", a map function can be called on a literal (eg. dict) by writing dot(.) after, but in Python a map method takes two args, a tuple and a function. we cant use dot to call map function on a literal. Why is that?
 
outrage!
@discoMonkey What's a map function?
 
@discoMonkey can you name situations where python functions (not types) get attributes looked up with . after? I can think of one or two but they are not very common.
The thing about Python functions is that you call them by putting ( after, and then eventually a ).
one could say this is one of the quirks of the Python language
 
@Kevin The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter. Syntax, map(function, iterables)
 
If we're talking about the actual builtin function whose name is "map", you can supply literals to that. For example map(str.upper, "foobar"). You can't do "foobar".map(str.upper) because map isn't a method of str.
You can't do map(str.upper, "foobar".) because... That's just not something that Python was designed to do.
 
9:53 AM
@Kevin you can't?
oh, not with that period, no
 
Equally validly, I might ask why Dart doesn't let you do "foobar"Kevin. Seems like a poor choice to forbid the Kevin operator, which protects against several security vulnerabilities, and emits a pine fresh scent
 
@discoMonkey Because . serves for namespacing. The entire point of obj.method is to look up the name method in the obj namespace. Falling back to unrelated namespaces would complicate the rules for that immensely.
 
@Kevin Are you sure it doesn't let you do that? It sounds like a pretty nifty language.
 
For .map specifically, it takes multiple iterables so treating it as a method of one iterable would be plain wrong even for semantics.
If anything, it would be a method of functions.
 
It's a violation of the RFC specification for the Kevin operator to implement it without sending me a royalty check
 
9:59 AM
@discoMonkey Does dart have traits or similar?
 
This reminds me of the Python syntax riddle of: why is "foobar".__init__ valid syntax, but 1.__init__ isn't?
 
Python does love its significant whitespace
 
10:47 AM
so I know one of the way to convert a binary string to an int: int("10110", 2) but how do I do the reverse? result of the example is "22" so do I just convert that to a binary string?
 
format(22, 'b')
 
>>> f'{22:b}'
'10110'
yeah, that
bin(22) has a 0b prefix
 
nice, Thanks :)
 
11:03 AM
@Kevin this looks advanced, but if I did manage to get this working, how would I get the result in python? I have to make powershell write it to a file and read it in python / print to stdout so I can then parse that output using subprocess?
 
I would probably have PowerShell print it to stdout, and have Python use subprocess, yeah
 
thank you
 
-2
Q: Print the count of lines after a certain word

rowocI have a file that contains a lot of line data. I need to count line numbers after a specific word in a file. file.txt Lorem ipsum dolor sit amet, at pro paulo facilis | end -l. voluptaria, sit eu graeci eirmod intellegebat How to get the count of number of lines present after end -l. line i...

can anyone please provide the inputs for the above ask
 
If ASTs seem daunting, maybe regex would be good enough for your particular problem. Maybe you don't need to parse all possible kinds of string literals. The more you know about the kind of input you'll see, the easier it is to parse them. "strings that definitely will never contain a sub-expression" are easier to parse than all possible strings. "strings that contain only letters and digits" are even easier than that.
 
11:30 AM
they also made a module based on this too.
 
I'd prefer subprocess.check_output over subprocess.run, but whatever floats one's boat
 
I prefer subprocess.Popen :P
 
Valid
 
12:09 PM
file.txt

mkdir data
docker run |......| scp file
cd dist
docker run |......| gofmt -l.
grep -nr "file"
mv file file_bk

Count number of lines after "gofmt -l."

tried below approach but count giving as 0

count_line.py

fname="file.txt"
def file_len(fname):
with open(fname) as f:
for line in f:
if line.strip() == "gofmt -l.":
break
print(sum(1 for line in f))
file_len(fname)
 
@rowoc Do you understand what the line if line.strip() == "gofmt -l.": does?
Then I recommend you focus on understanding that first, instead of trying to find the entire solution at once.
 
strip removes any leading spaces at the beginning and end
 
For the case you want to match, line = "docker run |......| gofmt -l.\n"
 
yes with giving full line , I am able to get the correct count , but requiremnt is to find that specific word and then count after that
 
So where does that leave you with the code you've found? What check should it perform instead?
 
12:16 PM
It should find the condition "gofmt -l." and give lines count after that
 
That's the entire task again.
 
Is the required task possible?
can line.endswith will work?
 
@rowoc Yes.
@rowoc If you are always looking for tokens at the end, yes.
 
Depends on what you want to do. Do you want to check if the line contains gofmt -l. or do you want to check if the line ends with gofmt -l.?
 
@Aran-Fey any approach would be fine
 
12:37 PM
@rowoc He's asking about the specification of your task really, rather than the approach. See MisterMayagi's comment above (my emphasis) "If you are always looking for tokens at the end, yes." Using endsWith will work if you can guarantee that the string you are looking for occurs at the end of the line (i.e. strictly no other character follows it)
 
@JRichardSnape yes I am sure string "gofmt -l" will be always at be end.
mkdir data
docker run |......| scp file
cd dist
docker run |......| gofmt -l.
grep -nr "file"
mv file file_bk

Count the number of lines after the end of string "gofmt -l."
Expected Output: 2
 
We know the requirements and we know that endswith will work. Problem solved :-)
 
@Kevin Hurrah! ;)
 
On Windows, is signal.SIGINT equivalent to signal.CTRL_C_EVENT?
 
No idea. If you have code that will tell you the answer if it is run on Windows, I'll be happy to run it.
 
12:45 PM
import signal
print(signal.CTRL_C_EVENT == signal.SIGINT)
At least I guess so. :D
 
>>> import signal
>>> print(signal.CTRL_C_EVENT == signal.SIGINT)
False
 
@MisterMiyagi Sounds like a hard problem hiding inside an innocuous question :D
 
Oh my, that is unfortunate...
Thanks
 
@Kevin Okay
 
@Kevin any chance that their values are the same?
signal.SIGINT.value, signal.CTRL_C_EVENT.value
it's an IntEnum so unlikely
 
12:56 PM
Nope, Values seem to be different
 
0...? That's quite suspicious
 
>>> import signal
>>> signal.CTRL_C_EVENT
<Signals.CTRL_C_EVENT: 0>
>>> signal.SIGINT
<Signals.SIGINT: 2>
windows 11 btw, but don't think it matters. At least I hope it doesn't
 
unless they are defined alphabetically
(but no, they aren't)
I do have a missing 0 index in my linux Signals
 
I figured out , Now its working withendswith

if line.strip().endswith("end -l.")
 
A bet : SIGINT (value 2) not supported on Windows if you try to send it.
 
1:02 PM
It is...
Kills the process clean.
 
ctrl_c_event seems to be windows only
 
it's short for SIGNAL INTELLIGENTLY TERMINATE
 
@AndrasDeak--СлаваУкраїні That's why I thought Windows wouldn't support it :D
 
I've found this SO Q&A and I'm pretty sure that I've opened a can of mind eating worms.
SIGINT on Unix: Let's shut down nice and slowly. SIGINT on Windows: Yarglohmygodahaahthepainyarghh....
 
1:04 PM
@rowoc Well done :-) that's how I would do it too.
 
@MisterMiyagi Mmmm. That question describes what I thought might happen (i.e. "I'm Windows, I know nothing of your graceful termination signals").
 
This makes me feel better of my own status: "I'm a Windows programmer. I know nothing of termination signals"
 
You could fit my signal knowledge in a teacup. "signals are a way to send simple messages to other processes. They're very fast. I think."
 
I'm also developing on Windows currently. I also have to interface with Matlab. Both of these things have reminded me why I am anti-proprietary software.
 
1:08 PM
@JRichardSnape I hope MEX is involved
 
Some intrepid transistor watching the electrons that go into the cpu so it can leap into action when it sees a sigint
 
@AndrasDeak--СлаваУкраїні I'm definitely more angry more often with Mathworks than Microsoft. Simulink models with a bit of embedded Stateflow. I estimate the entirety of Matlab freezes about 3 times on an average day. Usually because I'm doing something complex like renaming a variable. I'm moving as much as possible into Python...
 
the ctrl-C signal is the process equivalent of "mom says it's my turn on the XBox"
 
@JRichardSnape you can run Python in MATLAB, you know :>
 
How do I remove the carriage variable from my csv output file from csv module? I am writing file in linux, and production env is also in linux.
 
1:21 PM
I'm surprised universal newlines don't remove them automatically
 
How are you opening the files for writing?
 
12 hours ago, by Jack Daniels
I have some issues with csv module. I'm writing a file "open('output_file_1.csv', 'w', newline='\n', encoding='utf-8')" like this, but it's adding ^M character along with newline. I changed everything for universal encoding but I am still having issues. Any reasons why?
 
Aha
 
@JackDaniels consider responding to questions next time?
I don't know what it is today
 
Dude I went offline. I am just looking to format my input.
 
Cbg, everyone
 
Whenever I ask a question in the C# room etc, I worry that I won't be able to hang around to answer follow-up questions. "I need to attend a meeting in two hours... Maybe I should wait until tomorrow when I have more free time"
 
@Kevin in which case you would read replies later before asking again, yes?
 
Yes, although I do that anyway even in non-question contexts
 
1:26 PM
Yeah I read those replies, they didn't mention the solution. So I thought of asking again.
 
What's up with you people anyways? It's been like this for a long time.
 
@AndrasDeak--СлаваУкраїні Indeed I do. I've already discovered a bug in pyenv when using a venv. My colleague filed it with Mathworks and it's going into the next release.
 
@JackDaniels it might make you feel better that we have a strict 100% money back guarantee
@JRichardSnape oof
 
@JackDaniels try opening the file in binary write mode...
 
1:28 PM
file = open('output_file_1.csv', 'w', newline='\n', encoding='utf-8')
Here's the file opening, after that I just writerow
@JonClements like 'w+b'?
 
@JackDaniels writerow where the last column ends with a carriage return
 
@JackDaniels just wb
 
Alright, let me try that. I'll get back with the result.
 
@MisterMiyagi I played around with the signal module on windows 10....I didn't dig too deeply but from my experience, there a lot, and I mean a lots of signal from windows that isn't implemented in the local signal module. I ended up using taskkill cmd command through subprocess. Although, there is windows-kill but it's in C++.
 
@JonClements I have strings, do I need wrapper or something to write in csv?
 
1:36 PM
You can write anything you want into a file regardless of whether its file extension is ".csv" or anything else. It's all just pipes from Python's perspective.
 
There's a CSV module with a writer() function built into Python
 
I was just about to recommend the csv module myself. Handy little thing.
 
I am using csv module
 
good, good
 
But it's addiing carriage ^M to every line along with newline
 
1:39 PM
@Kevin omg I kevin'd kevin. I'm hereby no longer a noob.
It's randomhopeful, by the way. To those who remembers.
 
Your Kevin'd Kevin Certificate is in the mail
 
@AndrasDeak--СлаваУкраїні Hey ( :
 
@Kevin yep. After being on Linux for a while, I cared less and less about filename or file extension. Now I either use file(1) or look up a local db/file or my own internal brain memory as to "what is this file again"
 
@JackDaniels Hmm, it's never done that for me. You must be mistaken.
 
1:42 PM
@JackDaniels did you try to make a simple csv from scratch? I mean csv are just comma (usually) separated elements, so make a small list of string and separate it with comma. Then use your code on it to see if it has the same problem
 
2:06 PM
@JackDaniels, any chance btw that you are using pandas to create the data that you want to write in a csv, or that you have pandas available in your environment? Otherwise the pandas to_csv method can be really nice.
 
2:23 PM
@JackDaniels Out of curiosity, how do you check for the carriage return?
In what situation do you notice that?
 
2:41 PM
I'm implementing recurring events in a project and here's what I'm planning to do:
A recurring event will be NoSQL with 5 keys : User.id, Event.id, StartDate, EndDate(with a default value), Interval (n Days|n Weeks|n Months). The client requests a json with recurring and non-recurring events, his end will generate a schedule. The json has a hash value to see if it's different from the latest version. (Some users will have events set by other users).
Does anyone have a better idea?
 
Sounds reasonable imo. Do you expect to encounter more complex recurrency demands? Like first Sunday of every month?
 
Now that you tell me. Yes, it's highly possible, even, that they would ask for it.
Like an end of the month meeting, for example.
I mean an end of the month meeting, that has to happen on a certain weekday.
I have to say it's the javascript side of thing that fills me with dead, but I'll think about it.
 
 
3 hours later…
6:02 PM
@JackDaniels I'm digging deep in the memory banks. I'm relatively sure that, in Python 3 and with the csv module in Windows, you need newline='' when opening a CSV file, and you don't read it as bytes
Nice and easy to find
read/write. It's quite difficult to follow the history on this one as it unfolded as there were a number of different things being thrown about. newline='' fixes the carriage return for Windows
 
 
1 hour later…
7:12 PM
Playing around with higher order functions today... Think I might reinvent combinators soon
a = lambda x: lambda y: x+y
b = lambda x: x*2
c = 7
d = lambda x: x+1
e = 13
f = lambda a: lambda b: lambda c: a(b(c))
print(f(f)(f)(f)(f)(f)(a)(b)(c)(d)(e)) #result: 28
print(f(f)(f)(f)(f)(f)(f)(f)(f)(f)(a)(b)(c)(d)(e)) #result: 28
print(f(f)(f)(f)(f)(f)(f)(f)(f)(f)(f)(f)(f)(f)(a)(b)(c)(d)(e)) #result: 28
#and so forth
 
Fs in the chat for Kevin
 
I think if I can work an unbalanced binary tree into there, I'll uncover a rich vein of weirdness
 
Слава капусті!
@AndrasDeak--СлаваУкраїні that's insidious
 
 
4 hours later…
Z47
10:55 PM
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score

crossvalidation_poly = KFold(n_splits=3, shuffle=True)



for i in range(1,11):
poly_cross_validation = PolynomialFeatures(degree=i)
X_current = poly.fit_transform(x_validation)
model = lin_regressor.fit(X_current, y_validation)
scores = cross_val_score(model, X_current,y_validation, scoring='r2', cv=crossvalidation_poly,
n_jobs=1)
I am sorry, the last question, is this correct? I am trying to run CV for the validation data
X_current = poly.fit_transform(x_validation)
I have doubts about this line, shouldn't it be X_current = poly.fit_transform(x_train)?
 
11:35 PM
how do you grep for a question mark? Like I want to find "hello?" in files
 
@duhaime grep '?'
in other words, this sounds like an XY problem
 
perfect, thank you!
haha
 
You asked the question before trying if grep 'hello?' file worked?
 
I've got 99 problems and all of them are XY problems
I never use quotes when grepping
 
yeah, that's definitely some problem along the ABC
but unless you have a file named hellox I'd expect this to work without quotes
 
11:39 PM
oh interesting, it works in bash but not zsh
 
if you use grep -E or egrep or some other variant, then you need to escape the \?
GNU grep and who knows what defaults to ? being literal, extended variants default to ? being the special regex character.
your bash and zsh must be using different grep flavours
 
that could be
 
I'd recommend using grep -E and escaping to get consistent behaviour
 

« first day (4316 days earlier)      last day (615 days later) »