/dpt/ - Daily Programming Thread

Old thread: What are you working on, Sup Forums?

Other urls found in this thread:

lwn.net/Articles/444910/
lwn.net/Articles/446317/
syl9.com/csci193/Notes/193eigth.pdf
python.org/dev/peps/pep-0008/#function-and-variable-names
blog.janestreet.com/whats-in-a-name/
github.com/NoelFB/Celeste/blob/master/Source/Player.cs
twitter.com/SFWRedditGifs

hello lads,
show me what you're working on.

a % b is equivalent to a - (b*floor(a/b)) where floor(x) gives the greatest integer less than or equal to x.

int i = (int)((char)(1000));


Shouldn't I's value be 488? Why is it still 1000?

1000 in binary is 0b1111101000 if we take away the two most significant bits for the char cast, it should be 0b111101000 which is 488.

What am I missing here?

Fourth for Haskell

Im sorry I mean 104, but still, not 1000

Reminder that traps are gay

lol A char is normally 8 bits (1 byte).
You want a short

Cute Hideri is cute

Ok well ignoring that "0b111101000" is 9 bytes, what happens on conversion that involves overflow is implementation defined.

If you want to explicitly zero certain bytes, use a bitmask.

cutting binary 11 1110 1000 down to eight bits is binary 1110 1000 or decimal 232


binary 1 1110 1000 is decimal 488 but nine bits
I don't know of any language, compiler or interpreter with a data type of nine bits

Is hackerrank shit? Is codecademy shit?
What do you use for similar "do this exercise" based shit?

I like learning different languages or refreshing on new languages. But the exercises are really what help me progress through something and learn and enjoy it more.

C#, VS.

Yeah sorry fucked that up. I'm implemeting casting in my compiler for a class and I'm trying to figure it out. So, I's value should be 232 if I implement it by just taking away the excess bits for the type I'm casting to, right?

Just do a small project you're actually interested in doing in the language. Small exercises are fucking garbage for actually learning a language.

>int i = (int)((char)(1000));
>*b = 0x0;

wow
very good code guys

What language should I use for class assignments? Started out using C, which was nice for fundamentals, but most people are using something easier to write in like Python, which I'm not a huge fan of. Went through the tour of Go and it seems like a nice language -- easy to pick up, simple and productive. Any other suggestions?

Why did they make Linux object-oriented, /dpt/?

lwn.net/Articles/444910/
lwn.net/Articles/446317/

yes.

tank u

Idk about that man, reading through and doing the exercises in C++: Control Structures Through Objects vastly improved my programming skills.

syl9.com/csci193/Notes/193eigth.pdf

No matter what value X is, either decimal or binary, once you binary add 255 you will cut off all excess bits except the first 8, thus casting a char.

var i = 1000;
i &= 255; // simulated cast to char
i &= 255; // no effect
Console.WriteLine(i); // prints 232

Because it's a kernel.
If you want NICE code, like REAL nice, we all know the only option is algebraic typing.
But if you want PASSABLE code -- like, comfy to work with in some limited capacity -- gross, but workable -- then, OOP is also an option. The only other one, in fact.
Now, between algebraic typing and OOP, you tell me which one is better suited TO A KERNEL, specifically. Remember that this kernel has to be able to run on really ancient 32 bit machines that were probably around before you were born.
Show me a nontrivial program, written functionally, that makes use of algebraic typing and other high level conveniences that DON'T smell of POO, and yet is suitable to run on, say, a pi zero -- and I'll show you an analog computer that can play WoW. Or, for that matter, a flying pig.

jrpgs will save systems programming

>tfw you change data structure and get much better performance
i wish hitler was alive to see this

complexity or constant factor?

Difficult to say. The solution was pretty complex before I changed to a hash map instead of a sequentional container. I think complexity, though.

>int * i; *i = 0;
Nice UB you got there

Been programming a genetic algorithm for a research idea I had. I finally finished programming it, but now I have to troubleshoot.

>the point

how much soy could a rust-fag eat if a rut-fag could eat soy?

int i;
i = i ^ i;

soyboys eat very little food

How to make her my gf?

meme
how many times will i forgot to write int &a = x, int &b = y instead of int& a = x, b = y

>teach myself python in spare time
>really useful and ez
>want to do a decent project for showing to potential employers(NOT CS / Programing employers)
>Realize I have never shown anyone my code before
>Realize It must be full of rookie mistakes because I practiced alone

Save me.

I have a couple interviews next month for data science internships and I am priming some projects.

