/dpt/ - Daily Programming Thread

What are you working on, Sup Forums?

Old thread:

Other urls found in this thread:

msdn.microsoft.com/en-us/magazine/jj991977.aspx
stackoverflow.com/a/1481577/4479934
en.m.wikipedia.org/wiki/Region-based_memory_management
better-dpt-roll.github.io/
github.com/rust-lang/rust/pull/25640
docs.python.org/2/c-api/refcounting.html
archive.is/7b1iG
twitter.com/SFWRedditVideos

First for C#

Second for F#

Trying to cross-compile a library for 3DS Homebrew

It's suffering.

!(Thank you for using an anime image)

I'm creating simple 2D textured maps.

Pretty simple using a BMP C lib. The next step is generate the mask randomly using a perlin noise algorithm.

So I've been working on a chess program.

I have everything implemented except for castling and en-passant pawn taking, but I'm wondering about my checking for checkmate function.

Right now I'm using a O(n^2) (n = 64) method of trying to move every piece to every spot and checking if the king is out of check afterward. Is there a more efficient solution?

> go to interview
> interviewer ask me a programming question
> know Haskell because Sup Forums told me it was the best language
> start to solve it in haskell
> "umm, user i don't know haskell, can you do it in other language?"
> "uh sure..."
> remeber seeing some C code on /dpt/
> don't remeber anything
> start sweating
> drop my spaghetti
> got the hell out of there

When you work with other people and they use your classes and shit, you have control over what they can fuck with and what they can't. If everything was public, then they could go in and fuck with every member variable and they could just fuck everything up.

But if you're using github they'll have source code, so why couldn't they just go in and change it manually anyway?

How the fuck did you get an interview with just Haskell and no other language

Teach me your ways

>things that never happened

Wow you posted it again, well done

Hahahahahaha, that's so funny.

Also we have a functional programming thread:

Looks like you've got a lot of sand in your ocean, there, boss.

template
T average(T a, T b)
{
return a/2 + b/2 + (a%2 & b%2);
}

Did we finally do it? Did we finally create an average function in C++?

>(a%2 & b%2)
>&
dropped

...

Nice.

Why dropped?

Find a better way to compare two ints for a true value.

Does anybody know how to implement correct async/await method in WPF so that my program doesn't freeze? Program works but i can't do Thread.Sleep(n) in a while function

Here's a small section that is giving me trouble

private async void Button_Click(object sender, RoutedEventArgs e)
{
string car;
string price;
string link;

var task = Task.Run(() =>Thread.Sleep(10000));

// ----Simulating GET request for website scraping, this part works----


//-----End Simulating GET----

myList.ItemsSource = myClients;
string searchCar = txtBlock.Text + " " + txtBlock2.Text;


var articleNodes = htmlDoc.DocumentNode.SelectNodes($"//*[@id='main_content']/div[1]/div[2]/ul[1]//*[text()[contains(., '{searchCar}')]]");

while (articleNodes != null && articleNodes.Any())
{
foreach (var articleNode in articleNodes)
{
car = WebUtility.HtmlDecode(articleNode.InnerText);
price = WebUtility.HtmlDecode(articleNode.ParentNode.ParentNode.SelectSingleNode("span").InnerText);
link = WebUtility.HtmlDecode(articleNode.ParentNode.ParentNode.Attributes["href"].Value);
myClients.Insert(0, new User(car, price, link)); //inserts new item on top of ObservableCollection
}
await task;
}
}}

YOU HAVE BEEN VISITED BY THE ISLAMIC TRUCK OF TOLERANCE
______________¶___
|religion of peace ||l “”|””\__,_
|______________|||__|__|__|]beep! beep!
(@)@)*********(@)(@)**(@)
POST THIS IN ANOTHER THREAD OR THE PEACE TRUCK WILL COME TO YOUR COUNTRY AND KILL YOUR MOTHER IN HER SLEEP!

Yeah, I remove it. No worries senpai

Ok, i have managed to do it with
await Task.Delay(10000)

Oh shit, everything works, but i just realized if i press the button again with different selection, the last selection will continue working

