Code snipets that you are actually proud of

Reply with snipets that you are actually proud of

>inb4 datamining

Other urls found in this thread:

en.wikipedia.org/wiki/Short-circuit_evaluation
glot.io/snippets/ef9lgxvy3a
twitter.com/NSFWRedditVideo

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;
}

01 PRINT "HELLO WORLD"

...

C++?

What did you think it was? Common Lisp?

Lisp?

BASIC

...

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.

...

static void Main()
{
while (true) Process.Start(Assembly.GetExecutingAssembly().Location);
}

02 GOTO 01

I'm unusually proud of my half-golfed code

02 GOTO "01"*

>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

I'd like to point out that there are situations where if (a && b) would error where if (a) if (b) would not

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

No it won't
en.wikipedia.org/wiki/Short-circuit_evaluation

then run the file cause it will remove botnet

Huh, it's nice to learn something new. Thanks user

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.

...

#include
#include
#include

float f_sqr(float n) {
int w = *(int*)(&n);
int e = ((w >> 23) & 0xFF) - 127;
int m = w & (8388607);
int x = ((((e

whats c good for?

everything

>*gasp*

nothing

something

anything

a couple of things

exactly tree fiddy things

/**
* 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;} } }

No, this is
(TAGBODY
10 (PRINT "HELLO WORLD")
20 (GO 10))

YES NO

...

MAYBE

SHAZBOT!

SO

I DON'T KNOW

C-C-C-

thanks senpai it worked :^)

forkbomb

please never get a job

don't do this, it installs gentoo

c is good for spelling 'cake' or 'carrot'


you could even go as wild as spelling 'cucumber' (notice the two Cs?)

U-U-U-

B-B-B-

>data != code

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 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.

If he's paid hourly and no one reviews his code then his is the best solution.

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.

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();

// 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 Sup Forums, im going to bed now, good night

what a hellish nightmare that snippet is

>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

Kek, that reminds me of this little snippet I made some months ago:
glot.io/snippets/ef9lgxvy3a

Fucking indian guy killed his own teacher because he stole some code from him.

I honestly have no idea but i'm really interested to know why that snippet would be better.

if(cond) func();

Panties drop every time I dole out them if-one-liners.

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 );
}
}

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.

I mean, what other functions are there?

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).

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.

My pleasure.

>cannot find symbol:
>setLocation("street");

Kek

produceNewUnderperformingGPU( float moneyToBurn );

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.

...

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

>bool primeCheckUgly
well, at least it knows what it is

>iTunes
>Memecraft
>Skype
>Utorrent
>Google Botnet
Kill yourself my man

NEETs

Wow that was [b] ENTERPRISE QUALITY [/b] post

## 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

>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

My arbitrary integer averaging function, with no overflow or widening to other types:
#include

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;
}

...

that is so disgusting. this is why I only stick to php, at least that won't visually rape me.

...

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.

>visual studio

>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

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 $TEMP
mv $TEMP $OUTFILE
done
join -a1 -t \# $OUTFILE $TEMP
sort -k1,1 -k2,2n $TEMP > $OUTFILE
rm $TEMP

which editor is this?

HAMANA KABEESEI

vim

while (function(shitHappens(){
liveLife();
});

going fast

>if
>{
>foo
>}
>and not
>if{
>foo
>}
>proud

...

This is a snippet from 3dClustSim, one of the most commonly used software for fMRI data processing.

In case Sup Forums 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.

*That comment at the very end is also an actual comment in the code.

learning electronics

my fucking sides

...

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