« first day (1484 days earlier)      last day (2830 days later) » 

00:00
RELOAD! There are 3915 unanswered questions (91.2015% answered)
jrh
jrh
I really should probably stop using VS 2013 for my go to IDE, it seems like most posts are VS2015+ now.
VS 2017 is (slowly) downloading for an offline install, 3 GB and counting. This hotel happens to have a better connection than my house!
0
Q: Format capital letters at the start of a sentence

DenisI have a set of predefined templates for messages, where you can insert different arguments to make it more specific. In order for the messages to be looking good I needed a way to capitalize the first letters of each sentence because you might pass the argument fully lower-cased while in some ...

jrh
jrh
00:17
on a possibly unrelated note
5
Q: Processing input in background while user is typing

JanDotNetUse case A GUI with 2 controls: An input control for text (a DNA sequence) that should be analyzed A result control that displays the analyzing result of the entered text The analysis takes 2-3 seconds and should start as soon as the text in the input control is changing. The shown result sh...

process.Ensure(nameof(process)).IsNotNull();
I can't seem to find the Ensure method in the ref. source for System.Delegate, am I missing a using or something?
I thought that was VS 2015 just being too old but I'm not so sure now.
00:51
@jrh Perhaps it's this repo.
01:14
This looks to be a better fit for codereview. Might be some benefit to a look-up table rather than loop and shift — user4581301 20 secs ago
01:51
It's only unnecessary if you add the else which the OP did not have. As the OP had it a return is required to keep other code in the block from executing. So now, you're just debating an early return vs. an else clause - two different styles of achieving the same thing. No right or wrong, just opinion (which as you say would be more appropriate in code review, not here). — jfriend00 23 secs ago
-1
Q: Where to put SignalR Hub connecttion?