How do i stop button from doing while loop?

>async void
STOP RIGHT THERE, CRIMINAL SCUM

Read this before you go any further:
msdn.microsoft.com/en-us/magazine/jj991977.aspx

And you should be using Task.Delay() instead of Thread.Sleep.

>all those assumptions
>it still doesn't work

Disregard that, I suck cocks and didn't see that this was a button event handler.

If I were you, I would disable the the button or display a loading screen until the first one is done.

Otherwise, you're going to have to have a listener that stops the task execution when the button is pressed while it's doing the initial work.

>Find a better way to compare two ints for a true value.

>ints
>generic template argument

>ints
>assumes two's complement

DROPPED
R
O
P
P
E
D

>average
>returns int

>I would disable the the button or display a loading screen until the first one is done.

Currently, the program is designed to scan the site every 10sec, it should work continuously, but it would be the best if started searching for different parameters if textblocks are changed.

Otherwise, if you have to click the button again, i have no idea how to stop the last while

You shouldn't be using Thread.Sleep() with GUI applications. I think you have to create a new thread and run the asynchronous method in that thread.

Solved it seconds after posting

Now the problem is

GC allocators are faster than malloc

>implying C isn't so easy practically anyone can write it
Either way. Realistically if the interviewer asks for C for his convenience pseudo code is a good middle ground.

>generic template argument
fine, here
template < class T,
class = typename std::enable_if::type>
T average(T a, T b)
{
return a / 2 + b / 2 + (a%2 & a%2);
}


>assumes two's complement
Do you have a better way to be compatible across all platforms?

They're not.

That's completely irrelevant because any decent MMM doesn't do straight alloc's

I got A- in Java midterm are you proud of me :3?
There were 3 A- 1 C rest F and D. wew lad

Are too

Made me think what you meant by that

It tends to look that way. Somehow. It's beyond me how people manage to get D's in programming courses.

I'm writing a trie.

I need each node to have a "size" parameter that tells you how many entries there are below it.
How do i insert an entry into without going through the word twice?

class Node {
Map next;
int size;
Entry entry;
}

void insert(Node root, String word, Entry entry) {
// insert entry into root
// if entry didn't exist, add sizes to all nodes from root to leaf (here you're going through the word again)
}

stackoverflow.com/a/1481577/4479934

Memory arenas are faster than both.

And yet naively mallocing and freeing everything will never lead to multi-ms-long application pauses.

You're a retard.

I actually am fine with GC when it's opt-in and is used regionally. That way you don't end up with stop-the-world and can save GC for when it's really needed (rarely).

Well fuck me, i'm just a beginner, this shit is way over my head

Nobody who gives half a shit does memory management in a way that means they system-call allocate each resource on demand. A common model would be a en.m.wikipedia.org/wiki/Region-based_memory_management
Basically the issue with comparing GC to malloc is that they're not corresponding to each other.

Also you could interpret that a complete run of your GC is faster than a single malloc call.
Which I don't buy. Many applications would actually just need a single heap allocation believe it or not.

Well, what you're proposing is to stop a running thread.

You never want to do that straight up, because no one knows what that could potentially do.

Simply add the flag to your method to activate if there's already a running method of the same call, then in your while loop, abort the loop and handle an unfinished run if it sees that flag as 'true'.

>Do you have a better way to be compatible across all platforms?
Yes, don't rely on two's compliment.

>Are too
They're not. malloc is basically just a call to mmap.

What kind of data are you storing? How is it ordered, I mean.

Basic principle is to start off with the root node, and as you recurse throughout inserting, increment the size as you find the place for the node

The way I had mine setup was with a bitboard.

I had a function which would see if the king was in check. It just generated a series of bitmasks for where each of the opponents pieces could move next turn and checked against the king.

Then I had an iterator for all the pieces and an iterator for all the moves for each piece. It would filter results with that check function.

Checkmate was easy to implement, it was just the case where you had no more moves and was in check.

>mfw GCucks still have to manually free resources other than memory because their shit languages don't bother with RAII