What screams brainlet about my code?
Pt 1
import os

#finish making this general
def create_dropzone(subject):
the_way = r'C:\Users\Shepard\Documents\data\{}\Results'.format(subject)
if not os.path.exists(the_way):
os.makedirs(the_way)
os.chdir('C:\\Users\\Shepard\\Documents\\data\\{}\\Results'.format(subject))
my_index = ['Division', 'Subject', 'Course', 'Section', 'Professor', 'Title', 'ISBN', 'Price']
output = open(r'C:\Users\Shepard\Documents\data\{}\Results\{}data.txt'.format(subject,subject), 'a')
output.writelines(','.join(my_index) + '\n')
output.close()

def cleam(course):
to_be_cleaned = open('{}'.format(course)).read().splitlines()
muh_list = [x for x in to_be_cleaned]
muh_list = list(filter(None,muh_list))

removeline = [muh_list.index(line) for line in muh_list if line.startswith('Suggested')]
#print(removeline)
if removeline :
muh_list = muh_list[:removeline[0]]
dataline = [data.strip() for data in muh_list[1].split(':')]
bookref = [muh_list.index(line) for line in muh_list if line.startswith('ISBN')]
return muh_list,dataline,bookref
#main_list, first_line, booklines =cleam('ACCT_2253_02.txt')

Looks good to me lad, maybe I'm a brainlet too though
t. CS Studentfag

Fuck...I need to contact a certified Non brainlet.

How open are your professors to being approached for advice on personal projects?

Specifically being approached by people outside the department.

your variable names are terrible, you should practice using professional-looking names

you use [x for x in y] too much, e.g.
[x for x in to_be_cleaned]
# should be
list(to_be_cleaned)

If you aren't a student it would depend entirely on the person but most would probably not be receptive. People outside the department it also depends but mine are pretty easy going and would probably be okay to give some pointers.
As for myself they've given me lots of help, going over things I ask, and then explaining why x causes y and so on.

Goodluck user.

Forgot Part 2

def grabbooks(bookrefs,cleanedlist):
add_to_dataline = []
bookrefs.append(None)
for i,t in enumerate(bookrefs):

if t is not None:
#print('line t is . ',cleanedlist[t])
ezdata = cleanedlist[t-1:t+1]
if len(ezdata[0]) > 75:
#find a better way to do this
ezdata[0] = ezdata[0].partition('View options')[0]

data = cleanedlist[t+2:bookrefs[i+1]]

#print(data)
gt = [list(filter(str.strip, line.split('\t'))) for line in data if 75 > len(line) > 2]
#print(gt)
ezdata.append(gt)
add_to_dataline.append(ezdata)
#print(ezdata)
#print(add_to_dataline)
return(add_to_dataline)


Besides Muh_list what are the improper var names?

What would a professional variable look like?

I am in the Econ department, and all my professors can only code in shit like matlab or Stata.

I am gonna try to ask the guy who teaches the entry level CS classes.

ty brother

some more advice: you essentially rewrote the same string ('C:\Users\Shepard\Documents\data\{}\Results') three times which is just asking for a typo. you should always be looking for repetition in your code and finding a way to factor it out.
there's no reason to make my_index a list if the only time you use it is as a string. just write out the string.
finally, it's usually preferable to use with open('file') as f: instead of f = open('file'); f.do_thing(); f.close()

grabBooks (camelcase)
bookRefs, cleanedList.
Also make sure to be consistent so don't flip flop between book_ref and dataLine
I should have picked up on this on your first round, sorry.
Just make sure your variables are obvious in what they do and are formatted correctly.
Good luck then lad, godspeed.

You should use .readlines() instead of .splitlines() so you don't read the whole file into memory

Also you don't have to use list comprehensions for everything. I know its less lines but a normal for loop is typically more readable.

anything like muh_list or my_index or the_way looks weird to me. why not something like "book_list", "index", "data_path"? each word in a variable name should add to its descriptive value.

in python the usual standard is underscores, not camelCase, see python.org/dev/peps/pep-0008/#function-and-variable-names

CS student here

1.
>the_way
>my_index
>create dropzone
>muh_list
as great as these all are, meme names aren't exactly professional. great for humor if you aren't working for/in a company, but not very good unless everyone at the company gets the references, pus in larger code-bases when the inevitable new-hire has to maintain your legacy-code, having stale memes will make it hard for them to know what what is.
Try using boring and obvious names like "output", "dataline", etc.

