/dpt/ - Daily Programming Thread

What are you working on, Sup Forums?


Previous Thread:

Other urls found in this thread:

passwordsgenerator.net/sha256-hash-generator/
dicesites.com/primedice/verifier
dicesites.com/provably-fair
en.wikipedia.org/wiki/LC-3
twitter.com/NSFWRedditImage

>Step 1
>write down algorithm
//read values
//make a function to change values
//return it to a vector
//find the largest
//return answer

>Step 2
>Implement those algorithms
//read values
>(code)
//make a function to change values
>(code)
//return it to a vector
>(code)
//find the largest
>(code)

Is it a valid style?

before I go balls deep into learning a language, can one of you tell me what is worth learning and what isn't? something that is well payed and no Pajeet shit

Trap posters are the worst posters in these threads.
Delete your stupid fag image.

>something that is well payed
>payed
>"pajeet"
>I want to program but what language will pay me money?
I don't think you have a bright future, how upi about start flipping burgers?

>upi
you*

im in the same boat dude

just start with C ... only choice you have

do CS50 if you need Harvard(tm) , or just watch thenewboston's C Tutorial Series .. use codeblocks and just code along.

He is a great tutor.

This. C is a well suited beginners' language

It's what I do every time.

Is anyone else doing ?

I'm trying to learn matrix multiplication to do gauss jordan elimination, but the row additions seem arbitrary, can I not touch any of the later rows without adding something from the previous ones?

So I'm learning JavaScript and I'm trying to get a series of prompt windows to open and then perform actions afterwards
function myFunct (){
var x = prompt("Enter length");

if(x === 1)
do x;
if( x === null;
otherFunct();

myFunct();
}


My issue is that the actions won't happen all the prompts have happened. How do I fix this.

>or just watch thenewboston's C Tutorial Series
>Learning to program from YouTube
Not to mention, his C programming videos are pretty shit.

No, you should start by first designing your data structures. Then, define the operations on them (functions). Now the algorithm should be easy.

oooo | o x o x
xxxx | o x o x
oooo | o x o x
xxxx | o x o x

>gauss jordan elimination
might as well create an AI for that. Just follow the Cramer's rule

I see you are a fan of Java (tm).

Do you have a plan for how youll score that well paying job after you learn your shitty language?

yeah I'd rather buy a good book, none of that youtube or "for dummies" books
Just need to commit to a language, I think I'll go with python or C

Write an algorithm that finds the mode of an int array of any length.

I see you are a Moron (c)

1) do a project
2) show to employer
3) profit

>Sup Forums cant even average two ints
>expects us to average an entire array

Don't worry, it isn't the arithmetic average, so it's actually possible

>mode
>average entire array

>expects us to average an entire array
But I've posted by C solution to that many times.
Also, why the hell would you refer to 'mode' as average?

when doing operator overloading
am I supposed to define each operator both ways?
eg.
template constexpr bool operator==(const my_type& lhs, const T& rhs) { return /* comparison */; }
template constexpr bool operator==(const T& lhs, const my_type& rhs) { return rhs == lhs; }

Jesus christ.
How do people defend this shit?

thanks for the eye cancer

The question:
>How can I synchronously check, using node.js, if a file or directory exists?
A very reasonable thing to want to do, I'm sure you'll agree. Even with Node's strong emphasis on async I/O, it still makes sense to do sync work e.g. in scripts or on app startup. Very straightforward. I'm sure there will be no problem.

It turns out that the answer is so long, and has changed so many times, it needs a chronological summary section.

I have been contracted to write a huge webapp in Node.

Kill me now.

The mode is a kind of average. Please tell me you made it through highschool

>Not to mention, his C programming videos are pretty shit.

no they arent .. actually most of his videos are pretty good

sure if you are the book type ... go with C

import Data.List (maximumBy)
import Data.Function (on)

counts xs = map (\x -> (x, length $ filter (x ==) xs)) xs

mode = fst . maximumBy (compare `on` snd) . counts

Why would you want to do anything synchronously in node.js? The entire point is an event loop async hell-hole. Poor developers probably havent even heard of a continuation

