Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Every time you visit for the FIRST TIME today... [Part 1]

Name: Anonymous 2013-10-20 22:56

Post a random function that you made. May be from any project you've done or make one impromptu.

Any QUALITY is allowed. No bullying!

Name: Anonymous 2013-10-20 23:02

I like this thread!

void receive_file(char *filename, int socket) {
FILE *data = fopen(filename, "w");
if (!data) {
printf("Could not open file %s for writing.\n", filename);
return;
}

/* Receive file in chunks of n bytes */
int n = 1024;
int offset = 0, received = 0;
while ((received = recv(socket, data + offset, n, 0)) > 0
|| (received == -1 && errno == EINTR) ) {
if (received > 0) {
offset += received;
n -= received;
}
}

printf("Received file %s succesfully.\n", filename);
}


I haven't even tested it.

Name: >>2 2013-10-20 23:03

Wow, I don't even close the file. Shame on me.

Name: Anonymous 2013-10-20 23:16

Eat some entry-level sorting algorithm I wrote for as a homework when I was 14

void selection(int a[], int l, int r)
{
int i, j;
for (i = l; i < r; i++) {
int min = i;
for (j = i + 1; j <= r; j++)
if (a[j] < a[min])
min = j;
swap(&a[i], &a[min]);
}
}

Name: Anonymous 2013-10-20 23:35

>>4
You had programming classes in middle school? Living in a first world country must be fun.

Have some fucking pointless FIOC

def sprunge(text):
text = text.encode('utf-8')
params = urllib.urlencode({'sprunge': text})
paste = urllib.urlopen('http://sprunge.us', params).read()
return paste.lstrip(' ')

Name: Anonymous 2013-10-21 2:54

This is something I made back for old /prog/. I'm sure it was already done by smarter people long ago, but this one is mine and I have a vague sense of pride for it. It was based on an observation that instead of repeatedly pushing both sides of a range down a stack to implement quicksort, only one side was needed.

void nonrec_qsort(int *data, const int o_from, const int o_to, int *holding) {
int from = o_from, to = o_to;
stack *explicit_stack = make_stack();

while(true) {
if ((to - from) <= SUB_LIMIT) {
subsort(data, from, to);

if (to == o_to) {
free_stack(explicit_stack);
return;
}

from = to + 1;
to = pop(explicit_stack);
} else {
push(explicit_stack, to);
to = partition(data, from, to);
}
}
}


And then a more explicit version that you can run and shit.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define LEN 200
#define SUB_LIMIT 8

static void print_arr(const int *data, const int n)
{
int i;
printf("[%d", data[0]);
for (i = 1; i < n; ++i)
printf(", %d", data[i]);
printf("]\n");
}

/* explicit stack */
static int *explicit_stack;
static int stacklen = 0, stackpos = 0;

static void push(int i)
{
if (stackpos >= stacklen) {
stacklen *= 2;
explicit_stack = realloc(explicit_stack, stacklen * sizeof (int));
}
explicit_stack[stackpos++] = i;
}

static int pop(){
if (stackpos >= 0)
return explicit_stack[--stackpos];
return -1;
}
/* explicit stack */

static void subsort(int *data, int from, int to)
{
int *curr, temp_val, *temp, *min;

if (from < 0) from = 0;
if (to >= LEN) to = LEN - 1;
if (from >= to) return;

for (curr = data + from; curr <= data + to; ++curr) {
for (min = curr, temp = min + 1; temp <= data + to; ++temp)
if (*temp < *min)
min = temp;

temp_val = *curr;
*curr = *min;
*min = temp_val;
}
}

static int mid(const int a, const int b, const int c)
{
if (a < b)
return (b < c) ? b : c;
return (a < c) ? a : c;
}

void nonrec_qsort(int *data, const int o_from, const int o_to, int *holding) {
int midval, *lside, *rside, *curr, from, to;
from = o_from;
to = o_to;

i_bet_youd_rather_i_used_while_well_fuck_YOU:
if ((to - from) <= SUB_LIMIT) {
/* if set is small enough, use an n^2 sort */
subsort(data, from, to);

/* qsort always ends with subsorting the last sub-interval */
if (to == o_to) {
return;
}

from = to + 1;
to = pop();
} else {
/* partition and resize to leftmost side, storing rightmost index */
lside = holding + from;
rside = holding + to;
curr = data + from;

midval = mid(data[(from + to)/2], data[from], data[to]);

while (curr <= data + to) {
if (*curr < midval)
*lside++ = *curr;
else if (*curr > midval)
*rside-- = *curr;
curr++;
}

/* all values >, < midval have been taken care of, = must now be handled */
for (curr = lside; curr <= rside; ++curr)
*curr = midval;

memcpy(data + from, holding + from, (to - from + 1) * sizeof(int));

push(to);
to = curr - holding - 1;
}
goto i_bet_youd_rather_i_used_while_well_fuck_YOU;
}