2.
Make sure to comment parts of the code that may not be too obvious or unclear, you can never go wrong commenting up the wazzu, just remember not to comment on the obvious print("lol") #prints the string "lol". additionally, comment on why you did something if you need to, because sometimes some tard mkight change the code to something they can comprehend much easier but which negates the advantages yours might've had. If not finished with a certain part, make sure to leave a todo list so that other programmers know what needs to be added, otherwise pain will be your future.

3.
what said. feel like a brainlet myself for not having thought of that.

Ty guys so much this is exactly what I needed.

Here is the finale piece.

def form_the_final_lines(stable_line,change_line):
#print(change_line[0])
#print(change_line[0][:2])
output = open(r'C:\Users\Shepard\Documents\data\accounting\New folder\finalflash.txt', 'a')
for x ,v in enumerate(change_line):
#print(x)
output.write(','.join(stable_line+change_line[x][0:2]+[change_line[x][2][0][-1]])+'\n')
print(','.join(stable_line+change_line[x][0:2]+[change_line[x][2][0][-1]])+'\n')
output.close()


#remember to check all the nested lists inside GG for later use
#firgure out how to create a multidimensional array


#form_the_final_lines(first_line,gg)

TIL, I've only used Python for quick little projects so I've not really looked into it much.
A bit annoying too because I usually use camel case.

What's the complexity of iterating over an unordered_map in C++?

amortized O(n)

For fucks sake, I stupidly thought it was O(1)

...

An intermediate name could help clarify your code here
... change_line[x][2][0][-1] ...
# becomes
my_name = change_line[x][2][0][-1]

then you refer to my_name in the two places you use it

i meant to add: this is another case where you're noticing a duplication, and factoring out the copied functionality into one place. it's a pretty common way to improve code, and one of the first things i look at when reviewing stuff from interns/juniors

Rate my code and tell me where to improve pls.
Java because industry standards.
import java.util.Scanner;