John Louie Dela CruzI know that when your code is for communicating to server it should be in service but in angular 2, where should i put the signalR connection? In component like this? export class GroupChatComponent { private conn: SignalR; private proxy: SignalR.Hub.Proxy; messages: string[] = [];...

jrh
jrh
02:13
0
Q: Separating a method into two or keeping it as one - when to do so?

SirI have a simple example of two setups of the same block of code, but i am not sure what would be considered the "better" option, although subjective, i read about methods often doing too much than which they describe. So example is where i want to add data and do a sanity check first... the two ...

jrh
jrh
... that just doesn't seem right though, how could nameof anything be null?
 
1 hour later…
03:30
possible answer invalidation by Arrow on question by Arrow: codereview.stackexchange.com/posts/164264/revisions
03:47
0
Q: Design pattern to editor of templates in Spring

RenanI have a service in Spring that reads a template written/edited by user and with fields and entities existing in template (edited by user) are return the results of this template. Example: {{ user.name }}, in this case user are a entity and name is a field written by user, follow example, the que...

 
1 hour later…
04:54
0
Q: I have a Java Coding but there is some reasons those didn't work

AndriyDesign a programming named CharDistribution.java, which counts how many times each of the alphabetic characters (convert lower case to upper case) appears in the data file. Then print the result as follows: A - 65 B - 99 C - 5 D - 0 ... Z - 2 import java.io.File; import java.io.FileNotFoundEx...

05:40
possible answer invalidation by Timʘɫei on question by Timʘɫei: codereview.stackexchange.com/posts/164290/revisions
06:00
possible answer invalidation by Timʘɫei on question by Timʘɫei: codereview.stackexchange.com/posts/164290/revisions
possible answer invalidation by Coal_ on question by Coal_: codereview.stackexchange.com/posts/164187/revisions
 
2 hours later…
07:38
-2
Q: Registration Form. Does not need to store information anywhere, just needs to work

boogaloop//Required to build the signup/register portion of a system. The system should try to limit the potential for incorrect / false data being stored. You are only required to implement the initial detail checking phase of the program, your program only needs to display a message to the user explaini...

08:13
0
Q: OOP Generic Deck/Card implementation in Java

Nilzone-I decided to give this another go. Last attempt can be found here This time around I tried my best to make this as generic as possible. The goal is to make this usable for any types of cards, not just traditional card-games. AbstractOperation.java package com.tn.deck; import java.util.ArrayL...

0
Q: In memory data access

JohanI'm reading data from csv files and store the result in a simple DataContext instance that gets injected throughout my application. public class DataContext { private static readonly IDictionary<Type, IEnumerable<BaseEntity>> EntityMap = Assembly.GetExecutingAssembly().GetTypes() ...

08:50
0
Q: Haskell Sudoku Solver

Michal CharemzaAny comments on the following Sudoku solver? Comments I'm particularly interested are (but not limited to...) Algorithm. It created a list of "potentials" for each cell, and trims them down until it's solved. Anything better? How's my use of the State monad? I'm not that familiar, so don't know...

09:04
Monking
Question: Would you, monkeys, spend 1$ to read an idea ? Maybe you don't know what project to do next, or maybe you want a new business or IDK...similar things. Would you spend 1$ to read something that might or might not be worth it ?
I wouldn't.
Plenty of free ideas on the internet.
So you'd have to have something really good would I even consider paying for it.
At that moment, it becomes irrelevant whether you charge 1 buck or 5.
Same with online courses. I've completed a couple of free ones, but just this morning finished one that cost me around 70 bucks.
If an idea is only worth a dollar, ask yourself why you'd even bother charging for it.
@Mast Well, the idea behind this thing is the risk. I mean, yea'..I know that you, as a person, have some ideas, but cannot implement them. So just write them down and share them with somebody. For free (ATM).
I mean, imagine a place where you can have all kind of ideas..from different domains
Like, the internet.
What is your service going to provide that the internet as a whole and some google-fu isn't?
time
Well, you better provide a whole lot of information with your idea then.
In that case I could see a niche market for it.
I just wouldn't be part of it :-)
Got plenty of projects running.
Finishing them is a totally, unrelated matter.
If you ever find something that can help me with finishing what I start...
4
09:20
@Mast I know the feeling.
@Mast With the risk of repeating myself, alexvermeer.com/getmotivated
@SimonForsberg A friend of mine got a saying tattooed on his arm.
> If you feel like quitting, think about why you started.
4
Honestly, I think concentration is just as big as a problem as motivation in my case.
But that chart looks interesting, thanks :-)
09:36
@Mast That's a good quote.
@Mast Every now and then I work on a Java program/Android application for it.
Ironically, I'm having problems motivating myself to finish it.
09:52
lmao
At risk of asking a personal question, what's your primary roadblock in getting things done? @Simon
possible answer invalidation by SMth80 on question by SMth80: codereview.stackexchange.com/posts/164267/revisions
0
Q: C++ Reading Data in a File

IanI'm not sure if I should ask here. The program worked it's just that I'm not satisfied how I implemented it because I used two while loop to read a specific data and I have no idea what am I doing. How can I make it more efficient and instead of using two while loop? spritesheet.txt int main(...

@Mast Energy and prioritization
When I come home from work a typical day, I don't have much energy to work on anything.
And once I do work on something, I have so many different projects to work on that it's hard to choose.
Both sound familiar.
10:15
0
Q: A wrapper on top of boost vector

Ravikumar TuluguPlease review the following piece of code, the class implements a light weight wrapper on top of boost::container::vector, i am not getting the expected performance no where comparable to std::vector. The vector is functionally correct but i feel there is some room for improvement especially in t...

10:28
Thanks sir Simon. I'll roger that. — SMth80 18 mins ago
I hate it when people call me "sir".
@SimonForsberg Sounds like a case of mistaken identity.
Hell no. There is no specific question to start with and this question was posted twice with two accounts. This is not a code review or code providing service. Besides that, there is no point of just wrapping a crypto API so you can abuse it using strings. Cryptography is not something generic, you should deploy it for specific use cases and threat models. — Maarten Bodewes 37 secs ago
10:55
onking
@Mast Hey, maybe I can help with that
@skiwi interested
Looking in hindsight, I've only recently finished my most crazy ideas... Like a Brainfuck compiler
@Mast You should know me good enough by now to know that I never finish anything :P
It's interesting, even though I already expected it, that I have more than enough motivation to finish projects at work when being paid
After work nowadays motivation is the biggest issue though
@skiwi You finish a tab every once in a while :P
@Mast 887
You have an addon to count them?
If not, I see a perfectly valid reason to write one :-)
11:09
@Mast Ctrl+Tab in Firefox counts them if it gets a lot
@skiwi Guess I haven't reached that stage in a while.
0
Q: Solution to itoa in c. (C programming language)