int main()
{
int i, *data_to_sort, *holding;

/* this should be set up inside nonrec_qsort, but here for clarity */
stacklen = 1;
explicit_stack = (int *)calloc(stacklen, sizeof(int));

data_to_sort = (int *)calloc(LEN, sizeof(int));
holding = (int *)calloc(LEN, sizeof(int));

srand(time(NULL));
for (i = 0; i < LEN; ++i)
data_to_sort[i] = (rand() % 900) + 100;

print_arr(data_to_sort, LEN);
nonrec_qsort(data_to_sort, 0, LEN - 1, holding);
print_arr(data_to_sort, LEN);

free(data_to_sort);
free(holding);
free(explicit_stack);
return 0;
}

Name: Anonymous 2013-10-21 6:31

function j() {
iframe = document.createElement('IFRAME');
while (true) {
document.appendChild(iframe)
}
return null;
}

Name: Anonymous 2013-10-21 7:02

Some random reference shit (I think I wrote) in my programming folder.


#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

void *thread_func(void *);
pthread_t make_thread(int64_t);
void critical_error(const char *);

pthread_mutex_t t_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t t_cond = PTHREAD_COND_INITIALIZER;

int tindex = 0;
int *thread_order = NULL;

int main(int argc, char **argv){

pthread_t *tid;
int nthreads;

if (argc != 2)
critical_error("Usage: ./a.out [#threads]");

nthreads = atoi(argv[1]);

if (nthreads < 1 || nthreads > 128)
critical_error("Keep the number of threads between 1 and 128");

thread_order = calloc(nthreads, sizeof(int));
tid = calloc(nthreads, sizeof(pthread_t));

printf("(Main) Creating %d Threads...\n", nthreads);
for (int i = 0; i < nthreads; ++i){
tid[i] = make_thread(i+1);
printf("(Main) Thread %d Created\n", i+1);
}

printf("(Main) Sleeping 2 seconds...\n");
sleep(2);

for (int i = 0; i < nthreads; ++i){
printf("(Main) Lock Mutex\n");
pthread_mutex_lock(&t_mutex);
printf("(Main) Lock Sucessful\n");
printf("(Main) Sending Signal\n");
pthread_cond_signal(&t_cond);
printf("(Main) Signal Sent\n");
pthread_mutex_unlock(&t_mutex);
printf("(Main) Mutex Unlocked\n");
printf("(Main) Join thread %d\n", thread_order[i]+1);
pthread_join(tid[thread_order[i]], NULL);
printf("(Main) Join Successful\n");
}

return 0;
}

void *thread_func(void *num){
int tnum = (int64_t) num;
printf("(Thread %d) Lock Mutex\n", tnum);
pthread_mutex_lock(&t_mutex);
thread_order[tindex++] = tnum-1;
printf("(Thread %d) Lock Successful\n", tnum);
printf("(Thread %d) Calling Wait on Mutex\n", tnum);
pthread_cond_wait(&t_cond, &t_mutex);
printf("(Thread %d) Signal Received\n", tnum);
pthread_mutex_unlock(&t_mutex);
printf("(Thread %d) Mutex Unlocked\n", tnum);
return NULL;
}

pthread_t make_thread(int64_t num){
pthread_t tid;
pthread_create(&tid, NULL, &thread_func, (void *) num);
return tid;
}

void critical_error(const char *err){
fprintf(stderr, "%s\n", err);
exit(EXIT_FAILURE);
}

Name: Anonymous 2013-10-21 7:28

Do I really need to do this?

void printhello() {
printf("hello.");
}

Name: Anonymous 2013-10-21 12:40

$ cat genmac.py
#!/usr/bin/env python
mac = map(lambda c:ord(c), open('/dev/urandom','r').read(6))
mac[0] &= ~1
print ":".join(map(lambda x:"%02x"%x,mac))

Name: Anonymous 2013-10-21 15:18

def pkcs7unpad(el_blocko):
lastchrvalue = el_blocko[-1]
if lastchrvalue > 15:
return el_blocko
if el_blocko[-lastchrvalue:] == bytes([lastchrvalue] * lastchrvalue):
try:
return pkcs7unpad(el_blocko[:-lastchrvalue])
except ValueError:
return el_blocko[:-lastchrvalue]
else:
raise ValueError('Not valid PKCS#7 padding.')