>this is the current Sup Forums
It's been nice knowing you all

>an int array of any length.
My architecture cannot handle an int array of any length

Please write code in proper syntax first before asking people to fix your issues. No one knows if it is a simple missing bracket that is fucking with your code.

Once the web server gets listening then sure, it has to be 100% async. But the app needs to do some bookkeeping file checking/shuffling before starting the webserver, so it is fine to use sync functions before then. Or at least, I assumed it was until I read that SO answer.

I can't do the bookkeeping work in a separate script either, because it relies on a config.js file with arbitrary JS expressions mixed in with static data.

Or you could just... sort it, group it, max by length...

public static int mode(int a[]) {
int maxValue, maxCount;

for (int i = 0; i < a.length; ++i) {
int count = 0;
for (int j = 0; j < a.length; ++j) {
if (a[j] == a[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = a[i];
}
}

return maxValue;
}

That IS maxing by length

>because it relies on a config.js file with arbitrary JS expressions mixed in with static data.
Shit why? Sounds like a nightmare. You can't just have different initialization steps (functions) that get chained by callbacks? I know it sounds terrible but it IS node you're working with here. Async exists sounds like such a stability nightmare (we all know how reliable it is to count on node libraries to stay consistent ;) ) you should probably find some way to do initialization async

How do I write a python interpreter

How can you tell OPs cartoon girl is a trap?
perlscript to scrap stuff and make it look fabulous for terminal, json and static webpage.

In the most inefficient way possible.
Look at you counts function - it's O(n^2)

Start with the lexer.

Can you charm snakes?

do{
printf("\nInput two values and an operation: ");
scanf("%d %c %d", &a,&c,&b);

answer = calcMath(a, b, c);
printf("\nAnswer: %d", answer);

fprintf(fileWrite, "\n%d %c %d = %d", a, c, b, answer);

printf("\nRun again? Y/N > ");
scanf("%c", &runAgain);
if (runAgain != 'Y') useCalc = 1; //set to 1 for debugging, exists loop if set to 0

} while (useCalc)

Doing a simple calculator. Why does it skip the second scanf line? It outputs correct answers over several loop interations.

>muh efficiency

Go back to CS101, do not pass go, do not collect 200 neetbux

So I have this script that utilizes the first two rolls from a bitcoin gambling site and a client seed and it returns the server seed which i can use to get the SHA256 Hash of the string of the server seed to predict future outputs of the gambling site to a degree of statistical significance. I know if I have a program where I can input three rolls to generate the server seed it would be magnitudes more accurate (if not 100%) guaranteeing returns always though the computational time would skyrocket. Any ideas?
var clientSeed = "2";
var preRoll1=63.40;
var preRoll2=71.72;

//crypto lib for hmac function
var crypto = require('crypto');

var roll = function(key, text) {

//create HMAC using server seed as key and client seed as message
var hash = crypto.createHmac('sha512', key).update(text).digest('hex');
var index = 0;
var lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);

//keep grabbing characters from the hash while greater than

while (lucky >= Math.pow(10, 6)) {

index++;
lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);
//if we reach the end of the hash, just default to highest number
if (index * 5 + 5 > 128) {
lucky = 99.99;
break;
}
}

lucky %= Math.pow(10, 4);
lucky /= Math.pow(10, 2);

return lucky;
}


var i;
for (i = 0; i < 99999999999999; i++) {

var roll1=roll(i.toString(), clientSeed+'-'+0);
var roll2=roll(i.toString(), clientSeed+'-'+1);

if(roll1==preRoll1 && roll2==preRoll2)
{
console.log(
"Result ", i," -> ",
"Client Seed: ", clientSeed,
" - Server Seed: ", i,
" - Roll 1: ", roll1,
" - Roll 2: ", roll2
);
}
}

Newline left in the stream.

; assumes:
; ds:si is ptr to array
; cx is length of array
; es is a free segment initialized to 0
@@: lodsw
mov di, ax
inc [es:di]
loop @b
push es
pop ds
xor si, si
xor cx, cx
xor bx, bx
@@: lodsw
cmp ax, bx
jbe .a
lea bx, [si-1]
.a: loop @b
; result in bx

