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

Pages: 1-4041-8081-120121-160161-

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

Name: Anonymous 2013-10-25 15:37

>>40
You've misunderstood the intent of this software.

Name: Anonymous 2013-10-25 17:57

>>41
I know its a full width to double byte unicode translator, just messing around.

Name: Anonymous 2013-10-25 22:34

>>38
what language is that? what's that supposed to do? isn't rand(1) just 0?

Name: Anonymous 2013-10-25 22:43

>>43
Looks like Matlab/Scilab for the fucking retarded slicing syntax.

Name: Anonymous 2013-10-25 22:47

>>44
You take that back right now!

Name: Anonymous 2013-10-25 23:14

>>45
Matlab/Scilab
syntax
is

SHIT

for

FAGS.

Name: Anonymous 2013-10-26 2:38

>>46
OK YOU FUQIN ANGERED AN EXPERT PROGRAMMER

I agree that the language's syntax is third-hand puke disgusting. But the array slicing stuff is really neat.

Name: Anonymous 2013-10-26 7:05

Can /prog/ please rate my Project Euler #3 solution?
I am actually >>15.

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

int main()
{
unsigned long long int i, factor, number = 600851475143;

for (i = 1; i < number; i++) {
/* The largest factors are equal to the number divided
by the smallest factors. Then just test those large factors
for primality. */
if (isprime(factor = (number / i)) && number % i == 0)
break;
}

printf("%Ld", factor);
}

int >>15
isprime(long long int n)
{
long long int i, sqrt_n;

if (n == 2)
return 1;

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

Name: Anonymous 2013-10-26 7:21

>>48
Unfortunately, that's not LUCAS-quality.

Name: Anonymous 2013-10-26 8:27

>>43
conways game of life =)

Name: Anonymous 2013-10-26 8:36

todays thingo


alpha = "abcdefghijklmnopqrstuvwxyz";

rnonce = ceil(rand(1) * 10) + 5;

nonce = ceil(rand(1,rnonce) * 26);

nonce = nonce(nonce != key(3));

rnonce = length(nonce);

key = [1,2,3];

inpstr = "CAPSTEST";

outpstr = '';

lastinp = 0;

for(i=1:rnonce)

lastinp = mod(lastinp + nonce(i) - 1, 26) +1;

outpstr(i) = alpha( mod(lastinp + key(mod(i, 3)+1)-1, 26) +1 );

endfor;

lastinp = mod(lastinp + key(3) - 1, 26) +1;

outpstr(i) = alpha( mod(lastinp + key(mod(i, 3)+1)-1, 26) +1 );

for(j=1:length(inpstr))

val = 0;

for(iter = 1:length(alpha))

val = val + (inpstr(j) == alpha(iter)) * iter;

endfor;

lastinp = mod(lastinp + val - 1, 26) +1;

outpstr(j+i) = alpha( mod(lastinp + nonce(mod(i, rnonce)+1)-1, 26) +1 );

if(inpstr(j) == ' ')

outpstr(j+i) = ' ';

endif;

endfor;

outpstr

Name: Anonymous 2013-10-26 8:51

In my timezone it's past midnight.


int con_initialize_f(FILE * ifp){
int i_width, i_height;
int c = EOF;
int i, j;
size_t m = 0;

if (fscanf(ifp, " %d x %d ", &i_width, &i_height) != 2)
return E_MALFORMED_INPUT;

if (i_width <= 0 || i_height <= 0)
return E_MALFORMED_INPUT;

g_width = i_width;
g_height = i_height;
alive_stat = calloc(g_width * g_height, sizeof(*alive_stat));
nigh_count = calloc(g_width * g_height, sizeof(*nigh_count));
freeze_alive_stat = malloc(g_width * g_height * sizeof(*alive_stat));
freeze_nigh_count = malloc(g_width * g_height * sizeof(*nigh_count));

for (j = 0; j < g_height; ++j) {
for (i = 0; i < g_width; ++i) {
do {
c = fgetc(ifp);
} while (c != ' ' && c != '.' && c != EOF);

if (c == EOF)
return E_MALFORMED_INPUT;
else if (c == '.') {
alive_stat[m] = 1;
n_add(i, j, 1);
}
m++;
}
}

return 0;
}


That's some intialization code from http://repo.or.cz/w/simple-cellular-automata-suite.git , which I made for the Conway's Game of Thug Life thread. I keep meaning to go back and add new engines to it, but the life of an ENTERPRISE progrider is tiring. (I will give you commit access if you ask for it.)

Name: Anonymous 2013-10-26 9:31

>>52
conways game of thug life ^^
did you make black/white cells? xD

Name: Anonymous 2013-10-26 9:37

isn't there a way to factor recursively with modulo?

Name: Anonymous 2013-10-26 9:51