this one makes me feel dirty and i don't even know why

Name: Anonymous 2013-10-21 19:05


void Timer::Stop()
{
enabled = false;
stopEvent.Set();
}

Name: Anonymous 2013-10-21 21:02

function recparse(depth:Int):NodeList {
var nodes = [];
while (!stream.isEmpty()) {
var text = stream.pop();
switch (text) {
case "\\":
var tagName = "";
while (~/[a-z]/.match(stream.first()))
tagName += stream.pop();
var args = new Array<NodeList>();
while (expect("{")) {
stream.pop(); // Consume left bracket
args.push(recparse(depth + 1));
}
if (tagName == "") {
for (arg in args)
for (argnode in arg)
nodes.push(argnode);
} else {
nodes.push(Tag(tagName, args));
}
case "}":
if (depth > 1)
return nodes;
else
throw "Too many right braces";
case "{":
for (node in recparse(depth + 1))
nodes.push(node);
default:
while (nonspecial())
text += stream.pop();
nodes.push(Text(text));
}
}
if (depth > 1)
throw "Too many left braces";
else
return nodes;
}

Name: JAVA4EVER 2013-10-22 0:30

A lazy iterator for finding permutations. Needs Google Guava to run.


package problems;

import static java.util.Arrays.asList;

import java.util.Iterator;
import java.util.List;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public class ProblemPERM {

public static class SingleIterable<T> implements Iterable<T> {
private final T value;

public SingleIterable(T value) {
this.value = value;
}

@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
boolean done = false;

@Override
public boolean hasNext() {
return !done;
}

@Override
public T next() {
done = true;
return value;
}

@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}

public static <T> SingleIterable<T> single(T value) {
return new SingleIterable<T>(value);
}

public static class Permutation {
private Iterable<Integer> perm;

private Permutation() {
}

public Permutation(List<Integer> nums) {
perm = Lists.newArrayList(nums);
}

public Permutation generateFrom(int newValue, int pos) {
Permutation result = new Permutation();
result.perm = Iterables.concat(Iterables.limit(perm, pos), single(newValue),
Iterables.skip(perm, pos));
return result;
}

@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i : perm) {
result.append(i).append(' ');
}
return result.toString();
}

public static final Permutation ONE = new Permutation(asList(1)),
FST_TWO = new Permutation(asList(1, 2)), SND_TWO = new Permutation(asList(2, 1));
}

public abstract static class PermutationIterator implements Iterator<Permutation> {

public static PermutationIterator getInstance(int N) {
switch (N) {
case 0:
throw new IllegalArgumentException();
case 1:
return new PermutationIterator() {
boolean notDone = true;

@Override
public void remove() {
throw new UnsupportedOperationException();
}

@Override
public Permutation next() {
notDone = false;
return Permutation.ONE;
}

@Override
public boolean hasNext() {
return notDone;
}
};
case 2:
return new PermutationIterator() {
int position = 0;

@Override
public void remove() {
throw new UnsupportedOperationException();
}

@Override
public Permutation next() {
switch (position++) {
case 0:
return Permutation.FST_TWO;
case 1:
return Permutation.SND_TWO;
default:
throw new IllegalStateException();
}
}

@Override
public boolean hasNext() {
return position < 2;
}
};
}
return new ConcretePermutationIterator(N, getInstance(N - 1));
}
}

public static class ConcretePermutationIterator extends PermutationIterator {

public final int N;
private final PermutationIterator recursive;

private int position = 0;
private Permutation subPerm;

private ConcretePermutationIterator(int N, PermutationIterator recursive) {
if (recursive.hasNext()) {
subPerm = recursive.next();
} else {
throw new IllegalStateException();
}
this.N = N;
this.recursive = recursive;
}

@Override
public boolean hasNext() {
return recursive.hasNext() || position < N;
}

@Override
public Permutation next() {
if (position == N) {
position = 0;
if (recursive.hasNext()) {
subPerm = recursive.next();
} else {
throw new IllegalStateException();
}
}
return subPerm.generateFrom(N, position++);
}

@Override
public void remove() {
throw new UnsupportedOperationException();
}

}

public static <T> Iterable<T> wrap(final Iterator<T> it) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
};
}

public static void main(String[] args) {
int num = 11;
Iterator<Permutation> perms = ConcretePermutationIterator.getInstance(num);

for (Permutation p : wrap(perms)) {
System.out.println(p);
}

}
}

Name: Anonymous 2013-10-22 9:46