I just applied for my very first job ever. It's for an entry SE position in my city. I'm nervous about what to do if I actually get contacted back. If I do get contacted, how long will it probably be? And if they want to set up an interview, how long from then should I schedule it?

C fags will defend this.

Is it a seed or just a nonce?

Also try to clarify a bit, I have no idea how this system works or what you're trying to accomplish. Relevant information only helps.

defend this
-- | 'the' ensures that all the elements of the list are identical
-- and then returns that unique element
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = errorWithoutStackTrace "GHC.Exts.the: non-identical elements"
the [] = errorWithoutStackTrace "GHC.Exts.the: empty list"

Thanks. I fixed it.

int average(int a, int b)
{
int sum = a + b;
return(sum / 2);
}

>library

>How can you tell OPs cartoon girl is a trap?
Because cisgender girls don't use C.

haha no way this would pass production code review

>not ANSI compliant
>doesn't use 1TBS
0/10 see me after class

it generates only a server seed. I then take that seed and get the SHA256 hash equivalent using this site:
passwordsgenerator.net/sha256-hash-generator/
I then use this site, plug in the hash, server seed, client seed and then it generates the nonce for me
dicesites.com/primedice/verifier

What's wrong with it?

yes but can you average two strings

template constexpr auto average(T... n) { return (n + ...) / sizeof...(n); }

>Array

Autist on Sup Forums who started the meme used to say nope, UB, not portable, etc. to every response.

His definition of averaging 2 ints(only kept to himself) was incomputable. Don't bother.

/**
* Averages strings s1 and s2, storing the result in s3
* Up to the caller to ensure that s3 is at least as long as the longer of s1 and s2, otherwise undefined behavior will result.
*/
void str_average(char s1[], char s2[], char s3[])
{
size_t len1 = strlen(s1), len2 = strlen(s2), maxlen = len1, i;
if(len2 > len1) maxlen = len2;
memset(s3, 0, maxlen);
for(i = 0; i < maxlen; ++i) {
s3[i] = (s1[i] + s2[i]) / 2;
}
}

What's the average of 1 and 0?

Now what does your method return?

What algorithm does that verifier use, is it documented anywhere?

You didn't say you wanted the answer in floating point form, or using a specific rounding convention, so by default the function uses the same rules as integer arithmetic in C.

dicesites.com/provably-fair
they run through the process here. Dont have the algorithm itself however

You frown on first designing your data-structures? Data-structures are the bread and butter of any program.

I'm not the one who prompted you in the first place. However, if you think returning an int for an arithmetic mean is good practice, you can argue as much as you want that the specifications weren't fair. You're still wrong.

That reads past the end of the string with the shorter length.

If you have the option of forcing the app to be deployed on Node version >= 7, I highly recommend to write everything you can with async/await. It maybe pretend synchronous, but a hell lot easier to work with.

Better yet:
float average(int a[]) {
float result;
for(int i = 0; i < a.length; i++) result += a[i];
return result / a.length;
}