While you're busy hand-optimizing your allocations, we're making productive programs.

Its just a regular trie. What Entry is, doesn't matter.
If you always increment the size, the following happens:

insert(root, "abc", new Entry()); // root size is now 1
insert(root, "abc", new Entry()); // root size is now 2, new entry overrides the old one
delete(root "abc") // root size is now 1 even though no entries in the trie

>Do you have a better way to be compatible across all platforms?

>(a%2 & a%2)

a % 2 != 0

>mfw sepplemales have to write C++

>sorry user, I was being productive but I've decided that I'm now going to take a 30 ms break

>implying I use C++

>RAII
>good software
Pick one.
Not even a GC fag.

What's wrong with it C baby?

>RAII fags STILL have to explicitly define destructors as well as the other resources owned by the object in question

>explicitly define destructors
Not if the type is only made up of RAII'd or non-resource parts.

>as well as the other resources owned by the object in question
Well, obviously. Do you expect the compiler to just read your mind and program for you?

Looking at the stackoverflow I see this code
private object m_lock = new object();
private bool m_isRunning = false;
private bool m_isAbortRequested = false;

public void OnButtonClick(object sender, EventArgs e) {
lock ( m_lock ) {
if ( m_isRunning ) {
m_isAbortRequested = true;
} else {
m_isAbortRequested = false;
m_isRunning = true;
ThreadPool.QueueUserWorkItem(BackgroundMethod);
}
}
}

private void BackgroundMethod() {
try {
DoRealWork();
} finally {
lock (m_lock) {
m_isRunning = false;
}
}
}

private void DoRealWork() {
...
if ( m_isAbortRequested ) {
return;
}
}

Now, I guess this is a flag system that checks if i want thread to close or not, and if i don't it performs my method (in my case, web scrape).

How would i sign that i want to close the thread, assign new button that changes m_isAbortRequested to true?

class Constructs t k m where
construct :: k -> m t
class Destroys t m where
destroy :: t -> m ()


raii :: (Constructs t k m, Destroys t m, Monad m) => k -> (t -> b) -> m b
raii args f = do
x

*pure y

I expect not to have to deal with trivial bullshit constantly.

If I need the performance advantages attained by the disadvantages of needing to manually determine the lifetimes of all of my resources, as well as manually managing memory, I will go and write a C or C++ module to perform this singular task.

Until then, I'll be happy and productive in a language that gets the fuck out of my way and lets me describe what I want the program to do, without having to babysit all of the tedious details.

>>implying I use C++

What other language has RAII?

Not sure what you're trying to achieve.

node.size = (entry == null ? 0 : 1) + sum([n.size() for n in next])

D and Rust (most popular ones that aren't C++), in which case you're free to laugh at that user.

>What other language has RAII?
Not him, but Python for one

Python does not have actual RAII.

>Yes, don't rely on two's compliment.
I'm not relying on anything. Relying on two's compliment would be
a & b & 1

My code is
a%2 & b%2

If a and b are both odd, then they should have the same value. Meaning a%2 == b%2, and when that's guaranteed for a%2 & b%2 to have a int value of 1

Second a should be a b

It does. GC is of course default, but there is implicit reference counting allowing you to implement RAII style objects that delete their own reference when the refcount is 0.

If you can use libraries and whatnot and not have to touch memory or FFI directly (which would be the case the majority of the time) then the resource management and lifetimes and whatnot is done for you, you just have to follow the restrictions of the API.

Rust
inb4 irrelevant ESS JAY DUBBLE YOOS GitHub discussion link

You mean with __ as ___:? I'm not sure I would call that RAII.

Well the primary reason it's bad is because it's uneccesary and it's only purpose is to provide convenience for bad programmers.

I don't think I've written an application with RAII where RAII helped me more than it wasted my time.
I don't do 'resource' allocation and deallocation all over the place. And where I do the issues are trivial to catch my self if they ever were to appear. As a general principle (as the name implies and proponents generally argue, you use it wherever you can) it's faulty.

I don't oppose the idea that if you have a file accessor reference of some sort you'd like to close the file when that reference goes out of scope for instance. But that's the edge case. Your program should ideally open and close files only at a few places in the program. Relying on the system to read data to you in a timely fashion by spreading the file accessors all over the place is simply not sane.

It would be better if it could all be done implicitly. But it can't obviously. So you're kinda fucked.

It's just another programming misstep. Just like OOP. Though RAII has far less negative consequences.

GCC has a cleanup attribute that could be used to simulate RAII :)