[/code]int isprime(long long int n)
{
long long i, sqrt_n;

/* If even number */
if ((n % 2 == 0) || n <= 1)
return 0;

sqrt_n = sqrt(n);
/* Skip every 2nd number to avoid even numbers
to reduce the number of loops */
for (i = 3; i <= sqrt_n; i += 2) {
if (n % i == 0)
return 0;
}

return 1;
}[/code]

Name: Anonymous 2013-10-22 12:44

def checknums()
nums = getnums()
idx = @lastnums.length
if nums.length > idx then
sleep 5 # TODO -- Replace this with something that is not a hack
notify(nums[idx])
@lastnums = nums
end
rescue
nil
end

Name: abs(); 2013-10-22 15:05

>>15
if ((n % 2 == 0) || n <= 1)
return 0;
I guess 0 and other negative numbers count.

Name: Anonymous 2013-10-22 15:40


#include <math.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
const char melody_notes[] = "IQNNNN!!]]!Q!IWJWQNN??!!W]WQNNN?";
const double bass_notes[4] = { 3.0, 3.0, 4.75, 2.0 };
double a, d, m, b, drum, melody, bass, sample;
uint32_t t, w, v, p;
for (t = 0; ; t++) {
w = t >> 9;
v = w >> 7;
p = (w >> 5) & 0x03;
a = 1.0 - fmod(t / 2048.0, 1.0);
b = bass_notes[p] * t / 4.0;
d = a * fmod((14 * t * t) ^ t, 2048.0);
m = (melody_notes[((w >> 1) & 0x0F) | ((p / 3) << 4)] / 33.0 * t) - t;
bass = fmod(b * 0.98, 80.0) + fmod(b, 80.0);
drum = (((uint32_t)(fmod(5.0 * t, 2048.0) * a) & 128) * ((0x53232323 >> (w / 4)) & 1)) + (((uint32_t)d & 127) * ((0xA444C444 >> (w / 4)) & 1)) + ((uint32_t)(d * w) & 1);
melody = (fmod(m, 32.0) + fmod(m * 1.99, 32.0) + fmod(m * 0.49, 32.0) + fmod(m * 0.97, 32.0) - 64.0) * (4.0 - a - a - a);
sample = bass + (a * ((v ? drum : 0.0) + (v > 1 ? melody : 0.0)));
sample = (sample >= 0.0) ? sample : 0.0;
putchar(((uint32_t)(sample * sample) >> 14) ? 127 : (int)sample);
}
return 0;
}

Name: Anonymous 2013-10-22 16:11

#include <string.h>

static int replace_at_with(char *str, const size_t len, const char *target,
const size_t tlen, const char *replacement, int *err)
{
char buf[len];
size_t orig_len = strlen(str);

/* Length check, -1 for final \0 */
if (orig_len - tlen + strlen(replacement) - 1 >= len) {
*err = 1;
return 0;
}

/* Copy from the original until the target substring */
strlcpy(buf, str, target - (str - 1));
/* Now append replacement */
strcat(buf, replacement);
/* And copy the rest of the original */
strcat(buf, target + tlen - 1);
/* And back */
strcpy(str, buf);

*err = 0;
return strlen(buf) - orig_len;
}

Name: Anonymous 2013-10-22 21:13

>>17

As nonprimes. 0 is false, baka.

Name: Anonymous 2013-10-22 21:14


function findrepeating(string){ //string=starting string
var hash = {};
hash[string]=true;
var count = 0;
for (;;){
count +=1;
var t = [];
for (var i=0;i<string.length;i++){
var c0 = (i>0) ? string.charAt(i-1) : "0";
var c1 = string.charAt(i);
var c2 = (i<string.length-1) ? string.charAt(i+1) : "0";
var s = c0+c1+c2;
if (grammar[s]){
t.push(grammar[s]);
} else {
t.push(c1);
}
}
string = t.join("");
if (hash[string]){
break;
}
hash[string]=true;
}
return count;
}

Name: Anonymous 2013-10-22 22:04

>>21
That was Javashit quality!

Name: Anonymous 2013-10-22 22:56

Legacy code for Turbo C systems. Those were the days.

void graphtangent()
{
int i;
preparegraphicsmode();

/* Display message */
setcolor(WHITE);
settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 0);
outtext("sin (x)");

for (i = 0; i <= maxx; i++) {
double f = tan((i * M_PI) / 180.0);
putpixel(i, midy - (int) (f * 100), YELLOW);
delay(25);
}

getch();
restorecrtmode();
}

Name: int abs(int i); //dimwit 2013-10-22 23:24

>>20
Evaluate n = 0 on that statement:
if((true)|true)
Negatives:
if((false)|true)