x % y = z
y % z = a
z % a = b
...
until you get zero or one? (zero = divisible // one = isn't)

Name: Anonymous 2013-10-26 10:58

>>51,53
i knew it, it had to be luke with his shit matlab code

Name: Anonymous 2013-10-26 11:06

>>47
matrix =
[1 2 3
4 5 6
7 8 9]


FIOC:
>> matrix[1] == [1 2 3]
True


Matshit:
>> matrix[1] == [1 2 3]
(always add 50 newlines between lines of code and results)

Error: I am a piece of shit[i]![/i]

>> matrix(1) == [1 2 3]

Error: I am a piece of shit[i]![/i]

>> matrix(1)(:) == [1 2 3]


1.


Mathematica has saner syntax than Matlab and is homoeroticiconic. At least it has a valid excuse for having shitty slicing syntax and it's using [] instead of () for function calls.

Name: Anonymous 2013-10-26 11:08

>>52
Cute. Did you ever get your particular set to work, or did you just get the engine ready?

Name: Anonymous 2013-10-26 12:03

>>49
What's that mean?

Name: Anonymous 2013-10-26 13:32

>>58
and by set i meant ruleset*

Name: Anonymous 2013-10-26 13:35


mat = [1,2,3; 4,5,6; 7,8,9];

mat(1,:) == [1,2,3]

[1, 1, 1] %'(logical type)

Name: Anonymous 2013-10-26 13:39

>>55
or was that something else..?

floor(x / y) = a
x % y = z

((a % b) * a + z) % b == 0 ?

Name: Anonymous 2013-10-26 13:44

((a % b) * y + z) % b

Name: Anonymous 2013-10-26 13:50

then make y a multiple of b? =D

Name: Anonymous 2013-10-26 14:42

>>61
The list-of-lists syntax is much more flexible and clear, and it's also almost identical to the Mi,j notation used in mathematics and other abstract bullshite.

For instance, in linear programming it makes sense to talk of A5 as being the fifth constraint of the program, even though A could be a 5x9999 matrix.

Now, yes, that declaration syntax ([1,2,3; 4,5,6; 7,8,9]) is less cumbersome than typing [[1, 2, 3], [4, 5, 6], [7, 8, 9]], but that syntax is not stopping Matshit developers from representing the matrix internally as a list of lists.

PD: parentheses for subindices look retarded IMO

Name: Anonymous 2013-10-26 20:00

Don't hurt me please


void EncodeMessage()
{
key.assign(StrToBin(key));
message.assign(StrToBin(message));
for(unsigned int x = 0; x < message.size()/7; x++)
{
std::vector<bool> a;
for(int y = 0; y < 7; y++)
{
a.push_back(XOR((int)(message[7*x+y]-48), (int)(key[(7*x+y)%key.size()]-48)));
}
encoded.push_back(a);
}
}

Name: Anonymous 2013-10-26 23:35

>>66
Sepples quality code

Name: Anonymous 2013-10-27 0:14

//Attempts to find the sole "root" symbol of this grammar
bool findstartsym() {
set<int> lside, rside;

vector<rule*>::const_iterator i;
for (i = rtable.begin(); i != rtable.end(); i++) {
lside.insert((**i).get_lhs());
rule::const_iterator j;
for (j = (**i).begin(); j != (**i).end(); j++)
rside.insert(*j);
}

set<int>::const_iterator j;
for (j = rside.begin(); j != rside.end(); j++)
if (lside.count(*j) > 0)
lside.erase(*j);
//lside.erase(rside.begin(), rside.end());

if (lside.size() > 1) {
//Too many startsyms
cerr << "Multiple start symbols found!\n"
<< "Check your grammar for dangling productions.\n";
return true;
}

if (lside.size() < 1) {
//No startsym
cerr << "No start symbol found!\n"
<< "Make sure your grammar has a unique start symbol.\n";
return true;
}

startsym = *(lside.begin());
return false;
}

Name: Anonymous 2013-10-27 3:38

^^ it's euclid's greatest common divisor..
pair it up with a lazy prime template (like using 2 step.. except maybe 30 / 210 / etc) and fermat's prime test [2^(n-1) % n == 1]

Name: Anonymous 2013-10-27 3:53

...I wonder if it's worth using fermats.. it could be faster without?

Name: Anonymous 2013-10-27 4:15

Name: Anonymous 2013-10-27 6:20

>>58
My particular engine (the one based on sin and a bunch of ξ alterations) did end up working, it just wasn't very interesting to look at, unfortunately. It compensated for itself too fast and simply shot to zero.

Name: Anonymous 2013-10-27 14:03

var montageOffset = (function() {
// Magic numbers :(
var firstdelay = 6.15;
var shortdelay = 1 / 20;
var shortlimit = 12;
var longdelay = 3 / 2;

var t = 0;
var shortframe = 0;
var shortcount = 0;
var longframe = Math.floor(Math.random() * 62 + 1);
var frametime = 0;

return {
alt: false,
smalloffset: [0, 0],
tick: function() {
t += timeSinceLastTick;
if (t < firstdelay) return;
frametime += timeSinceLastTick;

var alt = this.alt;
if (frametime >= (alt ? longdelay : shortdelay)) {
if (alt) {
longframe = 1 + longframe % 62;
alt = false;
} else {
shortframe = 1 + shortframe % 62;
shortcount++;
if (shortcount >= shortlimit) {
alt = true;
shortcount = 0;
}
}
frametime = 0;
this.alt = alt;
}

var frame = alt ? longframe : shortframe;
var divs = 8;

// FIXME I think these are backwards.
this.smalloffset = [
Math.floor(frame / divs) / divs,
(frame % divs) / divs,
];
},
};
})();

Name: Anonymous 2013-10-27 15:17

>>72
Ah, what a shame.

Name: Anonymous 2013-10-27 15:46

outcome :: Board -> Outcome
outcome board = maximum [f $ (`M.lookup` board) <$> line | line <- allLines]
where f [Just X, Just X, Just X] = Win X
f [Just O, Just O, Just O] = Win O
f [Just _, Just _, Just _] = Draw
f _ = Continue

Name: Anonymous 2013-10-28 0:56

hmm.. so is that lpt nearly an optimized number sieve?
seems like it should be faster, since it tells you which numbers to keep rather than which to throw away? =)

Name: Anonymous 2013-10-28 1:52

and i get that keeping a number vs throwing it away isn't much of a difference in itself...

but even with say, primes < 25..
sieve 2 keeps 50% / throws 50%
sieve 3 keeps 66% / throws 33%
//sieve 5 keeps 80% / throws 20%

composite sieve 2,3,5 keeps (1,7,11,13,17,19,23,29) mod 30 (keeps 26% / throws 74%) and takes one pass instead of two..?
...it's a little large for < 25..
composite sieve 2,3 keeps (1,5) mod 6 (keeps 33% / throws 66%)
1,(2,3),5, 7,11, 13,17, 19,23, [25],29, 31,[35]...

Name: Anonymous 2013-10-28 14:28

if [[ "$1" =~ '/' ]]; then
FILENAME="$1"
else
FILENAME="$HOME/.local/bin/$1"
fi

if [ -f "$FILENAME" ] && file -I "$FILENAME" | grep -v -q 'text/'; then
while true; do
read -p "$1 may be a binary file. Really edit it? " -n 1 yn
case $yn in
[Nn] )
exit 1
;;
[Yy] )
break
;;
* )
echo At least answer yes or no.
exit 1
;;
esac
done
fi

$EDITOR $FILENAME
[ -e $FILENAME ] && [ ! -x $FILENAME ] && chmod +x $FILENAME

Name: Anonymous 2013-10-29 9:45

* Helper subroutine for DISPLAY-SHIP. The STRING statement can be
* thought of as a cruder version of sprintf from the C language.
DISPLAY-CHARACTER.
IF SHIP-IDX > 1 THEN
STRING SPACE DELIMITED BY SIZE
QUADRANT DELIMITED BY SPACE
SPACE DELIMITED BY SIZE
INTO OUT-TEXT WITH POINTER LINE-POS
END-IF.
STRING CHARACTER-NAME (SHIP-CHAR-IDX (SHIP-IDX))
DELIMITED BY ' '
INTO OUT-TEXT WITH POINTER LINE-POS.

Name: Anonymous 2013-10-29 11:26

>>79
SHIP-CHAR-IDX
Ugh, you shippers now need lookup systems just to remember who you're shipping this season? Disgusting, all of you.

Name: Anonymous 2013-10-29 22:46

/**
* Initialize the contents of the frame.
*/
private void initialize() {
editWindow = new JFrame();
editWindow.setTitle("Edit Item");
editWindow.setBounds(100, 100, 313, 250);
editWindow.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
editWindow.getContentPane().setLayout(null);

nameField = new JTextField();
nameField.setHorizontalAlignment(SwingConstants.RIGHT);
nameField.setColumns(10);
nameField.setBounds(92, 57, 158, 20);
editWindow.getContentPane().add(nameField);

priceField = new JTextField();
priceField.setHorizontalAlignment(SwingConstants.RIGHT);
priceField.setColumns(10);
priceField.setBounds(92, 88, 158, 20);
editWindow.getContentPane().add(priceField);

quantityField = new JTextField();
quantityField.setHorizontalAlignment(SwingConstants.RIGHT);
quantityField.setColumns(10);
quantityField.setBounds(92, 120, 158, 20);
editWindow.getContentPane().add(quantityField);

JLabel label = new JLabel("Name");
label.setHorizontalAlignment(SwingConstants.RIGHT);
label.setBounds(36, 60, 46, 14);
editWindow.getContentPane().add(label);

JLabel label_1 = new JLabel("Price");
label_1.setHorizontalAlignment(SwingConstants.RIGHT);
label_1.setBounds(36, 91, 46, 14);
editWindow.getContentPane().add(label_1);

JLabel label_2 = new JLabel("Quantity");
label_2.setHorizontalAlignment(SwingConstants.RIGHT);
label_2.setBounds(36, 123, 46, 14);
editWindow.getContentPane().add(label_2);

JButton button = new JButton("Change");
button.setBounds(102, 162, 89, 23);
editWindow.getContentPane().add(button);
}