geostockerAs some of you all might know I've been working my way through the C Programming Language (2nd). I recently finished a rough implementation of the itoa exercise (chapter 3). It's important to note that we haven't been introduced to any advanced subjects like pointers, dynamic arrays etc yet. Th...

@jrh It's checking that the parameter itself isn't null I'd bet?
11:44
This question is off-topic here and more suitable for Code Reviewgp_sflover 10 secs ago
12:27
Welcome. This question might do better on another Stack Exchange site. Perhaps Code Review? Anyone? — MickyD just now
13:26
0
Q: An Mp3 player using React and Redux and the HTML5 web audio API

SarahI built a simple MP3 player with React and now I would like to incorporate Redux to the app as it is getting larger and I feel Redux will help it to be more organized and efficient. I was wondering can you look through my code and help me with a few questions I have (which you will see shortly)....

0
Q: How to speed ut php database calls

JohanI need help to speed up this code. It works, but is really slow (updates 2 items/second). Any tips on how to speed it up? The script functions like this: 1. Break up an email to username and domain 2. If not already in database add username to username table and the domain to domain table. 3. Ad...

0
Q: Asynchronous task on every element of an array

neoflashHere is some synchronous code: let barsClient = [{ id: 1, name: "The Shindig", goingTonight: [] }, { id: 2, name: "Steakapolis", goingTonight: [] }, { id: 3, name: "Booty Town", goingTonight: [] } ]; let barsDB = [{ id: 2, name: "Steakapolis...

0
Q: Find the longest zigzag sequence in a array of integers

BobloblawlawblogsI think I have a brute force solution to the problem but I can't think of a more optimal solution A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 ...

14:03
Monking-ish ...
jrh
jrh
hello
something bugs me about how Microsoft put WPF and Winforms in the "Windows Classic Desktop" category but Win32 is kind of just sitting by itself in the Visual C++ category
back when I first started the "Win32" terminology was bad enough. I saw that and thought "No, I have a 64 bit system, this can't be what I want"
I thought Win32 was officially renamed to Winapi?
The "Windows Classic <Legacy Old Crap You Must Be Nuts To Use This But Actually It's Still Supported> Desktop" category under C# sort of sounds to me like Microsoft was having trouble with naming again.
IMO Microsoft did a lot of good work but they kind of waste it sometimes, they've got a lot of pretty nice specialized libraries that got sort of abandoned (sometimes before they're fully baked) in favor of some new thing (e.g., even .NET isn't comprehensive, sometimes I still need to P/Invoke winapi calls; Winforms and WPF have a rather limited set of built in Controls).
I guess it's just more valuable for Microsoft to always try to have some API on the newest thing than to make any full replacement for winapi.
15:07
0
Q: C++ sum and averaging functions for arrays and argument sets

StefanHere are two sets of variadic C++ functions to do fast summing and averaging of arrays (plain & std::array) or argument sets, (re)written as part of my generic toolbox. The sum functions are pretty generic, the averaging ones operate on floating point based types only (the integer counterparts a...

15:35
Anyone want to play Webopoly?
16:01
"I have checked out this." What were the results? Where is your function spending the most time? I would say that this post belongs in Code Review, but simply dumping code with no research shown and no explanation is not going to be well-received anywhere. — beaker 12 secs ago
@Hosch250 Is the offer still valid?
Well, the game started, but see if you can join at 121286 and Test.
Nvm, game will be over by the time I figured out how to start it :-)
At Webopoly.org.
Search the game ID and "Test" is the password.
If you can't join, we can start a new one.
>
Error: This game has already started. New players may not join
16:07
121287 and Test.
> Error: please enter a valid Game ID
Oh, wait, my bad
I'm in.
It seems like you have working code and are asking for improvements to that code. You might get better help at Code Review, which is a site designed for that. However, before it is migrated (or you delete and re-ask there), could you add some clarifying details of how the code works, as requested by Ronak? — josliber ♦ 55 secs ago
Lol, I purchased XKCD.
25.6 degrees inside, wow
Brrr.
16:19
lmao
Celsius.
Was 28 upstairs this afternoon.
17:15
It is very unclear what you are asking for. In general if you want your code reviewed and want to get improvement tips, there is codereview.stackexchange.com for you. — luk2302 13 secs ago
18:14
Anyone want to play another game of Webopoly?
Or maybe I should start writing one.
18:29
@Hosch250 Collaborate with @EBrown and @Simon and the 3 of you might actually get it done :-)
I don't write Java.
Eh, if you have a great understanding of C#, you can easily dabble in Java.
@Hosch250 I'm working on a C# implementation lol
Even I can Java.
Well, somewhat.
I don't demean myself like that.
18:38
-1
Q: Calling a get method of an object in another class

HuzoSo I have created this class public class LordOutLoud { public static void main(String[] args) { Heroes HeroLOL = new Heroes(); HeroLOL.setHeroName("LordOutLoud"); HeroLOL.setHP(1680); HeroLOL.setmana(350); HeroLOL.setStrength(10); HeroLOL.setAgility(25); HeroLOL....

My brother is going to play Webopoly with me. Want to join?
121293 and Test.
Too late.
18:56
-1
Q: PHP register/login/reset pw

Ãmïñē Ãmïñēi made 3 forms " register , loginand pw reset " and i connected the db . first, i need php codes to submit data from register page wich contains 1s name last name email and confirm email btc account and also pw and confirm pw with hash of course(md5&bcrypt) to db i only need to confirm that em...

@Hosch250 @Mast Yes please. It's better to have one finished than three unfinished ones.
19:23
1
Q: Faster solution to compute magic numbers

TimʘɫeiThere are N doors with a number on each door. You have a golden key(K) and you can open with it only doors on which the numbers are magic and can be reduced to the number of the key (With key 7 you can open doors on which the magic numbers can be reduced to 7). A number is magic if it can be redu...

19:53
@Hosch250 @Phrancis Databases don't have a list/vector type. How would one go about storing a list of at most 6 items in a database?
The only approach I've seen so far is reserving multiple columns and only filling them if such an amount of data (such lengthy a list) exists, but in a time of OO solutions this seems wrong to me.
Can I somehow trick a relational (SQLite) database into doing this the right way?
@EBrown You probably know a thing or two about databases as well.
0
Q: Simple uint128_t implementation

Rakete1111I made a simple uint128_t implementation for a project that I'm working on. The reason for not using for example boost::uint128_t is that it is not fully constexpr like I would like it to be. For this reason, I only implemented the operators that I'm going to use. I'm for example not interested ...

-1
Q: Time Limit Exceeded for a code chef easy program

Prateekimport java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; class Test { static ArrayList<Integer> stringCreator(int cen,int len){ ArrayList<Integer> x = new ArrayList<>(); ...

@Mast Put them in a table
@Phrancis For every entry?
Specifically, I want to split the authors per book.
A book can have 1 author. A book can have 6 authors. Each author has a author_id referring to the authors table.
How do I store 6 author_id per book in the 'right' way?
@CaptainObvious UWYA
@Mast You want to store a list of things? Use a one-to-many relation like normal.
20:12
@EBrown That only works if I have one author writing many books, not many authors part of one book, right?
Or would this turn into a twisted kind of many-to-many relationship?
@Mast You could easily many-to-many it as well.
This is how I currently store authors.
def save_author(title, author, conn):
    cur = conn.cursor()
    cur.execute(
            "INSERT OR IGNORE INTO BookAuthors (Book_id, Author_id) VALUES ( ?, ? )",
            (str(title).decode('utf-8'), str(author).decode('utf-8')))
    try:
        data = cur.fetchone()[0]
        print "Found in database ", title
    except:
        pass
Yep.
What's the problem?
And yes, I should refactor that INSERT OR IGNORE, haven't gotten around to it yet.
This assumes all authors in one string.
I want to split the string and add them as loose components, if that makes sense.
Books can have 1, 2, 6 authors.
Why not insert a record for each author?
20:15
That's what I'm doing, I think.
It inserts every author, saves the author_id at the book record.
Now I want the book record to show as many author_id as it takes.
Right, so SELECT * FROM Books INNER JOIN BookAuthors ON Books.Id = BookAuthors.Book_id INNER JOIN Authors ON Authors.Id = BookAuthors.Author_id
Huh?
I'm confused as to what you want.
-1
Q: Searching by name and date

shriyaI am trying to filter my search by consultant name and date created for records. i am using a datepicker for my calendar and a drop down list for selection on the consultant name. At the moment I have the search working for just the consultant, i cannot figure out how to add the date as a filter...

20:17
Turns out I pasted the wrong code by the way, tat one is 5 versions back. Oh well.
What you're describing is a typical case for a many-to-many relationship.
@EBrown I iterate over books. Currently, if the author doesn't already exist, I add it. Afterwards, I save the book using the author_id as reference.
@Mast That's the problem. Don't do that.
But this takes the entire author string, not split apart, and stores the entire darn thing.
So now I want to split it.
That's the easy part.
How the heck do I tell my database to store them seperately together?
So split it, then save an author for each string in the Authors table, then save a record with the Book_id and Author_id in the BookAuthors table.
20:20
Screw it, I'm dropping the entire code here for shits and giggles. It's hilariously bad.
        for line in filehandle:
            title, author, publish = line.lstrip('./').lstrip(DIRECTORY + '/').rstrip('.pdf\n').split('_')
            try:
                cur.execute(
                    "IF NOT EXISTS (SELECT 1 FROM BookName WHERE name = %s) INSERT INTO BookName (name) VALUES  (\"%s\")" % (title, title)
                )
                #cur.execute(
                #    "INSERT OR IGNORE INTO BookName (name) VALUES (\"%s\")" % title
                #)
                conn.commit()
@EBrown Yes, but that will allow me to save just one author, right?
@Mast No. You save multiple records in the BookAuthors table with the same Book_id and a different Author_id.
create_books_table = '''
CREATE TABLE IF NOT EXISTS Book (
    name_id         INTEGER NOT NULL PRIMARY KEY UNIQUE REFERENCES BookName(id),
    author_id       INTEGER NOT NULL UNIQUE REFERENCES Author(id),
    publish_year    INTEGER
)
'''

create_authors_table = '''
CREATE TABLE IF NOT EXISTS Author (
    id       INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name     TEXT NOT NULL UNIQUE
)
'''

create_booknames_table = '''
CREATE TABLE IF NOT EXISTS BookName (
    id       INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
@EBrown Ah, like how you put multiple genres to a music thing.
Yes.
I already have an authors table, but that doesn't have a sense of books.
Just a sense of authors.
It shouldn't.
20:22
So I could putt a table between those.
You create a third table,
So I can join after a join.
The Books table won't know about any authors, and the Authors table won't know about any books.
And the BookAuthorComboThingy will know about all the combos.
Yes.
20:23
So I have a Book, referencing to a combo. That combo knows all authors.
The book doesn't reference anything.
The combo references the Book AND the Author.
Well, there should be something in the book pointing to data that's somewhere else, right?
No.
So the book contains an id of combo_id or so.
Oh.
That's how I currently do it.
That's your problem.
20:25
Book has a name_id, author_id and publish_year. The first 2 are actually somewhere else.
Take the Author_id out.
Gone.
In the Name table and Author table.
I think I have a drawing somewhere.
This is what I had in mind before I figured I should split the authors.
Everything except the Keywords and BookKeywords is actually implemented.
@EBrown Take the author_id out, insert the combo_id, make that link to the author instead?
No
Take Author_id out entirely
confused
0
Q: C++17 if init for the while loop?

KcFnMiFor some home work I'm doing the following: int main() { ofstream file("log.txt"); file << setw(5) << "i" << setw(15) << "h" << setw(15) << "n" << setw(15) << "sum" << setw(15) << "diff" << endl; auto write2file = [&file](int i, d...

0
Q: split string by list of seperators and return used seperator in correct order

Dr. FreMy goal is to build a function that splits an string by an list of seperators and returns the used seperator in order of usage. This is the header of the function: vector<string>* split(const string* value, const string* seperators, string* split_by) The function is used like the following c...

20:34
Build that
Alright, I can understand that. But where do the multiple Authors come into play?
Through the middle table.
Right, multiple records in BookAuthor.
By creating the PK as a composite, and relating them, the book can have any number of authors, by having multiple BookAuthor records with the same Book_id but different Author_id's.
@Mast I think what @EBrown is getting at is that the author should not be a property of a book. Refactor the author ID out of that table and into a Book_Author table, which contains the book IDs and author IDs
Whoops, delayed response
20:37
Np, thanks for the heads up :-)
blames mobile
Insert authors first, book second, BookAuthors third.
Sounds right
I would do those 3 things within the same transaction
Ah, yes, transactions. That's a completely different problem I have to solve.
SQLite and Python work great, until you start writing it neat. Than stuff will break.
So for now it's a lot of dirty stuff that shouldn't be in the end result.
Don't worry, I'll post it as a question eventually :-)
If it werr a fully fledged DBMS I would write a stored proc, but SQLite doesn't have those
20:45
possible answer invalidation by Jamal on question by Johan: codereview.stackexchange.com/posts/164324/revisions
I thought it was pretty fledged nowadays.
At least, I use something quite similar to stored procs.
"IF NOT EXISTS (SELECT 1 FROM BookName WHERE name = %s) INSERT INTO BookName (name) VALUES  (\"%s\")" % (title, title)
Although I'm actually abusing Python here :-)
When it's about databases, I have no clue what I'm talking about.
Crap, what did I screw up this time.
Why did I think it was a good idea to fore go VCS for this project...
Stored procs make a huge difference
Both for performance and for application side programming
IF only SQL errors were of any use.
I either have a syntax error somewhere, or I'm doing something I'm not supposed to do.
            cur.execute(
                "IF NOT EXISTS (SELECT 1 FROM BookName WHERE name = %s) INSERT INTO BookName (name) VALUES  (\"%s\")" % (title, title)
            )
Throws syntax error near IF.
Most SQL errors useful enough
Has nothing to do with recent modifications.
I vaguely recall having solved this error.
Oh, right.
21:00
-- TODO get a better DBMS to replace SQLite
Yup.
SQLite doesn't like IF NOT EXISTS
So had to do that the ugly way again.
@Phrancis Suggestions? Last time I tried PostgreSQL it gave me headaches on the set-up.
I have a relatively unscathed history with MySQL, but would that be much better?
I try to stay away from it.
MySQL is actually quite good, for a free product
I prefer Microsoft SQL Server for usability, but it's not free and a lot more work to setup initially
MySQL has some quirks, but on the whole it's good.
There doesn't happen to be a third, even better alternative, does there?
Some people like PostgreSQL. I personally don't.
I think PostgreSQL is inferior unless you use pl/pgsql
No support for stored procedures without it. Nor query variables, etc. etc.
I used to talk crap about MySQL a lot, but really it was more talking crap about PHP.
I setup a MySQL DB to work with Node.js and I couldn't believe how easy it was to make it work.
To me the only advantage to SQLite is that it's serverless
21:15
My join fails for 8 out of 100 targets. Fun...
Need a hand?
@Phrancis So, not a great thing either.
@Phrancis It's probably my data sanitizing that needs a kick to the shins, not exactly the hardest problem to figure out.
@Mast Nope. PostgreSQL does have a few neat things, like native JSON support for example, but on the whole I find it clunky.
Failed to JOIN
'NoneType' object has no attribute '__getitem__'
0
Q: Multidimensional Matrix exponentiation

Hia3Is there a more efficient way of exponentiating a multidimensional matrix? This is how I am currently doing it: import numpy as np from scipy import linalg A = np.random.normal(0,0.01, (3, 2,2)) P = np.zeros((3,2,2)) for i in range(3): P[i] = linalg.expm( np.multiply(A[i], 0.5)) Note ...

21:17
It's probably trying to join something that isn't there for some odd reason.
Yeah sounds like it's returning NULL from the DB
@Phrancis Pretty useful if you're developing on your own, but I'll see if I can't migrate this to MySQL eventually. We'll see whether that's the smartest move afterwards.
@Phrancis Except that isn't really possible unless the data doesn't get accepted by the DB, in which case it should have failed on the insert already.
It's also easy enough to just host a DB server on your machine, if it's for yourself
Except I made it an INSERT OR IGNORE, so who knows what it suppresses...
Oh crap.
@Phrancis I know, I have some C++/MySQL experience. Been a long time though.
I don't like the INSERT OR IGNORE black box
21:19
I don't either.
But it worked.
It no longer does.
That's the kind of weird things you get with black boxes.
Right. I'd rather get an error.
Exactly.
Does SQLite have try/catch?
Aha, it inserts the bookname, inserts the author, but the book combining it fails.
@Phrancis Python has, and I can catch most SQLite errors with it.
So, guess so?
Of course not, it doesn't, duh.
Many DBMS have native, SQL language for try/catch type of operations
21:24
I bet it's failing on special characters...
Where - is already a special character.
And +.
Which is problematic if you have books with C++ in the title.
Oh, or it fails because the author already exists.
That shouldn't happen, I explicitly prohibit failing on that...
What do you mean by explicitly prohibiting?
        try:
            cur.execute(
                "INSERT OR IGNORE INTO Book (name_id, author_id, publish_year) VALUES ( ?, ?, ? )",
                (int(str(book_id).rstrip(',)').lstrip('(')), int(str(author_id).rstrip(',)').lstrip('(')), int(publish))
            )
            conn.commit()
            cur.execute(
                "SELECT name_id FROM Book WHERE name_id = \"%s\"" % book_id
            )
            conn.commit()
            current_book = cur.fetchone()
The last line tends to return a None, so probably NULL.
@Phrancis Isn't that the whole point of INSERT OR IGNORE? If it's already there, don't do anything.
But that's the relation I see so far.
Only books which have an author which already exists fail.
@Mast Who knows, that's the problem with black boxes
21:30
0
Q: Time Schedule Intersection version 2

GiladTime schedule intersection in my original question I gave an answer which has O(n^2) complexity. Here is the new version of the same problem. I'm trying to get to O(N+K). please review the code like this is a job interview the emphasis is on complexity and performance. thank you very much usin...

SQL... shivers
3
I would suggest to instead look for the author ID first, and if it returns None, then insert the author
Well, it does. After every insert, it fetches me the current thingy.
So it should always point to the right one.
Crap, this is hard to explain.
@Phrancis That would double my database actions, yuck.
SELECT operations are non-locking, shouldn't matter much
Is it weird that I've spent my past four months programming inside a system that has no SQL?
21:34
Yes
@skiwi I spend most of my days in a system without SQL. The joy of embedded applications :-)
@Mast We do database-heavy work though ;)
EEPROM software, flash circular buffer for error logging. That's it.
I must be one of the only regulars here who actually doesn't mind SQL at all
Well, except the PLC stuff, but that still doesn't have a real DB.
21:36
@Phrancis I kinda mind it now I've worked with the system at work
            cur.execute(
                "INSERT OR IGNORE INTO Book (name_id, author_id, publish_year) VALUES ( ?, ?, ? )",
                (int(str(book_id).rstrip(',)').lstrip('(')), int(str(author_id).rstrip(',)').lstrip('(')), int(publish))
            )
In hindsight, this is asking for trouble.
There must be something simpler to work with... that's exactly what we have invented at my job, except it's proprietary
@Mast Sounds like it would cause a foreign key violation whenever the author already exists
@Phrancis Eh, perhaps my database isn't explicitly configured to know about foreign keys because it seemed to work better without.
Might be a stupid idea in hindsight as well.
21:41
So, what the heck is a foreign key violation?
Say if you try to insert an ID into a table which references a foreign table, but the ID doesn't exist, or already exists
I could probably fix all of this by picking a better DBMS and re-writing everything. But doing that in an unstable state will leave a mess.
For instance, insert or ignore might be trying to create a new author ID in the authors table, and the ID is already taken, or it's a duplicate entry and the authors table doesn't allow duplicates
For some reason it appears to do some odd skipping whenever it can't do what it wants to do.
Oh, perhaps that's the autoincrement being an ass.
Yeah I did notice insert or ignore triggers the auto-increment to go up
21:47
So retrieving the current one after an insert or ignore will indeed retrieve NULL if the author was already there.
Since nothing got inserted.
But the pointer moved anyway.
Crap.
Yeah.
Black boxes.
Is this working code? Then you should post it to codereview.stackexchange.com for improvement suggestions. — Felix Palmen 26 secs ago
I could fix that, but that would destroy the whole point of doing it like I do.
Proper DBMS it is...
How bad are those MySQL quirks exactly?
Before we have the same discussion next week :-)
I've only done maintenance and minor alterations on them in the past.
What I would do from a SQL standpoint is:
1) Check authors table for existence
a) If it exists, grab the author ID
b) If it doesn't, insert it, then grab the author ID
2) Insert the book
Makes sense.
Select, if not null, use id. If null, insert, select, use. Insert.
21:50
Yep
If you do it like that in one transaction, you'll be fine sticking with SQLite
I thought you said SQLite doesn't have transactions?
Oh, I did say that
:|
I do commit after every action though, perhaps that's kind-of the same thing going on.
has no clue
1. I tried posting it at codereview.stackexchange.com. but it won't let me do that for next 40 mins. 2. I am trying to optimise time taken to run — Jayant Jeet Tomar just now
Ah well, let's try MySQL.
It's Python, how hard can it be to switch from DBMS.
21:53
Python is easy to switch methinks
I'd just make it stable before you do though, if possible
import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()

print "Database version : %s " % data

# disconnect from server
db.close()
Bloody same syntax as SQLite.
So, change the top stuff, don't touch the rest, all will be fine.
In theory.
Murphy is an asshole.
5
The only difference is I now have to set-up the DB from outside, where with SQLite I could start with nowhere and build the DB on the fly.
Perhaps MySQL will actually let me properly wrap everything for a change, that would be nice.
Anyway, much appreciated @Phrancis I now know what to do.
Get a decent DBMS, select before trying to insert and wrap everything in a transaction/rollback construct to prevent wacky cursor positions.
Afterwards I can implement the BookAuthor combo table to fix my other problem :-)
TTGTB
Should find the time to implement it tomorrow.
@Mast This ^ is how I'd structure it. Disregard the syntax errors that Workbench is showing, the code actually works
(use whatever size varchar you think you need)
@Mast One of the quirks is conditionals
258
A: MySQL: Insert record if not exists in table

MikeI'm not actually suggesting that you do this, as the UNIQUE index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting: CREATE TABLE `table_listnames` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) NOT NULL, `address...

insert into foo(bar)
values ('Hello')
where not exists (select bar from foo where bar = 'Hello')
Instead of the more familiar if not exists
22:19
-1
Q: dynamic pivot table query in t-sql

JENAUsing the data set given below, write a script that will create a matrix (shown below) with years on the x-axis and employee id on the y-axis. The purpose of this matrix is to show each year an employee was working for the company. Guidelines: - You are allowed to use temp tables and variables...

22:40
codereview.stackexchange.com put a 40-min restriction on you, so you just dumped your question here? — ThingyWotsit 1 min ago
Not using context manager for file handling, old fashioned syntax for error handling, too broad error handling, try block too long, NameError that you don't catch in the error case, string concatenation instead of the various formatting options, ... Once you have this working, if you'd like feedback, see Code Review. — jonrsharpe 34 secs ago
22:56
0
Q: Text-To-Speech program, with a lot of bells and whistles

Gameskiller01I have a Text-To-Speech program that will ask the user to input text, convert it to speech and then output that speech from within Pygame. It will then ask the user if they want to convert more text into speech or if they want to exit the program. I am currently having a problem with this code, w...

0
Q: How to optimise this code for competitive programming?

Jayant Jeet TomarPROBLEM STATEMENT : You want to build a temple for snakes. The temple will be built on a mountain range, which can be thought of as n blocks, where height of i-th block is given by hi. The temple will be made on a consecutive section of the blocks and its height should start from 1 and increase...

23:09
0
Q: Python Username and Password Program. Can this code be simplified?

GregThank you for your time. Can the following code be simplified? I think that the program that I have created is very excessive and quite slow. Sorry if this question is very broad! The program runs fine, but I would like to understand if this could actually be programmed better? Any help will be...

23:55
I'm voting to close this question as off-topic because this is a request for improvements to working code, which belongs on codereview.stackexchange.com — Raymond Chen 22 secs ago

« first day (1484 days earlier)      last day (2830 days later) »