Name: Anonymous 2013-10-23 0:41

>>24
Which would return 0 which means a false.

Name: Anonymous 2013-10-23 0:53

>>25
If the logic is inversed, 2 is not a prime.

Name: Anonymous 2013-10-23 1:20

>>26
Oh shit you're right. I didn't notice that.

Name: Anonymous 2013-10-23 4:08

word filter =)

function zmat = z1filter(imgmat, fmat)
shortstop = length(fmat);
simg = length(imgmat);
zmat = zeros(1, [simg - shortstop + 1]);
longstop = length(zmat) - 1;
for(iterX = 1:shortstop)
zmat = zmat .+ (imgmat(iterX:iterX + longstop(1)) == fmat(iterX));
endfor;
endfunction;

Name: Anonymous 2013-10-23 6:02

bool check_faggot(int post_number)
{
if(post_number == 1) return true;
else return false;
}


How to use:


post_number = 1;
printf(">>%d is ", post_number);
if(check_faggot(post_number) == 0)
{
printf("not ");
}
printf("a faggot.");

Name: ██████████ 2013-10-23 8:06

I'm new to Haskell.

ifM p x y = p >>= \p -> if p then x
else y

ifO p x = if p then x
else return ()


Also, sorry about the unaltered usage of 'p' in the first one.

Name: Anonymous 2013-10-23 10:58

mapLines f = unlines . map f . lines

Name: Anonymous 2013-10-24 0:29

>>18
This sounds interesting, but a sample of the output with `aplay -c 2 -f S16_LE -r 44100 /tmp/partial-output.txt' is unsettling to say the least. Any preferred options for output?

Name: Anonymous 2013-10-24 0:34

>>29
That was SEPPLES quality!

Name: Anonymous 2013-10-24 0:55

>>32
FIFO or tmpfs, your choice.

Name: Anonymous 2013-10-24 12:38

int main = 5;

Name: $ !8NBuQ4l6uQ 2013-10-24 16:33

>>35
const int main[]={3048,2425393152,printf,2122789,99516766,85<<24,3109479817,30,1346420785,3092271440,12,2337337345,2525756533,8,3296973567,4098198280,4165272400,1492403593,1509442953,3531935561,2214592511,3093105860,1337,2425393347};

Name: Anonymous 2013-10-24 18:54


ifelse food-ahead [ turn-left ] [ turn-right ] turn-right i
felse food-ahead [ move move ] [ turn-left ] move ifelse food-ahead [ turn-left
] [ turn-left ]

Name: Anonymous 2013-10-25 1:09


tic;

bigness = 20

x = rand(bigness) > rand(1);

fx = x;

oldfx = fx;

fx(:) = 0;

%figure(1); imshow(1-x); figure(2);

y = zeros(bigness + 2);

y(2:end-1, 2:end-1) = x;

zf = ones(3);

zf(2,2) = 10;

for(iter=1:200)

nextx = zfilter(y, zf);

%%rep = ((x==0) .+ (nextx==3)) == 2;

%%suv = ((x==1) .+ (nextx==2) .+ (nextx==3)) == 2;

%%x = rep .+ suv;

%%x = nextx==2;

x = (nextx==3) .+ (nextx==12) .+ (nextx==13);

y(:) = 0;

y(2:end-1, 2:end-1) = x;

if(mod(iter,5)==0)

xdiff = sum(abs(fx(:) .- oldfx(:))) ./ (bigness^2);

col(:,:,1) = fx;

col(:,:,2) = oldfx - fx;

col(:,:,3) = oldoldfx - fx;

imshow(col);

oldoldfx = oldfx;

oldfx = fx;

fx = x; %min(fx .* 0.5 .+ x, 1);

fprintf("%2.4f instability %c", xdiff, 13);

if(xdiff < (1/bigness))

iter

break;

endif;

sleep(0.75);

endif;

endfor;

toc

Name: Anonymous 2013-10-25 12:35

sub h2z {
my $s = shift;
$s =~ tr/ !"#$%&'()*+,-.// !"#$%&'()*+,-.\//;
$s =~ tr/0-9:;<=>?@A-Z[\]^/0-9:;<=>?@A-Z[\\]^/;
$s =~ tr/_`a-z{|}〜¢£¬ ̄¦¥₩/_`a-z{|}\~¢£¬¯¦¥₩/;
return $s;
}

Name: Anonymous 2013-10-25 14:48

>>39
I think you are missing many more, like
$s =~ tr/「」『』()。、・/''""()., /;
# and any of these:
# https://en.wikipedia.org/wiki/Japanese_typographic_symbols

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List