Name: Anonymous 2013-10-29 22:53

unsigned int yoba(unsigned int x) { return ((unsigned long long)(x)*0x4325c53f)>>36;}

Name: Anonymous 2013-10-30 12:04

phi :: FStructure -> Maybe Constituent
phi fs
| Just (CAT Sent XP) <- fs # Category = do
ARG (subjKey : _) <- fs # Arguments
subj <- phiOn fs subjKey
rest <- phi $ fs `with` [(Category, CAT Verb XP)]
return $ Phrase fs [subj, rest]

| Just (CAT Verb XP) <- fs # Category = do
ARG argList <- fs # Arguments
let objs = drop 1 argList -- Ignore subject
verb <- phi $ fs `with` [(Category, CAT Verb X)]
args <- mapM (phiOn fs) objs
return $ Phrase fs (verb : args)

| Just (LEX w) <- fs # Lexeme = Just (Head fs w)

phi _ = Nothing

Name: Anonymous 2013-10-31 18:43

def setcolor(label, color):
if label and color:
fgcolors[label] = color

Name: Anonymous 2013-11-18 7:36

I stuck this in a cronjob repeated a few times, and it downloads a random Touhou doujin CD from the TLMC to the pwd (which is set in the cronjob to be my mp3 player's SD card, if I have it plugged in overnight) so that I have some new random albums to listen to the next day at work. It's probably one of the worst pieces of code I've ever written, because I don't actually know Perl, so I just cobbled it together from help pages on CPAN.

#!/usr/bin/perl -w

use strict;
use warnings;
use Encode qw(decode_utf8);
use File::Temp qw(tempdir tempfile);
use File::Path qw(make_path);
use HTML::Parser;
use LWP::Simple qw(getstore);
use LWP::UserAgent;
use URI::Escape qw(uri_unescape);

my $ua = LWP::UserAgent->new;
$ua->agent("Some kind of randomized wget machine/0.2.1");
my $pl_parser = HTML::Parser->new( api_version => 3,
start_h => [\&pl_start, "tagname, attr"],
end_h => [\&pl_end, "tagname"],
marked_sections => 1,
);
my $req = HTTP::Request->new(GET => 'http://otokei-douj.in/');
my $pl_in_playlist = 0;
my @playlist = ();

my $res = $ua->request($req);
if ($res->is_success) {
$pl_parser->parse(decode_utf8($res->content));
} else {
die ($res->status_line . "\n");
}

if ($#playlist < 0) {
die ("Couldn't get any elements - has the site changed layout?");
}

my $subpage = "http://otokei-douj.in/" . $playlist[rand @playlist];
$req = HTTP::Request->new(GET => $subpage);
@playlist = ();
$res = $ua->request($req);
if ($res->is_success) {
$pl_parser->parse(decode_utf8($res->content));
} else {
die ($res->status_line . "\n");
}

if ($#playlist < 0) {
die ("Couldn't get any elements - has the site changed layout?");
}

my $dlpage = "http://otokei-douj.in/download.php" . $playlist[rand @playlist];
my $dir = tempdir( CLEANUP => 1 );
my ($fh, $filename) = tempfile( DIR => $dir, SUFFIX => '.7z' );
my @title_parts = ($dlpage =~ /link=%2F(.*)&album=(.*)/);
system("wget -q \"$dlpage\" -O \"$filename\"");

# One side effect of not pulling the link exactly is that '+' is
# present where '%20' would be if a second page were followed. Actual
# '+' characters are still represented as %2B, so this will not harm
# actual filenames
$title_parts[0] =~ s/\+/%20/g;
$title_parts[0] = decode_utf8(uri_unescape($title_parts[0]));
make_path($title_parts[0]);
system("7z x \"-o$title_parts[0]\" \"$filename\"");

# ----------------------------------------------------------------------
# Parsing functions:
sub pl_start {
my ($tagname, $attr) = @_;
if ($tagname eq "ul" && $attr->{'class'} eq "playlist") {
$pl_in_playlist = 1;
} elsif ($tagname eq "a" && $pl_in_playlist == 1) {
push (@playlist, $attr->{'href'});
}
}

sub pl_end {
my ($tagname) = @_;
if ($tagname eq "ul") {
$pl_in_playlist = 0;
}
}

Name: Anonymous 2013-11-18 15:12

>>85
Touhou vocals are shit.

Name: Anonymous 2013-11-18 16:28

>>82
I can't tell what the heckie this is supposed to do!

Name: Anonymous 2013-11-19 0:44

>>85
use HTML::TreeBuilder::XPath;

my $tree = HTML::TreeBuilder::XPath->new;
my $host = 'http://otokei-douj.in';

my $res = $ua->request(HTTP::Request->new(GET => "$host/"));
die "$res->status_line" unless $res->is_success;

$tree->parse(decode_utf8($res->content));
my @playlist = $tree->findnodes('//ul[@class="playlist"]/li/a');
my $album_url = $playlist[rand @playlist]->attr('href');

Insert error handling as desired, also you might want to make this a sub since you call it a couple of times (once for the main page, once for the artist(?) page)

Name: Anonymous 2013-11-19 4:55

>>85
N-n-nice find.
How do you guys even find these? That server is is so fast, and that page is so fucking parsable. Isn't it all a php|perl a script? I want to embed HTSQL so badly to it. If someone donates me 200, I'll download everything, and make a schema.

But I agree with >>86, vocals are shit, no matter the song.

Do they even have fakumen's work?:
https://www.youtube.com/watch?v=t0PcB9RzBnU&list=PL8F1671253111E1D6
https://www.youtube.com/watch?v=SQQy8W-gUb4&list=RDSQQy8W-gUb4

Facepalm:
http://fuuka.otokei-douj.in
Whomever is admin, is boss.

Name: Anonymous 2013-11-19 5:05

>>89
s/fakumen/fukumen|フクメン/ (mask)/
and no.

Name: Anonymous 2013-11-19 5:07

>>85-89
check thii2 2hiit out

#!/usr/bin/env perl

use v5.10;
use warnings;

use Mojo::UserAgent;
use File::Path qw(make_path);
use File::Temp qw(tempfile);

my $ua = Mojo::UserAgent->new;
$ua->transactor->name('Touhoulicious v2.h.u');

my $host = 'http://otokei-douj.in';
my $artist_url = choose("$host/")->attr('href');
my $album = choose("$host/$artist_url");
my $album_name = $album->text;
my $album_url = $album->attr('href');
make_path($album_name);

sub choose {
my $sel = 'ul.playlist > li > a';
return $ua->get(shift)->res->dom($sel)->shuffle->first;
}


I'm having trouble actually downloading the file though

Name: Anonymous 2013-11-19 13:44

>>88, 91
Thanks - I was kind of hoping somebody who knows shit might actually step in and put my shit out of its misery.

Name: Anonymous 2013-11-19 20:57

just some stupid shell scripting today
sudo time cat /dev/sdb9 | grep -Uboa -P `xxd -l14 -p 1.dat |sed 's/../\0\\x/g'` | tee search

Name: Anonymous 2013-11-19 20:59

>>93
forgot to mention that bgrep is lame piece of shitware, beware

Name: Anonymous 2013-11-19 22:26

>>92
No big deal. Here, I even commented some of it:

#!/usr/bin/env perl

use v5.10;
use warnings;

use Mojo::UserAgent;
use File::Path qw(make_path);
use File::Temp qw(tempdir tempfile);

binmode STDOUT, ":encoding(UTF-8)";

# Allow 1GB file downloads. Most of the albums should be smaller than this.
# Increase it if you think you'll find bigger ones.
$ENV{MOJO_MAX_MESSAGE_SIZE} = 1024 * 1024 * 1024;

my $ua = Mojo::UserAgent->new;
$ua->transactor->name('Touhoulicious v2.h.u');

my $host = 'http://otokei-douj.in';

my (undef, $tmpname) = tempfile(SUFFIX => '.7z', OPEN => 0);

# If you need to run this script multiple times each night, you might as well
# make the loop as small as possible and not schedule the cron job repeatedly.
my $num_runs = 1;
for (1 .. $num_runs) {
my $artist_url = choose("$host/")->attr('href');
my $album = choose("$host/$artist_url");
my $album_name = $album->text;
my $album_url = "$host/download.php" . $album->attr('href');

# Mojolicious already creates a temp file when saving downloads, but I
# haven't figured out how to repurpose it instead of making our own.
say "Downloading...";
$ua->get($album_url)->res->content->asset->move_to($tmpname);
say "Got $album_name";

make_path($album_name);

# Try using File::Unpack for this.
# (I wasn't able to build it but you might have better luck.)
`7z x -o"$album_name" "$tmpname"`;
die "Couldn't extract: $!" if $?;
}

unlink $tmpname;

sub choose {
my $sel = 'ul.playlist > li > a';
return $ua->get(shift)->res->dom($sel)->shuffle->first;
}

Name: Anonymous 2013-11-20 15:45

>>93
Why do you have nine partitions on /dev/sdb?

Name: Anonymous 2013-11-22 9:53

>>96
not nine but stil a lot
system, old/new home, swap, videos, random garbage and there is still some unallocated space.
that hdd is just a dumpster now.

Name: Anonymous 2013-11-23 14:20

>>97
your lack of an organized storage scheme pisses me off

Name: Anonymous 2013-11-23 18:04

def fixedXORbin(bin1, bin2):
assert len(bin1) == len(bin2)
final = bytearray()
for i in range(len(bin1)):
final.append(bin1[i] ^ bin2[i])
return bytes(final)

Name: Anonymous 2013-11-23 21:17

>>98
my time management skills will probably make your head explode then.

Name: Anonymous 2013-11-25 5:57

A lain spammer.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <poll.h>

#include <signal.h>

#define BUFFER_LENGTH 1024
#define LAIN_LENGTH 5
char* lain = "LAIN\n";

char* program_name;

void signal_handler(int number) {
printf("%s: signal handler saw signal %d\n", program_name, number);
}

int write_buffer(int fd, const void* buf, size_t count) {
unsigned char* cbuf = (unsigned char*)buf;
unsigned int offset = 0;
int rc;

for(;;) {
size_t remaining_count = count - offset;
rc = write(fd, cbuf + offset, remaining_count);
if(rc < 0){
return rc;
}
else if(rc != remaining_count) {
offset += rc;
}
else {
return count;
}
}
}

#define SIGNALLED_TO_STOP_READING 1
int read_stream_buffer(
int fd, void* buf, size_t count,
int (*reader)(void*, size_t, void*), void* userdata) {
int rc;
int reader_rc;

for(;;) {
rc = read(fd, buf, count);
if(rc <= 0) {
return rc;
}
else {
reader_rc = reader(buf, rc, userdata);
if(!reader_rc) {
return SIGNALLED_TO_STOP_READING;
}
}
}
}

int read_stream_buffer_impatiently(
int fd, void* buf, size_t count,
int (*reader)(void*, size_t, void*), void* userdata,
int timeout) {
int rc;
int reader_rc;
struct pollfd poll_fd;
poll_fd.fd = fd;
poll_fd.events = POLLIN;

for(;;) {
rc = poll(&poll_fd, 1, timeout);
if(rc <= 0) {
// rc == 0 implies timeout exceeded.
// rc < 0 implies an error occured.
return rc;
}

rc = read(fd, buf, count);
if(rc <= 0) {
// if rc == 0, there is nothing more to read
// if rc < 0, an error occured.
return rc;
}

// rc is bytes read.
reader_rc = reader(buf, rc, userdata);
if(!reader_rc) {
return SIGNALLED_TO_STOP_READING;
}
}
}

int echo_reader(void* buf, size_t size, void* userdata) {
printf("Read %u bytes: ", size);
fwrite(buf, size, sizeof(char), stdout);
printf("\n");
}

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

program_name = argv[0];

char recv_buff[BUFFER_LENGTH];

signal(SIGPIPE, signal_handler);

if(argc != 3) {
fprintf(stderr, "%s: server-hostname server-port\n", program_name);
exit(1);
}

char* server_host = argv[1];
int server_port = atoi(argv[2]);

int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if(socket_fd < 0) {
fprintf(stderr, "%s: could not open socket: %d\n", program_name, socket_fd);
exit(2);
}

struct hostent* server_host_entry = gethostbyname(server_host);
if(server_host_entry == NULL) {
fprintf(stderr, "%s: host: %s not found.\n", program_name, server_host);
exit(3);
}

struct sockaddr_in server_address;

bzero(&server_address, sizeof(struct sockaddr_in));

server_address.sin_family = AF_INET;
bcopy((char*) server_host_entry->h_addr,
(char*) &(server_address.sin_addr.s_addr),
server_host_entry->h_length);
server_address.sin_port = htons(server_port);

rc = connect(socket_fd, (struct sockaddr*) &server_address, sizeof(struct sockaddr_in));
if(rc < 0) {
fprintf(stderr, "%s: could not connect: %d\n", program_name, rc);
exit(4);
}

for(;;) {
rc = write_buffer(socket_fd, lain, LAIN_LENGTH);
if(rc < 0) {
printf("%s: lain write failed: %d\n", program_name, rc);
fflush(NULL);
break;
}
rc = read_stream_buffer_impatiently(
socket_fd, recv_buff, BUFFER_LENGTH,
echo_reader, NULL,
1000);
if(rc < 0) {
printf("%s: read failed: %d", program_name, rc);
fflush(NULL);
break;
}
}

close(socket_fd);
return 0;
}

