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!
Any QUALITY is allowed. No bullying!
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);
}
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]);
}
}
def sprunge(text):
text = text.encode('utf-8')
params = urllib.urlencode({'sprunge': text})
paste = urllib.urlopen('http://sprunge.us', params).read()
return paste.lstrip(' ')
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);
}
}
}
#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;
}
function j() {
iframe = document.createElement('IFRAME');
while (true) {
document.appendChild(iframe)
}
return null;
}
#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);
}
void printhello() {
printf("hello.");
}
$ 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))
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.')
void Timer::Stop()
{
enabled = false;
stopEvent.Set();
}
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;
}
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);
}
}
}
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
#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;
}
#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;
}
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;
}
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();
}
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;
bool check_faggot(int post_number)
{
if(post_number == 1) return true;
else return false;
}
post_number = 1;
printf(">>%d is ", post_number);
if(check_faggot(post_number) == 0)
{
printf("not ");
}
printf("a faggot.");
ifM p x y = p >>= \p -> if p then x
else y
ifO p x = if p then x
else return ()
mapLines f = unlines . map f . lines
int main = 5;
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};
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 ]
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
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;
}
$s =~ tr/「」『』()。、・/''""()., /;
# and any of these:
# https://en.wikipedia.org/wiki/Japanese_typographic_symbols
#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;
}
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
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;
}
matrix =
[1 2 3
4 5 6
7 8 9]
>> matrix[1] == [1 2 3]
True
>> 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.
[]
instead of ()
for function calls.
mat = [1,2,3; 4,5,6; 7,8,9];
mat(1,:) == [1,2,3]
[1, 1, 1] %'(logical type)
[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.
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);
}
}
//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;
}
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,
];
},
};
})();
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
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
* 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.
SHIP-CHAR-IDXUgh, you shippers now need lookup systems just to remember who you're shipping this season? Disgusting, all of you.
/**
* 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);
}
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
def setcolor(label, color):
if label and color:
fgcolors[label] = color
#!/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;
}
}
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');
#!/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;
}
sudo time cat /dev/sdb9 | grep -Uboa -P `xxd -l14 -p 1.dat |sed 's/../\0\\x/g'` | tee search
#!/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;
}
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)
#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;
}
$ 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
def add5(x)
return x + 5;
y f = f $ y f
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++;
}
twojar = @(x, y, z) x(z(y));
ycell = @(a, b, x, y, z) z(x(a) !xor! y(b))
int
main (int argc, char *argv[])
{
return EXIT_SUCCESS;
}
#include <stdlib.h>
int
main(
int argc,
char **argv
)
{
return(EXIT_SUCCESS);
}
calloc
changes in the middle of me programming and I don't think to re-check the manpage?
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! */
}
#include <stdio.h>
int main(int argc, char** argv) {
int byte;
for(;; byte++) {
fputc(byte << (byte >> (byte >> 7)), stdout);
}
}
`
>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
$ cat autostudy2.sh
while true
do
espeak <terms.txt
done
int
one (void)
{
return 1;
}
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
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;
}
'\0'
check, even though the point of the method is to avoid conversion. 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? ... An integer character constant has type int
#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;
}
Yeah, once you think about it, it somehow makes sense:... An integer character constant has type int
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.char
can be signed or unsigned; this usually just annoys me and is probably one of my main uses of union
...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;
}
#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);
}
while((c = fgetc(f)) != EOF)in a system where char is unsigned and sizeof (char) == sizeof (int) EOF is a vaild character
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 problemvoid *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]);
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 voidI 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, putcharI 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 StyleGNU Style is shit.
Your scenario is ridiculouswhy?
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, 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''
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);
});
};
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);
}
}
(f = fopen(*++argv, "r")) || error("fopen", "Couldn't open %s", *argv);
open(...) || die $!
.
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'))
str[-1]
. 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.
*++a = *++b;
help solve real world problems. *++a = *a
real world problemsHere 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++;
/* ... */
}
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. HCF
instruction whenever it encountered undefined behaviour. 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);
});
}
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
instance Functor PluginT where
fmap = undefined
instance Applicative PluginT where
pure x = undefined
(<*>) = undefined
instance Monad PluginT where
(>>=) = undefined