>Le integer average meme
God damn, I have to keep posting this shit.
/**
* Averages an array of integers.
*
* Averages an array of integers, without overflow or conversion to a larger type.
* It is equivalent to the sum of the array, divided by the array's length (rounded towards zero).
*
* @param n Number of array elements. Must be greater than zero.
* @param arr A pointer to an array of n integers. Must be non-null.
* @return The mean of the array's elements.
*/
int iavg(int n, const int arr[static const n])
{
int avg = 0;

/* A buffer of values that are lost to integer truncation.
* It should always be in the closed interval (-n, n).
*/
int error = 0;

for (int i = 0; i < n; ++i) {
avg += arr[i] / n;

int loss = arr[i] % n;

// error + loss >= n
if (error > 0 && loss > 0 && error >= n - loss) {
// error = (error + loss) - n
error -= n - loss;
++avg;

// error + loss 0 && error < 0)
--avg;

return avg;
}

>convert both strings to an int value
>average them
>convert average to a string value

HOW DO YOU DO THIS IN ASSEMBLY?

I AM FUCKING PANIC RIGHT NOW

me@server node -v
v4.4.2

And no I can't upgrade it. There's a hacky third party lib that might do the job, though.

/**
* Averages strings s1 and s2, storing the result in s3. Up to caller to ensure
* that s3 has enough allocated space to store the shorter of the two input
* strings, otherwise undefined behavior will occur.
*/
void str_average(char s1[], char s2[], char s3[])
{
size_t len1, len2, minlen, i;
len1 = strlen(s1);
len2 = strlen(s2);
if(len1 < len2) minlen = len1;
else minlen = len2;
memset(s3, 0, minlen + 1);
for(i = 0; i < minlen; ++i) s3[i] = (s1[i] + s2[i]) / 2;
}


Should be fixed now. My original intention was to treat the shorter string as being extended with null characters at the end, but that wasn't implemented properly and I ended up deciding it would be "cleaner" to just do the averaging up to the null character of the shorter string.

nvm? Do it! It will save you 10 headaches per function. As a bonus they might call you back later, because Pajeet can only into ES5.

SOMEBODY

PLEASE


RESPOND

On line 7 of the code you posted you are missing a closing ) bracket.

Look up how error reporting works in javascript so you know whats wrong. Usually languages that arent compiled like javascript and PHP have a line of code to turn on error reporting and print errors to the browser window for testing purposes.

Write it in C and then compile and disassemble it

How would I go about calculating seconds until the next Friday 10 AM in Lua?

Don't know what architecture you're using, but one of the first steps when looking at a problem is to find out how many variables you must work with. In this case it's four (current, stars, spaces, counter) so if you have that many general purpose registers, you don't need to worry about storing them on the stack.

Next step is to transform your loops and ifs into jump statements. Your program uses no standard ifs, and only while loops, and the general template for the assembly code of a while loop is something like:
LABEL:
test condition
jump to EXIT if condition is false
blahblahblah
jump to LABEL
EXIT:

Our class isn't using x86, it's this shit:

en.wikipedia.org/wiki/LC-3

I don't understand assembly AND I NEED HELP THE HOMEWORK IS DUE TOMORROW

The class is using the LC-3 cpu and there are 8 16-bit registers

Thank you so much i'll keep working on it

;; Author: Chris Wickell


.ORIG x3000

LD R1, N
NOT R1, R1
ADD R1, R1, #1 ; R1 = -N

AND R2, R2, #0 ; R2 = holds number of *'s to be printed

LOOP LEA R0, NEWLN

PUTS

ADD R3, R2, R1 ; while (R2 < N)

BRzp ELOOP

ADD R5, R5, #1 ;

ADD R4, R4, #1

FLOOP LD R0, STAR ; R0 = *

OUT ; Write *
ADD R5, R5, #-1

BRp FLOOP

ADD R5, R4, #0

ADD R2, R2, #1 ;

BRnzp LOOP
ELOOP
LEA R0, NEWLN

PUTS

STOP HALT

N .FILL 6

STAR .FILL x2A

NEWLN .STRINGZ "\n"

>Have psuedo code
>still cant write assembly
just drop out and stop wasting your time

Languages are just tools. Figure out what you want to accomplish. Find a niche you know will intrest you and dive into the language that can accomplish that.

You wouldnt use a hammer to install a screw.

Specializations:
Phone apps = Java
Desktop apps = C++
Websites = HTML, CSS, Javascript, PHP
Database Admin = SQL
Network Admin = DOS/Powershell or Unix/Bash shell

>interrupting the enemy when he's committing a mistake

import std.stdio;

void main(){
int a = 1;
int b = 0;
writeln((a+b)/2.0);
}

I'll read through this, thanks

please guys i'm just getting started

Offering criticism without an alternative is useless

>I'll read through this, thanks
it is straight from stack overflow

careful about copy-pastes from the internet /fraud

>import std.stdio
>void main
>writeln
[TRIGGERED]