Name: Anonymous 2013-11-25 6:03

This is kind of fun.


$ torsocks client www.google.com 80
Read 498 bytes: HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Content-Length: 925
Date: Mon, 25 Nov 2013 06:58:56 GMT
Server: GFE/2.0

<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
<title>Error 400 (Bad Request)!!1</title>
<style>
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:
Read 570 bytes: 180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}
</style>
<a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>
<p><b>400.</b> <ins>That’s an error.</ins>
<p>Your client has issued a malformed or illegal request. <ins>That’s all we know.</ins>

client: signal handler saw signal 13
client: lain write failed: -1
$ torsocks client www.yahoo.com 80
Read 217 bytes: <HEAD><TITLE>Invalid HTTP Request</TITLE></HEAD>
<BODY BGCOLOR="white" FGCOLOR="black">
<FONT FACE="Helvetica,Arial"><B>
Bad request syntax</B></FONT>

<!-- default "Invalid HTTP Request" response (400) -->
</BODY>

client: signal handler saw signal 13
client: lain write failed: -1

Name: Anonymous 2013-11-26 12:28


def add5(x)
return x + 5;

Name: Anonymous 2013-11-26 23:17

y f = f $ y f

Name: Anonymous 2013-11-29 22:18

Splits a string into a double array

void split_data(double *data, char *s, int fields) {
char buff[DATA_MAX];
int j = 0, i;

while(*s) {
while((*s == ' ' || *s == '\t') && *s)
*s++;

i = 0;
while(!(*s == ' ' || *s == '\t') && *s)
buff[i++] = *s++;
buff[i] = 0;

data[j++] = atof(buff);

if(j == fields)
return;
*s++;
}

Name: Anonymous 2013-11-30 6:22

how do i post labview code?

Name: Anonymous 2013-11-30 10:18

twojar = @(x, y, z) x(z(y));

Name: Anonymous 2013-11-30 10:23

ycell = @(a, b, x, y, z) z(x(a) !xor! y(b))

crypto primitives ^^

Name: Anonymous 2013-11-30 13:44

Oh look, Luke got tired of the old prague again and he came back.

Name: Anonymous 2013-12-01 10:48

for some reason i just thought of that shnappi song

Name: Anonymous 2013-12-04 21:32

>>109
Hey! I'm his father.

Name: VIPPER 2013-12-07 14:27

int
main (int argc, char *argv[])
{
return EXIT_SUCCESS;
}

Name: Anonymous 2013-12-07 14:36

>>112
EXPERT ANONIX IMPLEMEN-TATER

Name: Anonymous 2013-12-08 4:15

>>112

int
main(..

What the fuck

Name: Anonymous 2013-12-08 5:14

>>114
Have you never seen C before in your life?

Name: Anonymous 2013-12-08 20:48

>>115
Is that first edition C?

Name: Anonymous 2013-12-08 21:16

>>116
Are you guys serious? It's any edition C. White space is ignored, in fact


#include <stdlib.h>

int
main(
int argc,
char **argv
)

{
return(EXIT_SUCCESS);
}



is perfectly legal. Some people even separate arguments like that if they're very long and easier to organize that way.

Name: Anonymous 2013-12-08 21:22

>>117
I'm not talking legal, I'm talking standard.

Name: Anonymous 2013-12-08 21:54

>>118
The standards don't specify a style.

Name: VIPPER 2013-12-11 19:49

>>112
NICE VIP quality GNU-style C!

>>114,116,118
You are a [i]nigger[i].

Name: Anonymous 2013-12-11 23:26

>>120
That's not GNU-style - the indentation is two characters, not three!

Name: VIPPER 2013-12-12 5:39

>>121
GNU-style uses two characters indentation!

Name: Anonymous 2013-12-12 6:01

>>122
That's odd, indent -gnu does, in fact, use two space indentation.

This doesn't make sense. I distinctly remember that GNU style uses tabs three spaces wide. If my memory is faulty on this, what else have I forgotten? Will all the doorknobs switch sides again? What if the semantics of calloc changes in the middle of me programming and I don't think to re-check the manpage?

Thanks a lot, /prog/. Now I'm not going to be able to sleep for weeks.

Name: VIPPER 2013-12-12 6:38

>>123
nice get

indentation = 2 spaces
tab = 4 indentation

example of GNU-style code:

if ((thing || thing2 || thing3 || thing4 || thing5)
&& (thing6 || thing7 || thing8 || thing9 || thing10))
if (1)
{
yes_i_use_goto: /* check the special indentation for labels! */
niggers ();
yes_i_use_goto2:
more_niggers ();
if (1)
omg_tabs (); /* check the tab! */
}

Name: VIPPER 2013-12-12 6:40

>>123
manpage
man is sexist! use info.

Name: Anonymous 2013-12-12 10:16

A cute little noise maker


#include <stdio.h>

int main(int argc, char** argv) {
int byte;
for(;; byte++) {
fputc(byte << (byte >> (byte >> 7)), stdout);
}
}


I was trying to rewrite one I had found on /prog/ or was it /jp/? If you recognize it, could you post the original?

Name: VIPPER 2013-12-12 11:54

>>126
`
>char**, not char *argv[] or just int main (void)
>not giving a value to byte, not even byte = rand()
>not knowing that for(;; byte++) causes undefined behavior
>not returning 0, EXIT_SUCCESS or EXIT_FAILURE (ignore this if you are using C99 or C11 but in that case you should be using for (int byte = value; expr; byte++)
>not checking for fputc errors

Name: Anonymous 2013-12-12 12:15

>>127
Stop calling yourself a VIPPER when you act like an imageredditor.

Name: VIPPER 2013-12-12 12:30

>>128
also, you made me cry ;_;

Name: Anonymous 2013-12-12 12:50

Name: Anonymous 2013-12-12 13:01

/prog/ - reddit discussion

Name: VIPPER 2013-12-12 13:06

>>132
nigger

Name: Anonymous 2013-12-12 17:44

A post has been deleted. Don't make posts like that again.

Name: Anonymous 2013-12-12 18:29

>>134
Why didn't you didn't delete >>129?

Name: Anonymous 2013-12-12 18:51

>>135
Err, I mean >>127.

Name: Anonymous 2013-12-12 19:03

>>127,131
Since when is mememtexting an ``acceptable'' joke here?

Name: Anonymous 2013-12-12 21:43

>>135
Difference between stupid but ignorable, and absolutely insufferable.

Post >>127 at least had something related to programming in it.

I don't really check the board that often, but if I spot posts like >>129 again they'll be blacklisted.

Name: VIPPER 2013-12-12 22:09

>>138
Love you mod

Name: VIPPER 2013-12-12 23:08

>>138
wait! why didn't you deleted >>128,132?

Name: Anonymous 2013-12-12 23:40

>>140
I don't want to delete too many posts. 1 every so often is okay, but I dislike removing large swaths of posts (unless it's just one person posting 10 - 20 times in a row).

I was thinking of deleting those as well, since it annoys me when reddit keeps getting mentioned, but meh.

Name: Anonymous 2013-12-13 19:05

i'm studying for my music trivia final, here's what my high tech auto study code looks like:


$ cat autostudy2.sh
while true
do
espeak <terms.txt
done

Name: VIPPER 2013-12-19 3:45


int
one (void)
{
return 1;
}

Name: Anonymous 2013-12-22 12:23

module NanoTime where
import System.Clock

getNanoTime :: IO Integer
getNanoTime = do
tspec <- getTime Realtime
return ((s tspec) + (n tspec))
where s = (*(10^9)) . fromIntegral . sec
n = fromIntegral . nsec

Name: Anonymous 2013-12-24 7:29

int strcmp(const char *u, const char *v) {
union {const char *c; const unsigned char *u;} a, b;
for(a.c = u, b.c = v; *a.u == *b.u && *a.u != '\0'; a.u++, b.u++);
return *a.u - *b.u;
}

Name: Anonymous 2013-12-24 9:32

>>145
uuuuuuuuuuuuuuuuuuuuUUUuuuuuU!

Name: Anonymous 2013-12-24 17:02

>>145
Out of curiosity, why does the comparison need to be between unsigned values? I may be missing something, but that seems completely unnecessary, and I think it suffers from implicit char <-> unsigned char conversion at the '\0' check, even though the point of the method is to avoid conversion.

Name: Anonymous 2013-12-24 22:40

>>146
Am I kawaii? u.Ug.u~

Name: Anonymous 2013-12-25 15:22

>>147
Out of curiosity, why does the comparison need to be between unsigned values?
Don't really remember actually, it's been some time since I wrote this but I *think* I ran it through a test suite and it failed 1 test or so (out of 15) and the union fixed it somehow.
implicit char <-> unsigned char conversion at the '\0'
Wouldn't 0 and '\0' be both int or what do you mean? Suggestions welcome. Also, have you even READ DA STANDARD Section 6.4.4?

Name: Anonymous 2013-12-25 19:52

>>149
Well, if it passed a test there certainly is a difference. I was just interested what that difference is, since it wasn't immediately obvious.

My [b]STANDARD[/b] doesn't have a section 6.4.4 (I'm just looking at the ANSI C standard now, I'll check the others when I'm on a machine with access to them), but section 3.1.3.4 Character constants says

... An integer character constant has type int

So that's pretty unambiguous - I mistakenly thought it would be char.

Actually, though, it seems the difference is solely in the return statement, and shows up when one of the final characters doesn't have the sign bit set, but another does.

#include <stdio.h>

int diff1(const char a, const char b)
{
return a - b;
}

int diff2(const char a, const char b)
{
const unsigned char au = (const unsigned char)a;
const unsigned char bu = (const unsigned char)b;
return au - bu;
}

int main(void)
{
const char *str1 = "abCθDξ";
const char *p = str1;
for (++p; *p != '\0'; ++p)
printf("diff1(%c, %c) = %d\ndiff2(%c, %c) = %d\n",
*p, *(p-1), diff1(*p, *(p-1)), *p, *(p-1),
diff2(*p, *(p-1)));
return 0;
}


$ ./a
diff1(b, a) = 1
diff2(b, a) = 1
diff1(C, b) = -31
diff2(C, b) = -31
diff1(<CE>, C) = -117
diff2(<CE>, C) = 139
diff1(<B8>, <CE>) = -22
diff2(<B8>, <CE>) = -22
diff1(D, <B8>) = 140
diff2(D, <B8>) = -116
diff1(<CE>, D) = -118
diff2(<CE>, D) = 138
diff1(<BE>, <CE>) = -16
diff2(<BE>, <CE>) = -16


That certainly seems like something somebody would put in a test suite.

Name: Anonymous 2013-12-25 22:00

... An integer character constant has type int
Yeah, once you think about it, it somehow makes sense: char only seems to be used as string (char*) inside the stdlib and single characters are int -- I guess because of things like EOF, which is sometimes defined as -1, which might overlap in the code page with some other character if it were 8 bit.
The real problem to me is that char can be signed or unsigned; this usually just annoys me and is probably one of my main uses of union...

Anyway, new day, new function:
void* memset(void *p, int v, size_t n) {
unsigned char v_, *p_;
for(v_ = v & 0xFF, p_ = p; n--; p_[n] = v_);
return p;
}

Name: Anonymous 2013-12-26 18:22

Is there any reason this is bad practice?


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

void *error(char *f, char *fmt, ...) {
va_list args;
va_start(args, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);

if(f)
perror(f);

exit(1);
}

int main(int argc, char **argv) {
int c;
FILE *f;
(f = fopen(*++argv, "r")) || error("fopen", "Couldn't open %s", *argv);

while((c = fgetc(f)) != EOF)
putchar(c);

return(0);
}

Name: VIPPER 2013-12-26 18:48

>>152
while((c = fgetc(f)) != EOF)
in a system where char is unsigned and sizeof (char) == sizeof (int) EOF is a vaild character
better use while((c = fgetc (f)) != EOF || (!feof (f) && !ferror (f))

exit (1);
you cause a implemented defined behavior by returning 1, the standard values are 0, EXIT_SUCCESS, EXIT_FAILURE

fprintf(stderr, "\n");
since \n is a single character I would use fputc ('\n', stderr); but this is not really a problem

void *
you don't return something from that function, you should retrun void and in C11 you can add _Noreturn with the void

(f = fopen(*++argv, "r")) || error("fopen", "Couldn't open %s", *argv);
what if *++argv == NULL? undefined behavior. you must check it. I would use if (argv[0] && argv[1]) (f = fopen (argv[1], "r")) || error ("fopen", "Couldn't open %s", argv[1]);

In my opinion using a error function that destroys the progam is bad for two reasons:
1) the program must start from main and end in main and each function should have one return, using exit() makes my cry ;-;
2) in most cases closing the program on a error is a bad idea, it can create data loss. The worst is what it's used in libraries

other problems:
you don't check the return value of fprintf, vfprintf, putchar and you don't do anything if fgetc (f) == EOF && ferror (f), you don't use GNU Style

Name: Anonymous 2013-12-26 22:45

>>153
Ok All of these are fucking stupid.
better use while((c = fgetc (f)) != EOF || (!feof (f) && !ferror (f))
No. K&R2 goes through the entire fucking book using the style used in >>152. Your scenario is ridiculous

you don't return something from that function, you should retrun void and in C11 you can add _Noreturn with the void
I need to return something or it would not have compiled since I used error in an expression and the value was not ignored.

what if *++argv == NULL?
Then fopen would have failed and error would have caught it.

In my opinion using a error function that destroys the progam is bad for two reasons:
Your opinion isn't bad practice. exit exists to be able to terminate the process from any function. Your code may have to look much worse if you insist on exiting through main.

you don't check the return value of fprintf, vfprintf, putchar
I don't need to check the return value. If it failed writing the output than nothing can be done. What am I going to do if it fails writing the error? Try writing another error?

you don't use GNU Style
GNU Style is shit.

Name: VIPPER 2013-12-26 23:31

>>154
Your scenario is ridiculous
why?

Then fopen would have failed and error would have caught it.
Not really, it's undefined behavior (last time I checked the sandard, it may have changed)

Your code may have to look much worse if you insist on exiting through main.
yes same goes for goto

also please don't try to attack me, I have weak feelings ;-;

Name: Anonymous 2013-12-26 23:38

>>155
Looks like technically passing NULL to fopen is undefined though every implementation I've seen handles it fine.

Also, are you saying that you should never use goto either? Because forward error handling is an example of decent goto use.

Name: VIPPER 2013-12-27 1:22

>>156
Also, are you saying that you should never use goto either?
No, I would use goto AND exit() when I should (in this case for example). I am just saying that they are ``bad practice''

Name: Anonymous 2013-12-27 1:59

This is the first time I've ever wanted to filter someone on /prog/ ][.

Name: VIPPER 2013-12-27 2:57

>>158
why? anyway, feel free but you hurt my feelings

Name: VIPPER 2013-12-27 3:01

>>158
Anyway, I couldn't wait for better reply by a pedophile who sages threads

Name: Anonymous 2013-12-27 3:12

>>160
Fuck off back to pro/g/.

Name: VIPPER 2013-12-27 3:34

>>161
I am already there

Name: VIPPER 2013-12-27 3:39

>>161
oh btw, since you like saying "Fuck off" you may want to look at http://bbs.progrider.org/prog/read/1383465168/24

Name: Anonymous 2013-12-27 15:21

>>160
You're that guy? No wonder your posts are so lacking in quality.

Name: VIPPER 2013-12-27 16:22

>>164
I do, how about you?

Name: VIPPER 2013-12-27 16:25

>>165
oops reply to the wrong thread!

Name: Anonymous 2013-12-27 19:43


Storage.prototype.connect = function(callback) {
var self = this,
dbFileName = this.baseDir + "/database.db";

this.sequelize = new Sequelize(null, null, null, {
dialect: "sqlite",
storage: dbFileName
});

this.sequelize.authenticate().complete(function(err) {
if (err) {
return callback(err);
}

self.defineModels();
self.sequelize.sync().complete(callback);
});
};

Name: VIPPER 2013-12-27 20:40

>>167
I find this code sexy
10/10, would ``rub''

Name: Anonymous 2013-12-28 1:13

>>167
You forgot these:

}();{}[])};
};()[]
};};};()
};()

Name: Anonymous 2014-01-08 4:25

Hate doing math by hand in numeric calculus course, so whenever there is a PC nearby from some colleague, I whip dumb code to calculate.

Behold, a Runge-Kutta method in fucking Javascript (p.s it didn't worked at time because I messed up the values, did it again now because it was bothering me and because I'm dying of pain:

Array.prototype.last = function() {
return this[this.length - 1];
};

//@unused
function discretize(min, max, pass) {
var len = (max - min)/pass + 1, arr = new Array(len);
for(var i = 0; i < len; i++) {
arr[i] = min + pass*i;
}
return arr;
}

function problem(params) {
return Math.pow(Math.E, -params.y);
}

function invert(f) {
return function(params) {
return 1/f(params);
};
}

function rk_form(f, h) {
return function(params) {
return h*f(params);
};
}

function next_K(accum, c, h, xn, yn, rk_f) {
accum.push(rk_f({
x: xn + c*h,
y: yn + c*accum.last()
}));
return accum;
}

function reduce_next_K(h, xn, yn, rk_f) {
return function(accum, c) {
return next_K(accum, c, h, xn, yn, rk_f);
};
}

function generate_Ks(f, h, xn, yn) {
var rk_f = rk_form(f, h);
return [0.5, 0.5, 1.0].reduce(
reduce_next_K(h, xn, yn, rk_f),
[rk_f({
x: xn,
y: yn
})]);
}

function sum_Ks(k_arr) {
return (k_arr[0] + 2*k_arr[1] + 2*k_arr[2] + k_arr[3])/6;
}

function runge_kutta_4_next(f, h, xn, yn) {
return sum_Ks(generate_Ks(f, h, xn, yn));
}

function runge_kutta_4(f, h, x0, xn, y0) {
var x = x0, y = y0;
console.log(x, " -> ", y);
while(x < xn) {
y += runge_kutta_4_next(f, h, x, y);
x += h;
console.log(x, " -> ", y);
}
}


Runnable code here:
http://repl.it/N48/1

Name: Anonymous 2014-01-08 4:39

>>152
(f = fopen(*++argv, "r")) || error("fopen", "Couldn't open %s", *argv);

The CLEVEREST CODE EVER, because a fucking if statement is too imperative, ick

Name: Anonymous 2014-01-08 14:10

>>171
People use logical ands and ors in order to reduce the length of code and improve readability all the time, even in C. Anyone reading that knows exactly what's going on in less code.

And sure, I took it from perl where it's common to write things like open(...) || die $!.

I'm still questioning whether it's ok C programming to write things like that.

Name: Anonymous 2014-01-08 15:15

>>172
There is no such thing as "ok C programming", and I will stand by that statement until someone shows me an open source static analyzer that can detect every instance of potential undefined behaviour.

Name: Anonymous 2014-01-08 16:45

>>173

lol... a program that can detect all instances of undefined behavior would solve the halting problem. in the meantime, clang -Wall does well enough

Name: Anonymous 2014-01-08 17:18

>>173
The burden is on you to to come up with the potentially undefined behaviors because I happen to know none exist. Order of evaluation for && and || is guaranteed for a reason.

Name: Anonymous 2014-01-08 18:59


def _scan(self, chan, nick, msg):
store = json.load(open(FNAME))
delta = {}

for nick_ in re.findall('([a-zA-Z0-9]+)\+\+', msg):
nick_ = nick_.lower()
if nick_ == nick: continue
delta[nick_] = delta.get(nick_, 0) + 1

for nick_ in re.findall('([a-zA-Z0-9]+)\-\-', msg):
nick_ = nick_.lower()
if nick_ == nick: continue
delta[nick_] = delta.get(nick_, 0) - 1

for nick_ in sorted(delta.keys()):
store[nick_] = store.get(nick_, 0) + delta[nick_]
helpers.msg(self.client, chan, '%s now has %d points of karma.'
% (nick_.lower(), store[nick_]))

json.dump(store, open(FNAME, 'w'))

Name: Anonymous 2014-01-08 20:40

>>174
It's debatable if a program that may have undefined behavior should be allowed to be used. Like indexing outside the bounds of an array. But in order for a compiler to check these conditions tractably, a different language than c might be more appropriate. Explicit dependent types would be helpful. Otherwise the checker is essentially doing dependent typing inference...and looking for conflicting types...which is possible I'm sure but probably kind of hard...it reduces to the halting problem pretty trivially, but if you can get it to the point where the unprovable cases are questionable enough to not be accepted in a program, then that's good enough...

Name: Anonymous 2014-01-08 21:17

>>177
What are you going on about? Who are you to tell me whether my programs should be ``allowed to be used''? C can be used to write both portable and non-portable software, and that's part of its usefulness. If you want to write code in a langauge that has no undefined behavior, then go do so - I'll tell you right now that there are different languages most certainly more appropriate than C. But don't presume to tell the rest of us what to do just because you can't handle the fact that somewhere, somebody might be writing str[-1].

Name: >>173; not >>177 2014-01-08 23:03

>>178
But don't presume to tell the rest of us what to do just because you can't handle the fact that somewhere, somebody might be writing str[-1].
I'm more worried about myself accidentally writing something like that. Well, not as obviously silly as that, of course, but still enough to cause terrible security issues.

Name: Anonymous 2014-01-09 2:38

>>178
What should be allowed to be used is determined by a standard of quality. If someone is relying on out of bounds array indexing to get some effect, I would argue that code isn't reliable and shouldn't be used for anything important (anything at all). These issues usually aren't intentional. Otherwise, if the program is relying upon machine dependent behavior, for instance, the way signed integers overflow, then there should be a way to communicate this to the compiler. That way the compiler can select a way to get the intended behavior on the target platform. If the behavior can't be described in this way, then the programmer can write routines in inline assembly, one for each target platform, and then may invoke these routines from the portable code base. It isn't safe to rely on undefined behavior even if you are only targeting one platform, since subtle changes in the compiler or compiler options may throw off the resulting behavior.

Name: Anonymous 2014-01-09 9:25

>>180
Then, like I said, go fuck off to some language that is not C, only use software not written in C, and don't write any software in C yourself. It sounds very nice to say ``Don't ever rely on undefined behavior'', but sometimes the real world doesn't accomodate that. If you don't allow extraordinary circumstances to be met with extraordinary measures, then you are nothing more than an irritation to those who can deal with such circumstances.

Name: Anonymous 2014-01-09 10:59

A C compiler that does not support -fwrapv and -fno-strict-aliasing is utterly worthless.

Name: Anonymous 2014-01-09 11:31

>>181
If you rely on undefined behavior, your program will function differently depending on the compiler's whim. It's unlikely that the collection of possible behaviors fits within the set of intended ones, as they are all undefined. If you need functionality that goes outside of standard C, then there are platform specific libraries, and many compilers support inline asm. Between those, you should be able to accomplish what you need without invoking undefined behavior. I think I'll need to see an example of what you are referring to. I don't see how constructs like *++a = *++b; help solve real world problems.

Name: Anonymous 2014-01-09 11:44

fuck me, that's not undefined. Here we are. *++a = *a

Name: Anonymous 2014-01-09 13:33

>>183
real world problems
Here you go: You have a [set of] specific hardware target[s], and you have an algorithm in which you need to deal with a range of data, stored in a specific type of memory (think main memory vs flash or such). You want to access a piece of data, and you have a pointer to it, but if your pointer is `far away' from a known location that you just accessed from the hardware, it's faster to just recompute the data from registers, since the formula is simple and known. So you write code like this, where loaded_data and unknown_location reside in this special memory area:

void foo(short *loaded_data, short *unknown_location, short param_a,
short param_b, short *outp, size_t len)
{
/* ... */
skdist = loaded_data - unknown_location;
if (ABS(skdist) > SEEK_CUTOFF) {
/* rewrite to match your idea of `fast enough' as needed */
*outp = (param_a + (param_b * *loaded_data)) / (param_b + 5);
} else {
*outp = *unknown_location;
}
outp++;
unknown_location++;
/* ... */
}


The undefined behavior there is that two pointers which are not to the same array are being subtracted (and probably storing the result, too). Two thing makes this ``okay'': That you actually do have the ability to know what the compiler does in this case, so you know that it won't cause demons to fly out of your nose, and that you have complete control over the build environment for the entire duration of the program's work cycle. Sure, you're locked onto that behavior (in practice: that version of that compiler) for the rest of the time that you would possibly want to compile that program. But that isn't always a big deal. Suppose this program will be burned into a ROM, so that updating the code is impossible, and you know that there will only be one version of the ROM*. Then the program will really only be compiled once [for each target] - and if you control the build environment there's no reason to get fussy over requiring a specific version of a specific compiler.

The upshot is: not all code is portable, and that's not a bad thing. There's a hell of a lot of code that is not intended to work in 20 years when you compile it using the DS9000 compiler. C is more than its public face of ``that hugely portable, performant language that UNIX was written in'', and it shouldn't be restricted to that.

* Yes, that does mean you have to get it right the first time.

Name: Anonymous 2014-01-09 14:01

>>185
I think this example is ok by the standards listed in >>183. The only thing undefined (correct me if I'm wrong, I have not red da standard (because I am poor and not important enough to own a copy of it)) is the value of skdist. If this value was used for something like indexing in an array, that would be bad because it's value would be unpredictable, but it's just used in an if condition. Also, both branches of the if condition achieve the same end result, while one is more efficient than the other depending on details of the underlying machine and the meaning of skdist. So from the point of view of the caller, foo behaves the same in all cases, or at least it should write the same meaningful value to outp in all cases, despite invoking undefined behavior in its interior. From a correctness point of view, it's fine. I guess I was referring more to undefined behavior affecting correctness, although there are probably some reasonable examples there as well. Like atomic assignment. Although things like that should at least be wrapped in macros.

Name: Anonymous 2014-01-09 16:08

Stop saging your posts when they are actually worth reading, for fuck's sake.

Name: Anonymous 2014-01-09 16:26

>>186
The entire program after the subtraction is undefined behavior. All of it. From the point of the view of the caller, a C compiler that made foo print ``GOODBYE WORLD'' would be conforming and valid. So would a compiler that made that program spawn a new thread, and 35.6 seconds after the subraction, execs dd if=/dev/zero of=/dev/sda. That's what undefined behavior means, so you can't say ``this undefined behavior is just a little undefined.'' So that function relies on undefined behavior because it relies on the program not spontaneously turning into a text editor when foo is called. That is the `correctness' dependency on undefined behavior.

Name: Anonymous 2014-01-09 16:53

>>188
Well that's pretty silly. I'm trying to think of a hypothetical machine where a really undefined result would make sense. Maybe it allocates arrays in hardware assisted memory banks, and then if it attempts to subtract addresses that point to two different banks, there is a hardware failure and the machine catches on fire.

>>189
Thanks uguuu~

Name: >>189 2014-01-09 16:54

I meana >>187 thanks ugu.

Name: Anonymous 2014-01-09 17:21

>>189
The C compiler I wrote back when I was 12 years old generated a HCF instruction whenever it encountered undefined behaviour.

Name: Anonymous 2014-01-09 18:36

>>189
It's not silly at all - it allows you to reason about C without being a silly STACK BOI. Ironically, that kind of lack of information about, say, pointer representation, is what allows C to be so portable in the first place.

Name: Anonymous 2017-07-14 22:16

Plugin.prototype.verifyNickname = function (msg: string, cb: boolean): void {
let con: object = this.con,
nickname: string = msg[0];

if (!nickname) cb(false);

let error: number = setTimeout(function(){cb(false)}, 3000);

con.raw('STATUS '+nickname);

con.once('status', function (nick: string, result: string){
clearTimeout(error);
if (~~result !== 3) cb(false);
else cb(true);
});
}

Name: Anonymous 2017-07-14 23:03

>>192
Ironically, that undefined behavior was created by ANSI in 1989 and was not part of the original vision and purpose of C or why it was portable in the first place.

Name: Anonymous 2017-07-15 10:59

splitByHour =
let f h depth =
let hourOf = .time >> Date.fromTime >> Date.hour in
List.partition (hourOf >> (>) h) >> \(less, more) ->
if (h // 3) % 2 == 0 then
let d = depth // 2 in
Dict.union
(f (h - d) d less)
(f (h + d) d more)

else
Dict.fromList
[ h => List.sortBy .time more
, (h - 3) => List.sortBy .time less
]
in f 12 12

Name: Anonymous 2017-07-15 15:00

function permbl(p){
return `<button title="Permanently remove from this listing" class ="sub1permblock" onclick="window.localStorage.permablock+=',${p}';window.forcecssreload=3000;window.permablockrefresh=1;">X</button>` ;}

Name: Anonymous 2017-07-15 15:06


instance Functor PluginT where
fmap = undefined

instance Applicative PluginT where
pure x = undefined
(<*>) = undefined

instance Monad PluginT where
(>>=) = undefined

Name: Anonymous 2017-07-15 18:57

>>197
Is that part of a C to Haskell compiler?

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