public class SumTriangle {

/**Main method to facilitate user input and print to screen.*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//scanner object so that input can be facilitated easily
System.out.print("rows: ");
int n = sc.nextInt();
sc.close();//to avoid resource leak
System.out.println("Sum of rows: "+rSum(n));
}

/**The program below takes a provided number (num) and sums it reccursively.
* For example, 3 rows would sum to 6 since 6 = 3 + 2 + 1, 4 rows to 10, etc.
*
* @param num
* @return sum
*/
public static int rSum(Integer num) {
int sum = num;
if(sum

>where to improve
try not using java

memes aside, i've never see a comment (/**Main method to facilitate user input and print to screen.*/) on main(). it's strange.
actually you have too many useless comments in general. we know you're making a scanner so you can take in input. we know you're closing your scanner to avoid a resource leak.

there's no reason to rename "num" to "sum". you should probably use math instead of recursion here (though it looks like homework so you're probably required to use recursion)

>You essentially rewrote the same string [..] three times which is just asking for a typo
I was still working on that function. I was planning on using the_way to remove the repetition.

>there's no reason to make my_index a list if the only time you use it is as a string. just write out the string.

I am using a list because I want to be able to customize my header using parameters. Obviously I have not added that yet and both of these Perfectly point out why I need to add comments to my code.

>finally, it's usually preferable to use with open('file') as f: instead of f = open('file'); f.do_thing(); f.close()

Why? Does the first way automatically close the file? I don't know shit about how these things actually work under the hood. Does your way open and close the file?

Thanks for all the feedback.

perfect, glad to see that there's a reason for the first two.
yes, a with statement will automatically close the file after you've exited the block. it's just a handy thing python has to help us avoid having to .close() everything. (and in general, the with statement helps us automatically handle context)

The first books I read made me very scared about namespace. Wont I run into problems using simple names like output, index, ect.

I know I should be ok If I stay local, but I really worry. Explain away my brainlet woes.

>Also you don't have to use list comprehensions for everything. I know its less lines but a normal for loop is typically more readable.
>you use [x for x in y] too much, e.g.

I had a bad experience with multiple nested for loops in my last project.

When do I use List comprehensions vs for loops vs other options I dont know.

You seriously don't need comments for something which is obvious what is happening. If you're in school and the prof demands it okay, but otherwise, even in work that extreme amount is just pointless. Comments should be there to clarify something ambiguous or not instantly obvious. You don't need to tell the person what a scanner is, they know if they're writing in java. Same with your recursive sum function is blatantly obvious too.

maybe this doesn't fit your situation, but i solve the first problem with my text editor. it highlights any time i'm shadowing a built-in name. for example, if I wrote "list = []", it'll point out that "list" means something already.

>Tfw shitty bug because java automatically pass by copy every fucking function rather than passing by reference like a smart person
REEE

Yeah it is homework (finished homework mind you, i'm here to see how to improve), that's part of the reason for the useless comments and the recursion.

You mentioned using math as opposed ot reccursion or loops for adding the sum a number of rows, mind giving me a hint as to how this would work?
My best guess is it involves pic related, dunno what libraries do it though.

>stop using java
honestly senpai i can see why people complain about it. EVERYTHING is an object, and that's super-innefficient for most of these practice applications. Modules would be a better way of doing that. OOP is a useful paradigm in some situations but its fucking attrocious where abstract structures are not needed.

You need to work on your writing skills bruvh, that blurb reads like a middle schooler's home work.

I'm not fucking borges, but I'll try to start reading at least better writers.

>Modules would be a better way of doing that
i realize this might be misleading.
What i mean is modules would be a better way of doing libraries then having objects for fucking everything.

>her

Acording to Terry, naming is the most important thing in programming. Has anyone written a book/document on good naming practices?

yup, use summation formulas
it simplifies to (n(n+1))/2

Yes but it never got released because they couldn't come up with a name for it.

I concur. All hail modules

There are only two hard things in CS: cache invalidation, naming things, and off-by-one errors.

Modules are just static objects.

>honestly senpai i can see why people complain about it. EVERYTHING is an object, and that's super-innefficient for most of these practice applications. Modules would be a better way of doing that. OOP is a useful paradigm in some situations but its fucking attrocious where abstract structures are not needed.
No offense but you're doing entry level Java, you really don't even have a clue on the benefits or flaws in OOP or Java yet. These toy problems don't tell you anything about the pros and cons of a language really.

If it wears girls clothes it's not gay and if it isn't gay it must be a her.

The sum variable can be left out. rSum should take an int rather than an Integer in order to use less space and avoid garbage collections. Again the single-line comments are unnecessary. Javadoc comments above functions is usually 90% of the comments you need, with single line comments only to clear up particularly confusing logic if you have to (but first consider fixing your code rather than just commenting over shitty code, if the situation arises)

blog.janestreet.com/whats-in-a-name/

How to "collapse" all whitespaces and newline characters in a string in c++

std::str_convey(std::collection(std::space, std::newline), "foo bar");

>trying to get into electronics/hardware programming
>cant because cant come up with interesting projects and development is slow
what do

This can't be real.

He asked sepples code, not pseudocode.

see
face it, she's cute :)

i-im cuter.

...

What are some usual projects that people do to showcase in their portfolio?

std::what_a_shitty_language()

:O

#include
#include
#include

template
Iter collapse(Elem fill, Pred pred, Iter begin, Iter end) {
Iter dest = begin;
bool front = true;
bool collapsing = false;
for (Iter it = begin; it != end; ++it) {
if (pred(*it)) {
if (!front && !collapsing)
collapsing = true;
} else {
if (collapsing)
*dest++ = fill;
*dest++ = *it;
front = false;
collapsing = false;
}
}
return dest;
}

std::string collapse_ws(std::string str) {
auto last = collapse(' ', isspace, str.begin(), str.end());
str.erase(last, str.end());
return str;
}

int main(void) {
assert(collapse_ws(" foo\n bar ") == "foo bar");
}

there is no "usual" thing, actual impressive projects are nontrivial and usually some what unique. It's like asking what's a typical first book an author writes.

If you have a certain career goal try doing a project related to it, if you want to work on a game do some game dev stuff, if you want to work as a webdev make a website, etc.

OwO

github.com/NoelFB/Celeste/blob/master/Source/Player.cs

Discuss.

Better than most of the students I tutor.
Fix your naming and learn to be more "pythonic", otherwise it's fine.

>fishnet stockings
Slut.

The reason it's so generic is so that we can make other collapser functions for different scenarios

void collapse_ws_cstr(char* str) {
char* end = str + strlen(str);
end = collapse(' ', isspace, str, end);
*end = '\0';
}

int main(void) {
char other[] = "hello world!";
collapse_ws_cstr(other); // in-place, so no heap allocations done
assert(strcmp(other, "hello world!") == 0);
}

Would be cute without the heels

How can I convert a byte array to a single float value in C#?

>type "byte array to float into startpage"
>click first result
>float myFloat = System.BitConverter.ToSingle(mybyteArray, startIndex);
now fuck off and die

noted

I saw that, but that's asking for an index of the array to convert. I want to convert all of the members of the array into a single value.