That isn't RAII any more than C#'s "using" blocks are RAII.

Pseudocode of what i'm doing currently

void insert(Node root, String word, Entry entry) {
if (entry == null) throw new IllegalArgumentException();
Node node = root;
for (char c : word) node = node.next.getOrCreate(c);
if (node.entry == null) {
node = root;
root.size++;
for (char c : word) { node = node.next.get(c); node.size++; }
}
}


This loops through the word twice.

could anyone link me that site that had all the code for useless projects on it? I'm sorry I can't be more specific as I can barely remember it but I recall there being, for example, a phone number guesser that randomly took a sequence of 11 digits from the decimals of pi and then asked if that was the correct number

there was various other stuff like that, too

better-dpt-roll.github.io/

I'd rather not have to catch exceptions, free the resources of that frame, then rethrow manually. I'm already deciding when my shit is going to be freed, I just don't have to supply the intricate details myself.

Can you give some actual reasoning why it's "faulty"? I can't see how RAII could possibly waste time.

>My code is
>a%2 & b%2
In this case, it is wrong.

average(-3, -6) yields -4 and average(3, 6) yields 4.

Should be -3 and 4.

Never quite understood the Rust / SJW association.

It's because it's a Mozilla project so you get a little more political correctness thrown around in the GitHub issues. Does it actually affect anything? Of course not.

>If a and b are both odd, then they should have the same value. Meaning a%2 == b%2, and when that's guaranteed for a%2 & b%2 to have a int value of 1
That's wrong.

In one's complement, for a 16-bit int, both 0x0000 and 0xffff represent 0

This means that if the result of {a,b} % 2 is 0 and represented by 0xffff, then your calculation will be wrong.

This:
github.com/rust-lang/rust/pull/25640

Among other examples. If I recall, the guy with the eggplant got banned from GitHub entirely due to the uproar the Rust community created over it.

No, I'm talking about this: docs.python.org/2/c-api/refcounting.html

...

>Philosophers must be wise asians
Isn't that kinda stereotypic aka racist?

Banned from Github?

It was Node.JS

archive.is/7b1iG

>exceptions
Well naturally you should never have exceptions in flight.
Anyone who can avoid them should. They're one of the false reasons to use RAII.
>I can't see how RAII wastes time
Well any time you write a constructor/destructor is an example.
It'd be hard to see when you're in an environment that relies heavily on RAII or OOP how you can live without constructors and destructors but they really do waste a lot of time and I'm my opinion convolutes the code. But if you imagined that every time you declare a type you don't need to implement a bunch of stuff just for the sake of it and you just start using the type. Sometimes you do need initialization for a type. And you write your small init function. And sometimes your data is a container of some sort that need special care for deallcoation. That's when destructors are appropriate.
But not in general. You have so many situations where you don't need that stuff that it really adds up. And it'd be hard to appreciate without measuring. But I certainly feel much more productive when I don't do that stuff compulsively. And I don't have more bugs because I spend that time on my actual problems.

I'm sorry it's hard to be giving good examples. It's not a small topic.

why is every 'dpt' thread image an anime girl?
do you ever use bulma? she's technology

Exceptions are quite performant when used well.

I'm fine with them writing that but changing it is certainly petty.

But I'd secretly like to pretend every smart person is a woman because the idea is attractive to me. Even if it's not the case.
So I'm odd.

>exceptions are great!
t. satan

She doesn't program.

I'm not Satan

you sure? i thought she invented and programmed things herself
I only watched endless eight, I don't know much about OP girl, does she program?

that's exactly what satan would say
>thinking you could fool me like that