What code are you writing today?
Daily Programming Thread (DPT)
Other urls found in this thread:
codeabbey.com
adriann.github.io
reddit.com
github.com
ccs.neu.edu
youtube.com
haskellbook.com
en.wikipedia.org
github.com
tutorialspoint.com
en.cppreference.com
glowstone.net
msdn.microsoft.com
zerobin.net
en.wikipedia.org
pastebin.com
github.com
archive.fo
8ch.net
lkml.org
wikileaks.org
open-std.org
twitter.com
Working with libssh to get a C version of my python SFTP upload program working. Not sure if there's going to be much of a performance improvement, since most of the heavy stuff is outside of the main loop, but it should at least be much smaller.
Programming web-app using Django & Python 3.5
Fucking around with C# and Mono. I thought I might as well learn it, since it can't be worse than Java.
Turns out they really want you to use Visual Studio. It's annoying when I just want to find out how to compile a library and every tutorial starts out with "First you open Visual Studio and make a new library". Eventually I found out it's just -t:library when compiling.
That's my line.
why arent you using monodevelop?
I just like to know what's going on behind the scenes before I try using an IDE. So far I've got linking and compiling as a library down, but it's a little tedious because you have to specify every library.
Shell scripts for downloading/scraping various things from web so I can escape all the tracking of Internet. Also some crawlers for things that are not behaving nicely.
My theory is that they will get no useful info about my browsing habits if I download everything and browse interesting things offline.
How much storage do you have? Or are you just throwing away the stuff that doesn't interest you and continuously downloading?
I used to feel that way, but then I realized that taking a more top-down approach to language/framework/tool learning meant faster development time.
this is interesting. how do you discover what to scrape (you have to "browse" the web at some point initially, correct?)? is running no-script not a possible solution?
I'm trying to decipher the spaghetti that is the minecraft code. This is the most asinine program ever.
Was the source release, or did you use some kind of java bytecode decompiler?
we all know the source will never be released
using the decompiled mess that is shipped with forge
About 1TB.
Stuff that is downloaded just to mess with tracking is moved to /dev/null after downloading completes. And most stuff that I download is news stories that I remove every few days.
I browse offline mirrors with NoScript enabled so nothing is downloaded.
Sometimes I would have to go to "online" web, but I am hoping that I would be able to create something like randomly generating requests that will hide what I am really looking for.
Recently installed Eclipse despite barely any programming knowledge and no idea what to try and make. Does anyone have that "try and make this" thing so I can give it a shot?
Tic tac toe
Taking some rust off my C skills, so I picked up some old homework assignments back from school and try to overdo it.
Currently I'm implementing an abstract linked list to read an unknown number of numbers from input
making a platformer in c++ with sfml.
It's something.
Christ it's so hard to understand what I'm doing with this. Gonna post a snippet of what didn't work, and what did work:
public void onEvent(BlockEvent.HarvestDropsEvent event) { World world = event.world; ItemStack stack = event.harvester.getCurrentEquippedItem(); if (!world.isRemote) { if (event.block == Blocks.stone) { event.drops.clear(); event.drops.add(new ItemStack(ModItems.stoneFragment, 4)); if (event.y 0) event.drops.add(new ItemStack(ModItems.geode)); } } }}
This caused the game to crash after working one time only, couldn't get it to not crash after loading up the same world again. This below, is what I had to do to fix it.
public void onEvent(BlockEvent.HarvestDropsEvent event) { World world = event.world; if (!world.isRemote) { if (event.block == Blocks.stone) { event.drops.clear(); event.drops.add(new ItemStack(ModItems.stoneFragment, 4)); if (event.y 0) event.drops.add(new ItemStack(ModItems.geode)); } } }}
Fucking nonsense.
I am going to steal your thread for a moment.
Many have told me that books are the best resources for learning C++, and at this moment, I am using the learncpp website to teach myself.
Any suggestions or resources to further learn?
Practice the art of interpreting problem specifications and designing solutions for them i.e. go and write computer programs!
See to get started
I'm working my way through Realm of Racket, but I'm not really digging it. I have no idea why people rate this book so highly, it teaches me neither how to program in general, nor how to program in Racket specifically. It's really just a books about gluing libraries together. The only worthwhile parts are in between games where you learn more about Racket like its for-loops, but I don't think I would have been able to get anything out of it if I hadn't already known Scheme from SICP before reading RoR.
Before he can write computer programs he needs to know how to use the language. That's like dumping some welding tools on someone and telling them to go weld something without telling them how to weld. They will eventually figure something out, but it will be a horrible welding job.
I don't know what that's supposed to mean. You mean how to design a solution to a problem? Or how to design a program so you don't screw yourself over?
I mean general programming practices, like in the first chapter of SICP or like Common Lisp: A Gentle Introduction To Symbolic Computation. It's no problem for me, but RoR markets itself as a book for beginners. I have no idea who its target audience is.
I've assumed that he has completed the learncpp.com tutorials and now he needs some kind of motivation to put those lessons into practice.
RoR is an almost impossible book to get through as a beginner. The way it just poorly dumps some info then moves on and the fact that some of the code won't run as it has errors. If someones new they will just hit a wall. It's the worst of the three. The other similar books being land of lisp and clojure for the brave.
I wrote a simple Python script that converts the save files from FlagMaker1.7 to be compatible with FlagMaker2.
FlagMaker2 has been out for a good couple months and as far as I can tell I'm the only one that managed to write a converter. It's a major surprise considering there isn't much to change in the save files to make it compatible.
I wrote it a couple days ago but I guess I can still post it here: github.com
Don't care it does the job.
I'm willing to do a spotify-like interface to listen music from youtube with youtube-dl, is there already exists something like that?
Belongs to the sticky but here goes. There's a python module called mps-youtube that is a terminal youtube browser. It's not exactly spotify but it supports youtube-dl and mpv.
whats the point in learning to code? No one can tell me this.
I've implemented elaborate optimization technique and it wound up doing jack squat for runtime costs and improved search costs by a small percentile. Fuck.
To fill the unending void in your life that comes with the existential crisis, desperately trying to block out the horrible reality that all things must come to an end until nothing remains and the universe grows dark and cold, devoid of organic life and even artificial life that could appreciate anything that was ever done through the history of existence, nothing left to keep the memories alive.
Some people collect stamps, others learn to write software.
To just like make game
to make computers do things newfriend
is java a good place to start?
Java throws you in the deep end with a lot of complex ideas. Python would probably be a better place to start, because it's made to be simple and a lot of things use it. I don't know it myself, so I can't be more help than that.
Do you want a book recommendation?
...
I'd +1 python. Download blender and start using the built-in python interpreter to make it do interesting things.
...
Sure
What the hell is the deal with that code?
Zzzzzzz
Behold, the power of java.
This is pseudocode for addition in acceptable programming languages. 2 instructions maximum
ADD r1, r2JO ; optional for checking
This is the same in any modern day "scripting" shit language.
static PyObject *binary_op1(PyObject *v, PyObject *w, const int op_slot){ PyObject *x; binaryfunc slotv = NULL; binaryfunc slotw = NULL; if (v->ob_type->tp_as_number != NULL) slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); if (w->ob_type != v->ob_type && w->ob_type->tp_as_number != NULL) { slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); if (slotw == slotv) slotw = NULL; } if (slotv) { if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ slotw = NULL; } x = slotv(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } if (slotw) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } Py_RETURN_NOTIMPLEMENTED;}
This is inexcusable language design, but "programmers" here will defend this shit.
Sometimes I need my computer to do things that nobody else has programmed yet or has programmed in a way that isn't exactly what I want, I learned so that I could make what I need when I need it. Initially it started with simple scripts to automate tasks like updating my web browser automatically every day, recently I wanted people to be able to listen to my media player and see the metadata from it, so I wrote a plugin for my media player and a simple http/sse server that it communicates with over a tcp socket, now friends of mine can hear what I'm listening to and actually see what it is as well as download that particular file if they want. It's a simple thing but I wanted it and I couldn't find a solution as good as the one I could come up with myself, so I just learned how to do it and did it.
You should be able to apply this concept to any problem, you know your computer can do something you just have to learn how to make it do that, once you do that you can make whatever you want/need, no matter if it's a simple scripting task or something more complex.
It's also fun imo even though I'm not very good at it, I like programming as a hobby but it's also practically useful for me too.
It's not bad (nor is C#) but like others have said, try out Python.
abstraction cancer is what's going on with this code
fuck these types of books if your trying to learn. these are just shilling, pick a language initially, python or c/c++ would probably be best initially.
I started programming when I was in middle school, just from reading books, and a lot of those books were bullshit and frustrating. I followed the tutorials to get the general idea, then I picked something I wanted to do within reason, and did it.
You have to follow the language enough to learn which questions to ask to troubleshoot. This is a big problem with languages, and beginners books, that are filled with abstraction garbage. Are you trying to learn the book, or whatever library the book is shilling?
I already know how to program in a number of languages, I was trying to add a functional language to my repertoire. Scheme is a very nice language, but its minimal nature means that every implementation does its own thing. Racket looks like the most powerful of them all and allows defining new languages on top of it. I'm a mathematician, so being able to create a DSL for a particular field would be a killer feature for me. Take for example this page:
ccs.neu.edu
They use the simplex algorithm to solve and optimisation problem. I know all the theory behind it, but if I wanted to implement the algorithm on a computer in another language I would have to throw all the elegant math out the window. In Racket however I can write the specification of my problem the same way I would write it on paper. That's really cool.
The problem with a language as large as Racket (or Python) is that finding your way around is like trying to find your way around a new city without any directions. I can start looking around randomly, but it takes forever to find something I might be looking for. That's why I was hoping the book would be good, and it has a shitton of positive reviews. I was hoping for a sort of guide to show me around the town language.
If you want to learn functional languages, you might be better off starting with Haskell, Scala or F#. Racket is a great language in it's own right but those ones don't limit themselves to LISP syntax, and end up a little clearer as a result. Explicitly defining types also helps with making sure you know what's going on under the hood. As an example here's a F# fizzbuzz:
open System//Takes an int, returns a string//Uses pattern matching and tuples. Note that _ means ignoredlet checker (x:int) :string = match (x % 15, x % 5, x % 3) with | (0,_,_) -> "FizzBuzz" | (_,0,_) -> "Buzz" | (_,_,0) -> "Fizz" | _ -> string x//The |> operator is a bit like a shell script pipe//(fun x -> something) is an anonymous function[1..100] |> List.map checker |> List.iter (fun x -> printfn "%s" x)
Code to calculate sunrise/sunset to use with a tiny redshift replacement some user here posted.
I don't really mind the Lisp syntax, with good alignment it looks fine. And since Racket allows the entire set of unicode characters I could use math symbols and Greek characters if I want to. I have Neovim set up to highlight matching parentheses, and I have a plugin for auto-closing parentheses, one for snippets (very powerful) and one for rainbow highlighting.
Here is my first try at FizzBuzz:
#lang racket(define (fizz? n) (zero? (modulo n 3)))(define (buzz? n) (zero? (modulo n 5)))(define (fizzbuzz? n) (and (fizz? n) (buzz? n)))(define (fizzbuzz n) (cond [(fizzbuzz? n) "fizzbuzz"] [(fizz? n) "fizz"] [(buzz? n) "buzz"] [else n]))(for ([i (range 1 101)]) (display (fizzbuzz i)) (newline))
But this isn't really Racket, it's just Scheme plus a simple for-loop. After some quick skimming of the documentation I found pattern matching which allows me to write code similar to yours:
#lang racket(define (checker i) (match (list (modulo i 3) (modulo i 5)) [(list 0 0) "fizzbuzz"] [(list 0 _) "fizz"] [(list _ 0) "buzz"] [_ i]))(for ([i (range 1 101)]) (display (checker i)) (newline))
Now this is Racket. It uses the same approach as your code. The checker has one more line, but only because I spread the list definition over two lines because I like it better that way. The list processing is three lines as well, it's more verbose than your F# code, but there is only one single syntax rule in Lisp-like languages, which makes it easier to get into the meat instead of tripping over new syntax. Even if you had never programmed Scheme before you would be able to read my code. And for static typing there is Typed Racket, it's a similar language where you can specify the types in the code, removing the need for dynamic typing.
This pattern matching is the kind of thing I was hoping to read about in Realm of Racket, but instead I had to find the good things on my own.
A JSON parsing library. I intend it to be used in an 8ch client for console.
It's shit, though, I intended it not to use linked lists, but iterating twice over the document is shit.
why? just use an existing library to get your main project (the 8ch client) out the door
Programming some NES homebrew, because I'm a hipster nigger.
Working with VBlank is weird. NES pallete handling is really fucking weird (you have to write the pallete address you want to access, one byte at a time, into address 2006, then you write into/read from 2007 (so if I want to access address 3F00, I write 3F into 2006, then I write 00 into 2006, then I write all my output bytes into 2007 one at a time).
Fun shit.
youtube.com
Working on a metroidvania using irrlicht, bullet and lua.
Well, I want to learn as much as I can. Also, I fear an 8ch client will associate me with Holla Forums and, if published in my public git account, make me a little bit undesirable to get hired. A JSON library doesn't come with that problem, 100% publishable.
post code
my boss is forcing me to write a server in node js. how do I convince her to let me use something better?
How technically competent is your boss? If she's just picking node because she heard about it from somewhere get resources for the language you want and make a presentation. Show success stories, advantages and comparisons, and you can put literally anything as an alternative. For example "Perl runs on literally every web server in the world, and it's known as a server user's best friend", or "Python is made for quickly getting work done, so I'll be able to do this much faster than if I did it in node", or "Haskell uses fundamental math concepts to make a system that doesn't fuck up, and it's so reliable the stock market is powered by it", or even "C is so fast that it was made ages ago and to this day no other language can catch up"
If she's one of those hipsters, who just grabs onto the latest fad out of hype, you'll have to shill something she hasn't heard of.
Same thing except now I am learning how to deploy with nginx and gunicorn.
Say you'll do it.
But take extremely long time and waste company money on the implementation.
That'll teach the old cunt
What would you use instead?
She is forcing him to write a server in node.js, that should be telling how technically competent she is.
Quantum detanglement probability md5 algorithms. Don't bother me, its very complicated.
Why?
It depends. Node is one of those buzzwords that gets thrown around. Businessmen hear them and decide to do this node thing for better productivity.
Alternatively his boss could be one of those Starbucks-sipping, macbook-using hipsters who thinks they know how to code because they know basic web dev. It's much harder to convince them to use an old, boring, uncool language like everything else. They're code hipsters, and want to use the cool new tech nobody's heard of.
it can be easier sometimes to just put a copy of the .dll's you need inside the project folder.
Or, it could be a site that has a massive JS frontend, and it could actually be useful to be able to share the infrastructure between the JS frontend and a JS backend.
Node is generally shit, but there are actually legitimate uses for it.
Why?
I thought of doing the same thing because not having the updater in elins/w3m kinda sucks and the layout is a pain in the ass unless you use a ruby script to convert the layout to use tables (for elinks), but I was just going to use jq to parse everything.
Probably wont get around to working on that since I've got a number of concurrent projects to work on.
Leetcode. I now realize I don't know shit about algorithms and it's depressing me a lot, so I haven't gotten a lot done.
...
Same here. Trying do use nginx as reverse prox for a Python and a php application in the same server. Nginx is fucking magical.
I recently bought a physical copy of SICP, and I'm going through the exercises of the first chapter. I just spent an hour debugging a simple program because I forgot to include parentheses around the cond clauses. Sometimes I think I shouldn't be having these issues; I've been programming for a long time.
#lang scheme;;;; Exercise 1.3 - Takes three numbers and returns the sum of the squares of the two largest numbers.;;; Square function(define (square x) (* x x));;; Sum-square function(define (sum-square a b c) (cond ((= a (min a b c)) (display (+ (square b) (square c)))) ((= b (min a b c)) (display (+ (square a) (square c)))) ((= c (min a b c)) (display (+ (square a) (square b)))) )) (sum-square 4 6 3)
please stop
big data
enormous penis
And look at that, it's still perfectly readable.
Changing the files on a pgm. Problem is the files have different fields of different types.
V5R4 btw
Writing a wiki in Ruby because somehow there isn't one already.
I got Professional C++ for christmas. Seems pretty good so far.
There is something even more cute that you can do if you get far enough into Haskell First Principles (namely, the Monoid Chapter), if you squint hard enough.
Namely by abusing monoids.
rule n s i = case i `mod` n of 0 -> Just s _ -> Nothingfb rules = map f where f i = fromMaybe (show i) (fold rules i
The part where the monoids are abused is:
instance Monoid m' => Monoid (i -> m')instance Monoid n => Monoid (Maybe n)instance Monoid [a]type String = [Char]-- ie, (m' ~ Maybe String)
Which implies:
instance Monoid (Int -> Maybe String)-- ie, (m ~ Int -> Maybe String)
The last connection is that:
fold :: (Foldable t, Monoid m) => t m -> minstance Foldable [a]-- ie, (t ~ [a], a ~ m)rule :: Int -> String -> Int -> Maybe Stringtest :: Int -> Maybe Stringtest = rule 11 "dubs"
The titular fizzbuzz is defined as:
fizzbuzz = fb [rule 3 "fizz", rule 5 "buzz"]
What does this do? What changed here?
rule' f s i = case f i of 0 -> Just s _ -> Nothingdubs = rule' (`mod` 11 . `mod` 100) "Check'em"
Well now I just got a terrible idea.
Can you show the full code?
I feel retarded now.
What amount of time should one invest in Haskell to come up with something like this?
Also I didn't find this book, can you share it please?
This is not a book, damn.
Could you upload the pdf?
Starting Out with C++ from Control Structures to Objects, 8th Edition by Tony Gaddis is IMO a great book for C++ especially if you're a newfag to the language.
I'm starting codecademy python lessons. I haven't scripted since writing tintin scripts for a MUD I played.
I'd eventually like to start making money with my computer so I'm going to learn coding in my spare time. What language (s) will I be able to monetize quickest? I no can into shoop
salesforce
How do I go about writing my own parser (from scratch, no all-done-for-you library)? I've been told recursive descent is not the proper way of doing it and the actual shit involved automata.
There's an introduction to lexical and syntactic analysis in the book Basics of Compiler Design by Torben Mogenson. If you want implementation examples, both GCC and Clang have their parsers in reasonably easy to find locations of their source.
Redoing a poor performing page using clojurescript with reagent. Hopefully using it as a proof of concept for further changes on other pages
I wrote a CLI for my Arduino. It's only able to do really basic stuff right now (get/set pin states and read/write memory/EEPROM), but hopefully I'll be able to turn it into something useful.
Trying to find all roots of simple equations within given interval.
from math import *
def f(x):
return x**2-9*x+2
for g in range (0,10,2):
a = g
b = 10.
funa = f(a)
funb = f(b)
if ( funa * funb > 0.0 ):
print " In given interval [%s, %s] there are no roots "%(a,b)
if ( funa * funb < 0.0):
print " There are root(s) in given interval!"
deltax = 0.001
k=0
while (fabs(b-a)>deltax):
x=(a+b)/2; funx = f(x)
k=k+1
if (funa*funx
To turn my computer into my slave, as much as possible. At least learn how to write some bash scripts.
for a in range (0,10,2): a = float(a)
?
Writing a markov chain generator for text. But I've been stuck on the data structure for a while now. I wrote one in Python before but figuring out how to get decent data structures in C is much harder than I thought.
My first 3 star program though lol.
Crouching looks a bit like autistic screeching
I am certain entropy is the lesser bias of creation. Otherwise we would go from novelty, complexity and complete differentiation to homogeneity, by contraction.
Instead we got expansion and growing novelties, more complex intelligent systems, dust to man apes building computers, and the best of all since the big bang: sex, the little bang. Shagtastic
I'm extending the Gloss library for easy graphics with Haskell. I've made some rather trivial improvements but they require you to use freeglut, but the maintainer won't accept it unless it works with old glut also, and now it turns out to not be so trivial anymore. :(
Writing a crypto library just for something to do. It's been three days and I've only got tests for boilerplate code done so far.
I only wish I was writing code today. There are a couple of projects Id like to be happily banging away at, but, alas, I must attend my job 5 days out of 7, and tonight.... tonight I drink... I drink to celebrate victory.
Things I wish I was coding:
1.) My own version of diagnostic software to interface with the ELM327 OBDii dongle, for Android. As a gear head I want live streaming data which only a few apps offer, and useful debug info when the interface fails
2.) Software for the PC to edit / manipulate / view GEDCOM family tree files, and an updated format of my own devising that includes more info
Holy trips and holy quads recognized.
I'm the luckiest guy in the world. Boss caught me on Holla Forums with big swastika on screen, and he just seig heiled me and kept walking.
Alright, I'm interested. Most Metroidvanias don't incorporate advanced physics.
I HAVE to write a simple game in Java
Which IDE should I use?
Intellij IDEA
text document + terminal
Hey gramps, it's not the 80's anymore
Thanks
I need a type of job/task server. It needs to:
1. Allow clients to schedule "jobs" sometimes in the future
2. The server will keep track of these jobs
3. The server will send the jobs to the worker agents at the time the job was scheduled
4. If a worker agent dies when it is doing work, the server will send the job to another worker
Can anyone recommend anything for this?
emacs
A single transferable vote counter. Getting the algorithm right and getting it fast/efficient enough to cope with large (>1gb) datasets is a challenge.
I'm trying to get into DOS programming, but GCC is being a real bitch. Trying to write to DL writes instead to DH, and turning on optimization completely breaks the program.
Are there any good C compilers that run on Linux and support real mode?
Check whatever the freedos project uses?
I'm a relative newfag to C++ can someone tell me what the last 2 lines of this struct are doing?
//----------------------------------------------------------------------------------------//// Defines a data structure for a chromosome////----------------------------------------------------------------------------------------struct chromo_typ{ // The binary bit string is held in a std::string std::string bits; float fitness; chromo_typ(): bits(""), fitness(0.0f){}; chromo_typ(std::string bts, float ftns): bits(bts), fitness(ftns){}};
looks like struct initializer overloading.
I'm trying out SmallerC. It's missing some stuff like asm templates and good documentation, but for what I'm doing, it's pretty good.
FreeDOS uses OpenWatcom, but that looks like bloated garbage
Structs in C++ are classes with default public access, ie if you don't specify otherwise anything can access anything inside it. This means they have all the power of classes such as constructors, destructors, operator overloads, member functions, static class members, inheritance, etc. The two functions are constructors, a default constructor that takes no arguments, and one that takes a string and a float.
Thanks.
What should I read to learn Perl the right way?
but the Perl meme is that there's more than one way to do it..
If you code for DOS you've got to put some soul in it. Write your code in DOS.
I prefer Turbo C.
Modern Perl & Higher Order Perl. The pdf version of both is free.
I learned the basics from Programming Perl, and the rest from making scripts. It's written for an older version, but it works fine.
Why doesn't this work?
print "Float %f" % .2 + .1
But this does?
num = .2 + .1print "Float %f" % num
The first one tells me it can't concatenate str and float objects, which makes sense to me, but isn't the second one just the exact same thing? Yet it works.
I might be wrong on this, but
In the first one, it evaluates ("Float % f" % 0.2) + 0.1
In the second, it evalues "Float % f" % (num = 0.1 + 0.2).
Basically, the string formating operator "%" has a higher precedence than "+", so "Float %f" % 0.2 + 0.1 becomes "Float 0.2" + 0.1.
But in the num case you've already calculated 0.1 + 0.2, so "Float %f" % num = "Float %f" % 0.3 = "Float 0.3"
Never assume things about operator precedence in C, because it won't work the way you think it will.
t. NASA Software Safety Guidebook
Looks like Python, so is correct, it's just working left to right, evaluating operators and operands as it sees them. One of my favourite parts of Python3 is it got rid of this stupid special instance of a function call, but the string format operator still exists.
what did barbie mean by this?
Wrong. Even if the order was different, modulo is always higher precedence than addition. See:
>>> print 'Float %f' % .2 + .1Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'float' objects>>> print 'Float %f' % .2 * .1Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'float'>>> print 'Float %f' % .2 ** .1Float 0.851340>>>
Always remember your order of operations.
What are things in modules called?
So for example there is a random module and from this random module I can import shuffle. What is shuffle called? What is it?
I have a character array of TWO ascii numbers
I need to convert them into either 2 separate ints or an int array (i dont care) what is the simplest way i can do this?
in C btw
an object afaik
If I understood your post correctly you are looking for atoi function.
Depends on the programming language and the type of the symbol. In Python, it's a function. If there's a class in a module, it's a class. The "things" in modules are the exact same "things" they are in the programs you write, so if there's a variable in a module, it's a variable (technically they're all "variables" that exist as properties of the module, regardless of what the contained type is).
Give us an example. what do you mean by "character array of TWO ascii numbers"? Do you have "45", or something like "43 47", or something else? atoi is probably something like what you need, but you might need to do more to it depending on what you've got going on. Use more detail in your questions.
Dependency management is a fucking nightmare (npm is fucking horrible), the diamond problem can fuck you over hard in this case. JavaScript is a pretty shit language. You want something that is way easier to modularize and build full testing frameworks and suites around and usually something statically typed. The only reason you use JavaScript is if you have to, or if you already have a shitload of stuff in JavaScript you have to work with.
This Was what I was looking for but IDK if im implementing it correctly
myint= atoi(characterarray[0]);
but gcc flips out if i do this
i have
char array[3]; (the 3'rd for the EOL)
i need to grab array[0] and array[1] which will be ascii numbers like 48 that represent real numbers like 0 . I want to put those real numbers into an int.
In that case, use atoi if you need to interpret the thing as a 2-digit decimal number, or use array[0] - '0' and array[1] - '0' to interpret as two different one-digit numbers.
Wrong, you need to feed it the character array, so just atoi(characterarray) will give you what you need. See en.cppreference.com
Oh, and it will work if the third character is a newline, but note that it MUST be terminated somehow. If it was a 2-element array and both were filled with numbers, your atoi function might read garbage from memory.
If you want better ability to error-detect (and safer, more flexible functionality in general), use strtol instead. Make sure you check your errno. I'd recommend playing with atoi to see how it works, and then replacing it with strtol with proper error-detection.
I thought atoi was implemented with strtol now.
Can't be, because atoi can't change errno.
Unless atoi saves and resets errno after the call.
More likely they both just rely on the same lower-level internal functions.
Thanks for all the help but none of these worked. atoi kinda worked if i did some weird shit but it gave me fucked up output, entering 47 would give me an int of 4 and an int of 47 not 7 like i wanted.
BUT
I developed a FOOLPROOF way that works 100% the way i wanted in the first place
BEHOLD :
int a = uinput[0]; int b = uinput[1]; a = a - 48; b = b - 48;
little did i know you can use an ascii character to define and int!
That works only on 1-9 range, answers that people gave work on whole range of int of your system. If you have told us that you have two DIGITS in ASCII then people would have given you similar answer to what you posted.
I am not mad at you, just please try to be very specific about things when doing programming questions because little details matter a lot in software world.
// glibc-2.24/stdlib/atoi.c#include #undef atoiintatoi (const char *nptr){ return (int) strtol (nptr, (char **) NULL, 10);}
Writing rogue-like game for TempleOS
Well, it sounds like you fucked something up. Maybe if you had actually posted your fucking code, we'd be able to tell what the fuck you're doing wrong.
i did
see
a character array is always going to contain a single number 0-9, 2 digit numbers are not characters
see
your comparison is disingenuous.
how would you implement an overloaded binary operator in the context of a type system with *only 2 instructions*?
I don't even know python
what is type inference in haskell et al?
barbie is a good for nothing "software analyst" or "software architect" who can't code for shit.
What the fuck? Why? That's wasting 87.5% of memory.
I bought Python the Hard Way and an entry level computer science book. The first one uses python 2 and the second one uses python 3 - which python should I start on?
...
i wanted to have a physical copy
3
Fucking pleb
It gives your thought structures ways to systematically break down complex problems into definable solvable operations. Way more useful than learning high end math or physics which can also teach your brain how to think but have very limited application outside of academia.
Java is slowly dying. Unless your obsessed with modding minecraft I would skip it.
Learn C or Python.
really ? Fuck, I don't want to send this book back. Is the jump from python 2 to 3 significant ? I was very attracted to the drills in Python the hard way - can I still make use of it ?
Im not really looking to make anything significant right now, I just want to learnl.
you're already an idiot for buying a book you'll toss away once you figure out how to use documentations
Java is slowly dying as fast as C++ is slowly dying - it is not. What makes Java so popular is that the language is universally known as a consequence of having the right programmers features to be productive in getting shit done. In addition to that, there's a Java library for any kind of work you wish to deal with. Pretty much the only space with minimal Java presence is in the low powered embedded computing space. Java is not dying any time soon.
Python 3 is mostly the same as Python 2. There are various notable differences between the two when you're ready to learn them. However, those differences are not difficult to learn by the time you've finished your book; there are plenty of websites that will teach the differences if you ask Google about it.
I just finished a parsing engine for making libgen files (and any derivative using it's file structure) human-readable instead of having a database of information along with a file named by it's md5 hash which also requires an SQL sever to be running to access.
u need to start learning python 3
2 should not even exist today but it does due to lazy devs
if you are writing software in py2 in 2k17 kys plz thx
doesnt matter just learn python 2 since thats the book you got
going from 2 to 3 wont be difficult at all
float f_atan(float x){ long long int i3, i5, i7 = ((long long in) (*(int*)&x)); i3 = i3*3 - 0x7EF47AE1; i5 = i5*5 - 0xFDE8F5C3; i7 = i7*7 - 0x17CDD70A4; x = x - (0.333f * (*(float*)&i3)) + (0.2f * (*(float*)&i5)) - (0.1428 * (*(float*)&i7)); return x;}
What manner of black magic is this abomination?
looks like some sort of hashing algorithm with stage IV cancer.
I think it's the inverse tangent function approximated by taylor's formula using floating point optimization?
how do i make a winsock server that's single threaded and always loops back to the listening state?
msdn.microsoft.com
looking at this right now and it can only take one client and then it shuts down. my current implementation is functional but the only way i got it working was to loop the entire program. ie reload the DLL i'm using, make a brand new listen socket, etc. what should the outline of the program be?
Can someone update this to work with LibreOffice? It's for Excel 2007.
Module1
Rem Attribute VBA_ModuleType=VBAModuleOption VBASupport 1'tarkistaa onko nappulaa painettuDeclare Function GetKeyState Lib "User32" _(ByVal vKey As Integer) As IntegerDim quit As BooleanDim spd, incx, incy As DoubleDim neg, hidasta As IntegerDim aika, paika, aiaika As SingleFunction liikuta_pelaaja(a As Boolean) ' False = vasemmalle ja True = oikeelleIf (Timer - paika) > 0.0001 Then 'liikutetaan tietyn ajan väleinpaika = TimerIf a = False ThenIf ActiveSheet.Shapes("maila1").Left >= 194 ThenActiveSheet.Shapes("maila1").Left = ActiveSheet.Shapes("maila1").Left - 6End IfEnd IfIf a = True ThenIf ActiveSheet.Shapes("maila1").Left 0.0001 Thenaiaika = TimerIf ActiveSheet.Shapes("maila2").Left + ActiveSheet.Shapes("maila2").Width = 194 ThenActiveSheet.Shapes("maila2").Left = ActiveSheet.Shapes("maila2").Left - 6End IfEnd IfEnd IfEnd IfEnd Sub
Sub liikuta_pallo()If (Timer - aika) > 0.001 Thenaika = Timerneg = Int(Rnd() * 2 + 1) 'kumpaan suuntaan liikkuu x/yhidasta = Int(Rnd() * 2 + 1) 'hidastaa palloa jos 1 muuten nopeuttaaSelect Case ActiveSheet.Shapes("pallo").LeftCase Is < 195 'osuuko vasempaan seinään?incx = Int(Rnd() * 2 + 0.5)If neg = 1 ThenIf hidasta = 1 Thenincy = incy - Int(Rnd() * 2 + 0.5)Elseincy = incy + Int(Rnd() * 2 + 0.5)End IfElseIf hidasta = 1 Thenincy = incy + Int(Rnd() * 2 + 0.5)Elseincy = incy - Int(Rnd() * 2 + 0.5)End IfEnd IfCase Is > 948 'oikea seinäincx = -Int(Rnd() * 2 + 1)If neg = 1 ThenIf hidasta = 1 Thenincy = incy - Int(Rnd() * 2 + 0.5)Else: incy = incy + Int(Rnd() * 2 + 0.5)End IfElseIf hidasta = 1 Thenincy = incy + Int(Rnd() * 2 + 0.5)Elseincy = incy - Int(Rnd() * 2 + 0.5)End IfEnd IfCase Else 'nyt katotaan häviääkö jompi kumpiSelect Case ActiveSheet.Shapes("pallo").Top - 1Case Is < ActiveSheet.Shapes("maila2").TopActiveSheet.Cells(3, 12).Value = "Häviäjä"ActiveSheet.Cells(3, 11).Value = "Voittaja"MsgBox "Peli ohi :)"EndCase Is > ActiveSheet.Shapes("maila1").Top + 3ActiveSheet.Cells(3, 11).Value = "Häviäjä"ActiveSheet.Cells(3, 12).Value = "Voittaja"MsgBox "Peli ohi :)"EndCase Else 'ja nyt osuuko mailoihin' alempi mailaIf ActiveSheet.Shapes("maila1").Top = ActiveSheet.Shapes("maila1").Left And _ ActiveSheet.Shapes("pallo").Left
Yet py2 is still the default python binary on most distros which gives the false impression that py2 is still the preferred version.
EOL for py2 is 2020 which will be a pain for package maintainers.
libreoffice uses Java instead of Visual Basic
you need to rewrite the entire code
>>>/suicide/
...
I'm trying to implement Perlin Noise from the wiki page in c but I keep on returning 0.00000. What am I doing wrong?
#include #define IYMAX 999#define IXMAX 999//float less percise than double but less errors// Function to linearly interpolate between a0 and a1// Weight w should be in the range [0.0, 1.0]float lerp(float a0, float a1, float w){ return (1.0 - w)*a0 + w*a1;}// Computes the dot product of the distance and gradient vectorsfloat dotGridGradient(int ix, int iy, float x, float y){ // Precomputed (or otherwise) gradient vectors at each grid node //extern float Gradient[IYMAX][IXMAX][2]; float Gradient[IYMAX][IXMAX][2]; // Computer the distance vector float dx = x - (float)ix; float dy = y - (float)iy; // Compute the dot-product return (dx*Gradient[iy][ix][0] + dy*Gradient[iy][ix][1]);}// compute Perlin noise at corrdinates x, yfloat perlin(float x, float y){ // Determine grid cell coordinates int x0 = (x > 0.0 ? (int)x : (int)x - 1); int x1 = x0 + 1; int y0 = (y > 0.0 ? (int)y : (int)y - 1); int y1 = y0 + 1; // Determine interpolation weights // Could also use higher order polynomial/s-curve here float sx = x - (float)x0; float sy = y - (float)y0; // Interpolate between grid point gradients float n0, n1, ix0, ix1, value; n0 = dotGridGradient(x0, y0, x, y); n1 = dotGridGradient(x1, y0, x, y); ix0 = lerp(n0, n1, sx); n0 = dotGridGradient(x0, y1, x, y); n1 = dotGridGradient(x1, y1, x, y); ix1 = lerp(n0, n1, sx); value = lerp(ix0, ix1, sy); return value;}int main(){ printf("%f\n", perlin(4, 4));}
I don't get this at all, can someone explain it to me? how does the compiler know what "term" and "next" means? Are those keywords or something else? How does it know that those are functions and not a and b?
#lang sicp(define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b))))(define (inc n) (+ n 1))(define (sum-cubes a b) (sum cube a inc b))(define (cube x) (* x x x))
Why not use this opportunity to learn how to use a debugger? Trace back through your code until you find the first point where something is 0 when it shouldn't be.
That, or check your gradient arrays. You declare them, but never set the values of the elements inside them. You should still learn how to debug though.
From what I remember it doesn't know until they are applied and then it looks up the symbol table or something.
Writing my own ransomware. Any tips? How much should I ask for ransom?
You should ask for the smallest banana in the world.
Just regular symbols, scheme has very few keywords. You should read the r5rs standard, it's like 50 pages long.
At compile time, it doesn't. Scheme is dynamically typed, which means that the type of value in bindings isn't fixed (static). So, the compiler/interpreter keeps track of what type of value things are, probably using tagged pointers, then does runtime checks to make sure the type is what is expected. This means that (in a naive implementation) the code will do type checks at every function call, and error if the value isn't a function.
how do I receive it anonymously? pretty sure a PO box you need id. can you have like fedEx deliver to like
?
You could tell them to place it in a supermarket where they keep bananas.
Then if they bust you when you pick it up.
I'm going to look into this. I am a decent python programmer but have no experience with gui i am willing to help
I'm doing one of those code challenge sites and it's genuinely challenging.
Link pls, bored as fuck.
Just pirate it and drop it on a Windows VM/machine (doesn't run on Wine). It's the best piece of software Microsoft has written after the Office suite.
Really, it's that much better than Eclipse. Also code will work just fine under Mono (or you can compile with Mono too).
Nigga, there's a free-as-in-beer version.
the site is hacker rank the challenge I was doing is in bit manipulation in the algorithm category.
Was the one giving me trouble.
How can I get this to write the actual day from the 'day' list, then go back to Monday once it's done Sunday?
modulo
Change "range(1, 43)" on line 9 to "range(0, 43) to start list from Monday. If you leave 1 then it starts from Tuesday.
Insert "x=x%len(day)" between lines 9 and 10 to make it "go back to Monday after Sunday".
% is called modulo operator, it returns remainder of division.
I believe he wants to put x%len(day) inside the [].
Is there a canonical text on X11 programming? I'm not just looking for the basics — I want to understand how it works and hook into other programs' text input in particular, so "just use GTK lol" is not an answer.
If any of you here are learning or have already managed to into programming to a decent extent, how do you remain motivated and productive, what's your system? I've poked at C and Lua and had no major issues making some small programs, I find it enjoyable in these little self contained packages but I don't really get enough of a buzz out of it at the end to create a sustained interest or passion in programming. I can see things I'd like to do if I became proficient, but a system for learning is more important than an end goal and at the moment I have no system.
Better question, why do you want to make a bunch of things you won't use? If you want to make something, just do it. You'll learn along the way. There's no need to make things you'll never use just to "get more proficient". All that will do is kill your interest.
How's my style, Holla Forums?
#include int main( int, char**);intmain( int argc, char** argv ) { for( int i=1; i
you're the most productive programmer I've ever seen! I want you on my team and I want to see the other managers' jaws drop when they see the kLOC spike in productivity.
however, after studying your code I'm somewhat disappointed:
1. why don't you put the return on a separate line from the '0;'? too much javascript?
2. why don't you put "Fizz" across four lines with four string literals? Don't you know that "a" "b" is compiled as "ab" ?
top post
simple text based game in lisp
if(
!(
i%3 && i%5
)
)
what the fuck is this shit?
put the conditionals of the if in a single line if they're that short you unbelievable cunt
*autistic crouching*
my team's trying to make a survey page with that'll dynamically pull questions from a database. each question is going to be one of 7 different types. we want to be able to count up the scores on each type and store it in the database when they complete it. any idea on how we can do this? the front end guys got it where it pulls the questions and it looks really pretty on the webpage and we have no idea how to do anything with it
Are you retarded? Write something to handle the answers at whatever url the frontend guys made the submit button target. I'm not sure what you want help with without sharing more information.
I'm implementing Conway's Game of Life as a console program in Java CS101 wew and after reimplementing it a couple different times in different ways I still end up with the same problem, leading me to believe something is just wrong with me.
I don't want someone to spoonfeed or do my homework for me, because I'm having a good time learning, but I am curious if this is a common or solved problem, so:
My board is a char[][] 2D array, and as I loop through each position I check all of its neighbors for aliveness in order to step the game forward using the rules.
The recurring problem: For some reason, when checking all the neighbors for a given space, any neighbor that has already been checked is seen as a dead space and not counted.
I've got no idea why. I'm operating on a copy of the board, because I was warned multiple times about fucking up by changing the pieces in-place (durr) so it shouldn't be that, but I'm stumped.
Is this a common thing to run into or should I show my doubtlessly shit code?
Today I just started writing an OS in C. All I've done so far, though, is a minimal kernel that loads the hardware and then goes into an infinite loop.
Sadly I couldn't get much actual work done yet because the target hardware is a TI calculator, and getting everything set up in SDCC (it's a C compiler that supports z80 architecture, which the calculator uses) took a while.
Not to mention the fact that the way the hardware is set up is fucking retarded. Certain ports and chips on the calculator refuse to work unless under certain conditions, and the OS needs to be signed with a 512 bit RSA key and some other problems.
Eventually, though, I hope to get as close as possible to being POSIX compliant, even thought it might not be possible.
No you messed up somewhere. Now is a good time to learn debugging.
Show code.
zerobin.net
I'm using the Eclipse debugger for the first time now. Holy shit I never knew you could see inside everything like this. Thanks user. This is gonna solve it if I can manage to spot exactly when everything goes wrong.
Clarify what you mean
The problem is that you're using System.arraycopy on a 2D array. In Java, a 2D array is an array of arrays. When you do arraycopy, Java duplicates the contents of the first array, but not the contents of the subarrays. What this means is that nextboard is an array of arrays (like board), but because you only duplicated the topmost array, nextboard is using the exact same subarrays as board (look up the difference between deep copy and shallow copy for more information about how this works). Because of this, when you change a value in nextboard, you're changing that value in board as well. This is why your program is producing incorrect results.
You can fix this by making a deep copy of the subarrays. However, you don't even need to do this. Since nextboard's contents are determined by checking board's contents, you don't need to initialize nextboard to be a copy of board. You'll be changing the contents anyway, so why waste time making a copy of you're going to throw it away? Simply removing the line where you arraycopy should fix your bug.
Shit, user, you're right, removing that line immediately fixes everything. So because my board is an array of arrays, arraycopy just copied the top level one which itself contained references to each of the existing subarrays, instead of making separate copies of each, and that's why board was being altered by changes to newboard. Correct?
Looking up deep copy and shallow copy now.
I have no idea now why I left in initializing it with a copy of board. I'm renewing my commitment to consciously asking myself if every line is totally necessary from now on.
Thanks, user.
Have you heard of rubber duck debugging?
en.wikipedia.org
Correct. Deep and Shallow copying becomes important whenever you're using data structures with multiple layers of indirection. When you're using such a structure, ask yourself if creating deep or shallow copies makes more sense for the way you want to use it.
The Java debugger is one of the best features of the JVM; why aren't you using it?
I'm guessing that you received a NullPointerException on the event object, since the only change was moving member access behind a few more conditionals.
I've been using AutoHotkey a lot lately. It's the poorest designed programming language I've ever encountered, but it's too useful not to use if you're a Windope like me. Here's a snippet of the Starcraft II automation tool I'm developing:
class Starbot_Config { static NULLVAL := "ERROR" static KEY_0X := "0X" static KEY_0Y := "0Y" static KEY_1X := "1X" static KEY_1Y := "1Y" __New(_iniFile) { this.iniFile := _iniFile } GetRect(section) { _0x := this._getNonNull(section, this.KEY_0X) _0y := this._getNonNull(section, this.KEY_0Y) _1x := this._getNonNull(section, this.KEY_1X) _1y := this._getNonNull(section, this.KEY_1Y) return new Starbot_Rect(new Starbot_Point(_0x, _0y), new Starbot_Point(_1x, _1y)) } SetRect(section, rect) { IniWrite, % rect.topLeft.x, % this.iniFile, % section, % this.KEY_0X IniWrite, % rect.topLeft.y, % this.iniFile, % section, % this.KEY_0Y IniWrite, % rect.bottomRight.x, % this.iniFile, % section, % this.KEY_1X IniWrite, % rect.bottomRight.y, % this.iniFile, % section, % this.KEY_1Y } _getNonNull(section, key) { IniRead, _retval, % this.iniFile, % section, % key, % this.NULLVAL if (_retval = this.NULLVAL) { throw "INI value missing for """ . section . "." . key . """" } return _retval }}
Do you still have a proper Conway game now? If you only have one board (array) that you are updating as you go you are doing exactly what your prof warned against.
Why not have two board that alternate being the "latest" board. Read board A, and write cells to B, then Read B and write to A.
No, he was creating a new empty board and then initializing it with the contents of the original board, which leaked references and led to the issue, before overwriting it with rule check results.
Now he's just creating the empty newboard array before filling it in according to the rule checks.
which editor/theme is that?
// we have a global volume handle for use by our direct write callsHANDLE hVolHandle = INVALID_HANDLE_VALUE; BOOL FlushCache(){ // close th volume handle if it is currently open so we can reopen it with MAGIC! if (hVolHandle != INVALID_HANDLE_VALUE) { CloseHandle(hVolHandle); hVolHandle = INVALID_HANDLE_VALUE; } // Notice the FILE_SHARE_READ without FILE_SHARE_WRITE... you can't open a volume handle for exclusive write... HANDLE hFile = CreateFile(m_szVolumeName, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); // this is really all we need, allegedly if (hFile != INVALID_HANDLE_VALUE) { //we should never be able to open a volume this way, but if we somehow did, we need to close that funky handle CloseHandle(hFile); } else { DWORD le = GetLastError(); // if we failed for any reason other than a sharing violation or access denied, then it didn't work if (le != ERROR_SHARING_VIOLATION && le != ERROR_ACCESS_DENIED) { return FALSE; } } if (hVolHandle == INVALID_HANDLE_VALUE) { // reopen the handle with normal permissions if( (hVolHandle = CreateFileW(m_szVolumeName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING, NULL)) == INVALID_HANDLE_VALUE ) { return FALSE; } } return TRUE;}
Fucking CIA niggers
Why can't there by a language that allows control flow changes as easily as variable changes?
for(;;) doX;vs.for(;;);doX;
What do you mean by this? Could you explain it in a bit more detail, please?
Like this kind of thing.
void A( array[][] ){ int val = 0; for each row in array{ for each col in row{ val++; } }}void B( array[][] ){ int val = 0; for each row in array{ for each col in row{ } val++; }}void C( array[][] ){ int val = 0; for each row in array{ for each col in row{ } } val++;}
Seems to me that these are considered different enough that you are supposed to write separate functions. And most of the time I have no problem with this. But usually when I get to writing variations or tweaks of functions I find myself writing ridiculous code.
For a real world example imagine you are drawing a square and you want to change the color you are drawing a) once per pixel, b) once per line c) once per shape.
So that's 3 square drawing functions.
Only solution I've ever come up with is to pass a bunch of stuff like
void A(once_per_pixel, once_per_line){for each row in array{ for each col in row{ if(once_per_pixel) val++; } if(once_per_line) val++; }}
But idk it seems like mess.
Your problem can be solved using predicate functions.
A predicate is a function that takes a parameter and returns a boolean based on the parameter. For example, boolean isOdd(int) is a predicate on an int and may be implemented as:
boolean isOdd(int number){ return number % 2 == 1;}
This predicate will return true only if the the provided number is odd. Similar predicates can be written for other types.
In Java 8 'Predicate' is an interface and the method boolean test(T) is used to check whether the provided predicate is true for a particular input:
Predicate myIsOdd = ClassName::isOdd; // ClassName should be the name of the class that you are getting the predicate from. It is not legal to write myIsOdd = isOdd; even if the function isOdd is in the same class.
System.out.println(myIsOdd.test(3)); // Prints true
System.out.println(myIsOdd.test(2)); // Prints false
To change your example slightly (I believe this is easier to understand, I'll redo your example afterwards), if we wanted to decide based on the color we may do something like this (in Java 8):
void A(Color[][] array, Predicate colorIt){ for (Color[] cArray : array) // This is the 'for each loop' notation, and is a shorthand for for(int i = 0; i < array.length; i++) {Color[] cArray = array[i]; [... your code here ...]} { for (Color currentColor : cArray) { if (colorIt.test(currentColor)) { // Do whatever we're doing with the color here } } }}// Calling the function A to only act on blue items in the array:A(myArray, ClassName::isBlue);
Just know that the above implementation is not how we would actually write such a function. In reality we wouldn't write this function at all. We would set up a Stream of colors and filter and map over the Stream rather than do this in an imperitive style.
You may be able to imagine that you'd be writing a lot of these types of functions with small parts changed. The changes you're thinking of have been generalised into map, reduce, filter, and other functions. For more on this I would recommend just about any talk by Venkat Subramaniam.
Now we get to your square drawing problem.
Note that function C doesn't do anything with val because it is set after everything has executed and val isn't static so I won't be discussing C here.
Fortunately, your problem is only a little more difficult than the above example, and you'll see we can still use predicates but in a slightly different manner.
Using your last example:
void A(array, predicate){ for each row in array{ for each col in row{ if(predicate) val++; } }}
If we use this method and our predicate was:
"once per pixel" - val would increase every time
"once a line" - val would increase by the number of lines
So how do we actually make these predicates?
There are two ways:
Make a predicate that takes the size of the line we're working on, and our current position in the array
Or make a predicate that takes our current position.
In the second case the size of the array is built into the function (this works in Java, I don't know about C or other languages):
Predicate makeEndOfLinePredicate(Color[][] array){ return (i) -> { return i == array[0].length; }; // Look up clojures and lambdas if you want to know more about this kind of thing. I don't have the time to explain this but I don't want you to walk away from this thinking the only option is to pass the value in each time // We're also ignoring null/boundary checks for simplicity. }
You invoke that function by using
Predicate pred = makeEndOfLinePredicate(myArray);NOTPredicate pred = ClassName::makeEndOfLinePredicate(myArray);This function returns a predicate, and is not the predicate itself.
For completeness, "once per pixel" would be return true every time because we always want to increment the val:
boolean oncePerPixel(int number){ return true;}
To create a predicate like interface in, for example, C we would use pointers to functions and call them in much the same way as we do here.
Does that answer your question?
can you guys explain me polymorphism?
why would i use the same name to do different things? seems confusing to me
you dont need to know about it; OOP is cancer
Thanks. I'll definitely have to think about this some more but for now I just went with passing an option and using the if(option == PER_PIXEL) val++ format.
It's not the worst and it is probably more readable than the abstractions I was imagining.
It's about defining common properties of object types. I'll talk about two different types of polymorphism. Interfaces and Inheritance.
Interfaces:
An interface is basically a promise that you make saying "Any object that implements this interface can do certain things". For example, you might create the interface "car" using this pseudocode:
interface car{ int get_mpg(int speed);}
What this means is that any object that implements "car" will always have a function called get_mpg(). The internals of get_mpg() however, are not defined in the interface. This means that different cars can calculate their mpg differently. You might have the following objects:
object prius implements car{ int get_mpg(int speed){ return speed * 0.5; }}object SUV implements car{ int get_mpg(int speed){ return speed * 0.01; }}
Why is this useful? Suppose you have lots of different types of cars. If you want to put them in a list and print out the mpgs. Without interfaces, you would need separate variables (one for each car type) and you would have to call their get_mpg functions like this:
prius carA = new prius();print carA.get_mpg();SUV carB = new SUV();print carB.get_mpg();//etc
This is because they are different objects and can't be treated the same way
With interfaces, you can do
list cars = //Fill it with prius, SUV, ferrari, whateverfor vehicle in cars{ print vehicle.get_mpg()}
Although a prius is a different object from an SUV, they both implement car, so they can be stored in an array of cars.
(cont)
Inheritance:
Inheritance allows you to define an object, and have another object be treated like that original object, even though it may do other things as well.
Suppose we have the following object:
[class]object bird{
void eat(int seeds, int meat){
//code to eat seeds goes here
//does not eat meat
}
int get_num_legs(){
return 2;
}
}[/code]
We want to make an eagle now. Since an eagle is just a more specific kind of bird, it doesn't make sense to rewrite all of our bird code. Inheritance lets eagle copy bird, while allowing us to change the internals of how it works or add new things. We can do the following
object eagle inherits bird{ void attack_children(int num_children){ //code to attack children goes here } void eat(int seeds, int meat){ //Eagle only eats meat. No seeds }}
Eagle has inherited from bird. That means that you can put an eagle into an array of birds, and you can treat an eagle like a bird (ie, we can call eat() on both an eagle and a bird). The following would therefore be valid code:
list tree;tree.add(new bird());eagle bald = new eagle();bald.attack_children(15);tree.add(bald);for bird in tree{ bird.eat(5, 4); print bird.get_num_legs()}
You'll note that although we changed the code for the eagle's eat function, we can still treat it like a bird. You'll also notice that nowhere did I write the eagle's get_num_legs function. This is because when you inherit from an object, you inherit all its functions and properties. Unless you explicitly redefine them, they are the exact same as the object from which you inherited. This allows you to save time by not having to rewrite common functions for similar objects.
Sorry for the shit explanations. I'm bad at explaining how things work over text.
So Holla Forums. I'm working on this project. Its a simple script image tagging system. Basically, you have your one fuckhueg folder full of unsorted pictures. When you add a tag to a picture, it makes a folder with the name of that tag if it doesn't already exist, then adds a symlink pointing to the pic in that folder.
I want to make a script that lets you search for images with multiple tags. It would look into multiple folders, compare whats inside, and output any filenames found in all specified tags. There are several utilities for comparing lists, but I'm having trouble getting useful results.
Any ideas? Suggestions? Am I retarded?
Is this a bash script? Try something like
uniq -c $all_lists_combined | grep $number_of_tags
uniq -c will take all items in a list, output all unique entries with the number of times it occurred in the list. You can then grep the output to find which images appeared N times where N is the number of tags you searched for.
I'm writing this on my phone while looking at the man page for uniq, so take what I say with a grain of salt.
Hey /dpt/
I'd like some help to understand how to write programs in the functional style. My initial attempts have been mostly imperative with a sprinkling of functional idioms.
If anyone has a moment to spare, I would really appreciate it if you could review this F# code and let me know how I can rewrite it to be more idiomatic:
Thank you in advance
As an addendum, you will need to use the sort command to sort the list you pass into uniq. It doesn't detect duplicate lines if they're not consecutive.
Thanks for the info. I'm going to run along and see if that works for me. It sounds like it will.
Please post your OS and what scripts you have developed so far. Would you want twenty tags on an image to create twenty folders for each category, and what about a folder for each unique combination of tags? Perhaps you should use a local webpage that can apply a filter and return results from the directory... a locally hosted Gelbooru
I don't know why I'm responding to a known cancerous namefag like you
OS: Gentoo
I can post the scripts I've developed so far, they're pretty basic. I've never been very good at programming. It took me three hours to write these two scripts. I call this tagging suite I'm working on, "SackyTag" I even made a ShitHub for it.
github.com
I think you're overthinking it. This is a simple textpunk image tagging system for shitposters. If you wanted a locally hosted webpage, it would just be an index of the search results folder. Check out the scripts and readme on ShitHub.
It took me an embarrassing amount of time to get these two tiny scripts written.
I don't know why I'm responding to a known cancerous namefag like you
OS: Gentoo
I can post the scripts I've developed so far, they're pretty basic. I've never been very good at programming. It took me three hours to write these two scripts. I call this tagging suite I'm working on, "SackyTag" I even made a ShitHub for it.
https:/ /github.com/SpaceBudokan/SackyTag
I think you're overthinking it. This is a simple textpunk image tagging system for shitposters. If you wanted a locally hosted webpage, it would just be an index of the search results folder. Check out the scripts and readme on ShitHub.
It took me an embarrassing amount of time to get these two tiny scripts written.
A Tox chat bot with RaTox and Ruby.
I autismed all over a white board at my college trying to work out how to do compiled callable dynamic types for a programming language I'm trying to make (so far I only have the tokeniser and AST done).
working on a minecraft mod using ava and gradlew.
I'm working on Excel VBA code for editing existing entries on sales tracking sheets. They like to lock everything down and have it handled by Userforms so retarded normies don't blow away half the sheet all the time.
Now personally I think Excel VBA is retarded, but it beats my old job, and they're paying me $15 more per hour to do this and I get to work from home so fuck it.
retarded
Java is a solid, robust, and versatile language. The problem with it is it can be a bit slower to work with. Also designing UIs for Java is fucking cancer. For the record, I actually started with Java, but I had a lot of other computer and math/logic experience, so my only major sour points were UI and JSP related.
For that reason I suggest Python: it has a mountain of support in the form of libraries, learning material, and the community (just like Java) but it's easier and faster to get shit from start to finish. It's a good prototyping language, and for some reason it also has some of the best data science libraries around (which is what I use it for when I can't be assed to fuck with R). One thing to beware with Python: material written by newfag programmers. Plenty of hipsters/SJWs trying to break into coding by reading a Python tutorial spew ridiculous amounts of misinformation. Try to sort out the bullshit, but if you're not sure about something, ask here.
lol you can tell this guy doesn't work anywhere near an enterprise situation. Also Android is the most popular phone OS... just saying.
This is why I got my amateur radio license. I don't use it much, but I hike/canoe out of cell range a few times a year, and even a lightweight radio setup can get some pretty serious range. I also live on top of a hill and being able to hear/talk to nearly every repeater in town with 1 watt on the 2 meter band is amazing. Also my callsign (which you keep for life) ends in BFG. I won't lie, that's about 25% of the reason I even got an amateur cert...
I like strategic planning, I like solving problems, and I like organizing shit. Programming fit all 3 and required a fraction of the time to learn compared to any of the other job ideas I had. Now I make decent money and I can throw together scripts and shit to improve my own quality of life whenever I get bored. It's been pretty sweet, much better than I expected.
Just don't do it if you don't like sitting down all day, because you'll be on your ass for 7-8 hours a day at least. I work from home and I still find it annoying to sit for that long (though it got me working out to burn energy off so that's good). If that's not your jam, keep it as a hobby or do something else.
Is someone willing to help compile something for me? I'm trying to get ScripthookDotNET working on FiveM/FiveReborn because those faggots blocked it, but I think I know how to unblock it.
Pic related is what i've been trying to achieve, but when I try to compile it it gives me a msb3644 error, and I don't know shit about programming aside from this.
Well shit, I got it working, but I still can't compile it.
I started my first (proper) project a couple days ago, a program which grabs csv-formatted data on a given ticker symbol (from yahoo finance) and will eventually give you graphs of variance, stddev, calculate returns etc. I couldn't find anything terminal based that did that so I started my own.
Right now it prints to stdout because I was thinking of making it really unix-y but as far as I can tell that can make modifying existing files pretty complex and I don't want to use tempfiles to produce properly formatted data fields.
here's the source:#include #include #include #include typedef struct stock_symbol { char *symbol; float ask, bid, open, close, low_24, high_24, low_52, high_52, change, pc_change, div_yield, div_per_share;} Stock;/* char * *//* create_file(char *symbol) *//* { *//* char *filename; *//* sprintf(filename, "%s_%u", symbol, (unsigned) time(NULL)); *//* fclose(fopen(filename, "w")); /\* to avoid ghost fopen()s *\/ *//* return filename; *//* } */voidcb1(void *s, size_t len, void *p){ printf("%s\n", s);}intmain(int argc, char *argv[]){ CURL *curl; FILE *fp, *csv; struct tm *tm; struct csv_parser p; char buf[1024], date[18], csv_url[80], filename[32]; size_t bytes_read; time_t t; Stock stock; time(&t); tm = localtime(&t); if (argc != 2) return -1; stock.symbol = argv[1]; /* struct stock symbol is reusable and obvious */ sprintf(csv_url, "download.finance.yahoo.com
Any advice would be well appreciated.
also ignore some of that code, it's unused or pretty bad because I just want to get some core functionality working.
HEY FAGGOTS
where else do you guys hangout? anyone on the IRC? looking for live programming talk and pals
Telegram, mostly LainChan general chat.
Cloning Candid, don't need any SJW Ai going against muh anonymity
thank you user-san
How's your progress so far user?
Pretty good, just need some money to host it. It would cost a shit ton and I don't think that anyone would use it. Once I get the API functional I plan on releasing it as free software.
Doing memory checking on a C program with valgrind. From what I've read, it is pointless to free memory allocated with malloc on exit because it will be returned to the heap anyway. So when valgrind prints something like this:
LEAK SUMMARY: definitely lost: 0 bytes in 0 blocks indirectly lost: 0 bytes in 0 blocks possibly lost: 0 bytes in 0 blocks still reachable: 643,518 bytes in 380 blocks suppressed: 0 bytes in 0 blocks
...am I okay? It shouldn't matter if it's still reachable at exit, right?
enjoy your fascist mod ban lol
the lainchan telegram chat is to be avoided
?
it's just a chat client, what channel or whatever do I need to be on?
That just means that there's 380 blocks of memory allocated when your program finishes and you still have the pointers to them. You're correct that it's basically pointless, but I find it helpful to list known memory blocks still allocated at the end of the program, either through free/delete calls, or just a comment. With free/delete and valgrind, you know when you have to update the known memory blocks list since it'll show up. If you don't care about that, then just leave it since it's fine.
Thanks!
I've been bored at work and doing shit on codewars.
I wrote a brainfuck interpreter in python. Then in javascript. I started doing it in C++, but got too annoyed.
I need a real project.
Make a replica of a game client in a game that you play. Must be completely headless, no graphical recreation (you can have a GUI to show things). Have to replicate the networking protocol and have the client join the game and interact with the world.
If you don't play a game... Find one then.
You know, I thought Powershell terrible on my first impression years ago, but after having had to use it to automate tasks for a retard (think, incapable of even checking the space remaining on a hard drive they have to back up to, or checking if a removable device is read-only because it wasn't plugged in properly), it's hands down the best thing Microsoft has done.
Not saying much, but I suppose I'm just thankful I didn't have to run Visual Studio or compile any AbstractBean .NET garbage to automate this piece of shit operating system.
Gonna try to finish a map generator by tonight, then work on my SFML vidya where all the characters are colored blobs while I search for a pixel artist.
Help me and a lot of others unfuck Scripthook.NET for FiveM/FiveReborn, I guess?
A website to show the leaderboards for a Xonotic server that Holla Forums hosts and plays on.
Sample link:
archive.fo
You're all welcome to play sometime.
>>>Holla Forums12078949
The most active days tend to be Fridays an Saturdays for them.
This user script might be helpful for Holla Forums users. It makes searching the catalog a bit easier.
// ==UserScript==// @name Holla Forums Catalog Search// @namespace 8ch.net
I wanted to practice with sockets and protocols, so I'm working on a CLI gopher client. You'd think that with such a simple protocol, that servers would actually follow it, but I can't even count on them to send the proper terminating sequence.
name = input('What is your name?\n')print('Hi, ', name, '.', sep = '')
That's some top notch code user. You should submit that as a PR to the Linux kernel.
print('Thank you very much!')
I wanna see how Linus would respond to that
He was pretty mad about that last drm pull request.
I'm sure that was all totally legitimate code
...
...
Moving my way slowly through Eloquent Javascript.
I reversed an array today :^)
...
I am currently learning Java as my first programming language, and if you understand math or think logically you'll have a relatively easy time. Just go for it!
So, I was briefly looking at the 'Marble' CIA code released by Wikileaks (wikileaks.org
int IScramble::CreateStringLiteralA(unsigned char *cBuffer, int iNumOfChars, char *&cOutput)
What are they doing with cOutput? Why are they making a pointer with & in a function declaration? Is this something in C++ which doesn't happen in C?
Don't you have a street to be shitting in?
Learning my way through Ansible 1.5 because I inherited a project at work from a bunch of Indians.
The code is a fucking mess, and I have to add a bunch of extra behavior. These goddamn idiots threw everything in a single file (A 5000-line file of all of the Ansible behavior, yes). I just read through the Ansible guide, and now I'm spending all my goddamn day splitting this 5000-line dogshit file into what it should have been in the first place. Fuck Javascript, fuck Ansible, and fuck Indian coders.
Even my Indian coworkers hate working with Indians, which is why they fucking left India.
& in a type declaration in C++ is a "reference", essentially an auto-dereferenced pointer. Basically, if you mentally turn the & into a *, and change every use of the variable into (*var), it works pretty much the same (with some weird semantics for assigning to a reference from various types).
//These are pretty much the sameint &foo(int &bar) { bar = 5; return bar;}int *foo(int *bar) { (*bar) = 5; return bar;}
It just means that you can pretend to pass and return things by-value while it's actually happening by-reference, with the semantics handled by the compiler.
So char *&cOuput means that it's a reference to a char pointer, so the pointer value itself can be changed and that will be externally visible. Reference-to-pointer is not a commonly-used paradigm, as you usually can do it in more expressive ways, and those kinds of pointers would usually be wrapped (so you would usually use a reference to some sort of container or stream instead, and use exceptions for error conditions, so you'd have no need to change the caller's passed-in pointer value. Even when you don't use exceptions, there are more expressive ways to do it). It is typically faster than those more expressive ways, so I'm guessing this is performance-intensive code, or largely internal code that is expected to be called by the actual API endpoints and further used before returning a value to the caller somehow.
Thank you, that makes sense.
HAHAAH OH WOW
It's largely true. You pass in "by-value" which gets converted to a reference type, but other than specific semantics for assigning between reference types (which I mentioned, and which includes function arguments), it's largely the same. To a large degree, they're pretty much safe pointers.
Check out the standard: open-std.org
Section 8.3.2 clarifies semantics for reference declaration and assignment. 8.6.3 clarifies reference initialization. I know references don't necessarily require storage, where pointers do, but every ABI I've ever seen stores a reference passed into a function call as a pointer, and operates on it as such. Given that references can dangle and refer to out-of-scope objects, a pointer is a much more useful analogy than thinking of it as a strict alias.
How else would you explain it to somebody who is familiar with C but not C++?
Started my first C++ project and I've already ran into a problem I can't solve myself.
Both of these work correctly, so the font does support unicode characters and myString is also fine:
text.setString(L"á");std::cout
Started my first C++ project using SFML and I've already ran into a problem I can't solve myself.
Both of these work correctly, so the font does support unicode characters and myString is also fine:
text.setString(L"á");std::cout
"L"
Alright Holla Forums I want to make a program that needs a GUI and manipulates audio and I only know C from one year of a CS class in uni, what language/libs should I learn to make this program? I hear Rust is cool but I don't want to write audio libraries from scratch.
Can you not just do this?
text = myString