int find_WKB_typeid(PGconn *conn) { PGresult *dbresult; char *num; if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "no connection to db\n"); exit_nicely(conn); } dbresult = PQexec(conn, "select OID from pg_type where typname = 'bytea';"); if (PQresultStatus(dbresult) != PGRES_TUPLES_OK) { fprintf(stderr, "couldnt execute query to find oid of geometry type"); exit_nicely(conn); //command failed } if ( PQntuples(dbresult) != 1) { fprintf(stderr, "query to find oid of geometry didnt return 1 row!"); exit_nicely(conn); } num = PQgetvalue(dbresult, 0, 0); // first row, first field PQclear(dbresult); return ( atoi(num) ); }
void clearSession() { const char *conninfo; PGconn *conn; PGresult *res; conninfo = "dbname=echuraev"; conn = PQconnectdb(conninfo); if (PQstatus(conn) != CONNECTION_OK) { printf ("Connection to database failed: %s\n", PQerrorMessage(conn)); exit_nicely(conn); } res = PQexecParams(conn, "DELETE FROM sessions", 0, NULL, NULL, NULL, NULL, 0); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf ("Cannot remove old sessions: %s\n", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); PQfinish(conn); }
/* * write an array of lines to a file * * This is only used to write text files. Use fopen "w" not PG_BINARY_W * so that the resulting configuration files are nicely editable on Windows. */ static void writefile(char *path, char **lines) { FILE *out_file; char **line; if ((out_file = fopen(path, "w")) == NULL) { fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"), progname, path, strerror(errno)); exit_nicely(); } for (line = lines; *line != NULL; line++) { if (fputs(*line, out_file) < 0) { fprintf(stderr, _("%s: could not write file \"%s\": %s\n"), progname, path, strerror(errno)); exit_nicely(); } free(*line); } if (fclose(out_file)) { fprintf(stderr, _("%s: could not write file \"%s\": %s\n"), progname, path, strerror(errno)); exit_nicely(); } }
static void stop_error_copy(void) { PGresult *res; /* Do we have a copy active? */ if (!CopyErrorActive) return; /* Terminate the copy */ if (PQputCopyEnd(ConnectionError, NULL) != 1) { fprintf(stderr, "COPY_END for import_polygon_error failed: %s\n", PQerrorMessage(ConnectionError)); exit_nicely(); } /* Check the result */ res = PQgetResult(ConnectionError); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "COPY_END for import_polygon_error failed: %s\n", PQerrorMessage(ConnectionError)); PQclear(res); exit_nicely(); } /* Discard the result */ PQclear(res); /* We no longer have an active copy */ CopyErrorActive = 0; return; }
/* * set up an empty config file so we can check config settings by launching * a test backend */ static void set_null_conf(void) { FILE *conf_file; char *path; path = pg_malloc(strlen(pg_data) + 17); if (is_gtm) sprintf(path, "%s/gtm.conf", pg_data); else sprintf(path, "%s/gtm_proxy.conf", pg_data); conf_file = fopen(path, PG_BINARY_W); if (conf_file == NULL) { fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"), progname, path, strerror(errno)); exit_nicely(); } if (fclose(conf_file)) { fprintf(stderr, _("%s: could not write file \"%s\": %s\n"), progname, path, strerror(errno)); exit_nicely(); } free(path); }
int main(int argc, char** argv) { CvSeq* comp = 0; CvRect window, eye; int key, nc, found; int text_delay, stage = STAGE_INIT; init(); while (key != 'q') { frame = cvQueryFrame(capture); if (!frame) exit_nicely("cannot query frame!"); frame->origin = 0; if (stage == STAGE_INIT) window = cvRect(0, 0, frame->width, frame->height); cvCvtColor(frame, gray, CV_BGR2GRAY); nc = get_connected_components(gray, prev, window, &comp); if (stage == STAGE_INIT && is_eye_pair(comp, nc, &eye)) { delay_frames(5); cvSetImageROI(gray, eye); cvCopy(gray, tpl, NULL); cvResetImageROI(gray); stage = STAGE_TRACKING; text_delay = 10; } if (stage == STAGE_TRACKING) { found = locate_eye(gray, tpl, &window, &eye); if (!found || key == 'r') stage = STAGE_INIT; if (is_blink(comp, nc, window, eye)){ text_delay = 10; system("/bin/bash ./blinked.sh"); } DRAW_RECTS(frame, diff, window, eye); DRAW_TEXT(frame, "blink!", text_delay, 1); } cvShowImage(wnd_name, frame); cvShowImage(wnd_debug, diff); prev = (IplImage*)cvClone(gray); key = cvWaitKey(15); } exit_nicely(NULL); }
/** * Initialize images, memory, and windows */ void init() { char* msg[] = { "Blink Detection 1.0", "Copyright (c) 2009", "http://nashruddin.com", "Press 'q' to quit...", "Press 'r' to restart...", "Have fun!" }; int delay, i; capture = cvCaptureFromCAM(0); if (!capture) exit_nicely("Cannot initialize camera!"); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT); frame = cvQueryFrame(capture); if (!frame) exit_nicely("cannot query frame!"); cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.4, 0.4, 0, 1, 8); cvNamedWindow(wnd_name, 1); for (delay = 20, i = 0; i < 6; i++, delay = 20) while (delay) { frame = cvQueryFrame(capture); if (!frame) exit_nicely("cannot query frame!"); DRAW_TEXT(frame, msg[i], delay, 0); cvShowImage(wnd_name, frame); cvWaitKey(30); } storage = cvCreateMemStorage(0); if (!storage) exit_nicely("cannot allocate memory storage!"); kernel = cvCreateStructuringElementEx(3, 3, 1, 1, CV_SHAPE_CROSS, NULL); gray = cvCreateImage(cvGetSize(frame), 8, 1); prev = cvCreateImage(cvGetSize(frame), 8, 1); diff = cvCreateImage(cvGetSize(frame), 8, 1); tpl = cvCreateImage(cvSize(TPL_WIDTH, TPL_HEIGHT), 8, 1); if (!kernel || !gray || !prev || !diff || !tpl) exit_nicely("system error."); gray->origin = frame->origin; prev->origin = frame->origin; diff->origin = frame->origin; cvNamedWindow(wnd_debug, 1); }
static void ecpg_filter(const char *sourcefile, const char *outfile) { /* * Create a filtered copy of sourcefile, replacing #line x * "./../bla/foo.h" with #line x "foo.h" */ FILE *s, *t; char linebuf[LINEBUFSIZE]; s = fopen(sourcefile, "r"); if (!s) { fprintf(stderr, "Could not open file %s for reading\n", sourcefile); exit_nicely(2); } t = fopen(outfile, "w"); if (!t) { fprintf(stderr, "Could not open file %s for writing\n", outfile); exit_nicely(2); } while (fgets(linebuf, LINEBUFSIZE, s)) { /* check for "#line " in the beginning */ if (strstr(linebuf, "#line ") == linebuf) { char *p = strchr(linebuf, '"'); char *n; int plen = 1; while (*p && (*(p + plen) == '.' || strchr(p + plen, '/') != NULL)) { plen++; } /* plen is one more than the number of . and / characters */ if (plen > 1) { n = (char *) malloc(plen); strncpy(n, p + 1, plen - 1); n[plen - 1] = '\0'; replace_string(linebuf, n, ""); } } fputs(linebuf, t); } fclose(s); fclose(t); }
char * encode_to_utf8(char * cstring, int len){ char * newstring = malloc(len+1); //memcpy(newstring,cstring,len); //newstring[len]='\0'; if(!newstring){ printf("Out of memory\n"); exit_nicely(); } // I really just don't care if you are a non-utf8 character // I am going to blast you away int newcursor=0,oldcursor=0; while(oldcursor < len){ if (cstring[oldcursor] < 128 && cstring[oldcursor] > 0){ if(cstring[oldcursor] == '\\' || cstring[oldcursor] == '\''){ newstring[newcursor] = ' '; newcursor++; } else{ newstring[newcursor] = cstring[oldcursor]; newcursor++; } } oldcursor++; } newstring[newcursor] = '\0'; return newstring; }
/* * executeQueryOrDie() * * Formats a query string from the given arguments and executes the * resulting query. If the query fails, this function logs an error * message and calls exit_nicely() to kill the program. */ PGresult * executeQueryOrDie(PGconn *conn, const char *fmt,...) { static char command[8192]; va_list args; PGresult *result; ExecStatusType status; va_start(args, fmt); vsnprintf(command, sizeof(command), fmt, args); va_end(args); pg_log(PG_DEBUG, "executing: %s\n", command); result = PQexec(conn, command); status = PQresultStatus(result); if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK)) { pg_log(PG_REPORT, "DB command failed\n%s\n%s\n", command, PQerrorMessage(conn)); PQclear(result); PQfinish(conn); exit_nicely(true); return NULL; /* Never get here, but keeps compiler happy */ } else return result; }
/* * connectToServer() * * Connects to the desired database on the designated server. * If the connection attempt fails, this function logs an error * message and calls exit_nicely() to kill the program. */ PGconn * connectToServer(ClusterInfo *cluster, const char *db_name) { unsigned short port = cluster->port; char connectString[MAXPGPATH]; PGconn *conn; snprintf(connectString, sizeof(connectString), "dbname = '%s' user = '******' port = %d", db_name, os_info.user, port); conn = PQconnectdb(connectString); if (conn == NULL || PQstatus(conn) != CONNECTION_OK) { pg_log(PG_REPORT, "Connection to database failed: %s\n", PQerrorMessage(conn)); if (conn) PQfinish(conn); exit_nicely(true); } return conn; }
/** * Initialise the persistent cache with NaN values to identify which IDs are valid or not */ static void persistent_cache_expand_cache(osmid_t block_offset) { osmid_t i; struct ramNode * dummyNodes = malloc( READ_NODE_BLOCK_SIZE * sizeof(struct ramNode)); if (!dummyNodes) { fprintf(stderr, "Out of memory: Could not allocate node structure during cache expansion\n"); exit_nicely(); } ramNodes_clear(dummyNodes, READ_NODE_BLOCK_SIZE); /* Need to expand the persistent node cache */ if (lseek64(node_cache_fd, cacheHeader.max_initialised_id * sizeof(struct ramNode) + sizeof(struct persistentCacheHeader), SEEK_SET) < 0) { fprintf(stderr, "Failed to seek to correct position in node cache: %s\n", strerror(errno)); exit_nicely(); }; for (i = cacheHeader.max_initialised_id >> READ_NODE_BLOCK_SHIFT; i <= block_offset; i++) { if (write(node_cache_fd, dummyNodes, READ_NODE_BLOCK_SIZE * sizeof(struct ramNode)) < READ_NODE_BLOCK_SIZE * sizeof(struct ramNode)) { fprintf(stderr, "Failed to expand persistent node cache: %s\n", strerror(errno)); exit_nicely(); } } cacheHeader.max_initialised_id = ((block_offset + 1) << READ_NODE_BLOCK_SHIFT) - 1; if (lseek64(node_cache_fd, 0, SEEK_SET) < 0) { fprintf(stderr, "Failed to seek to correct position in node cache: %s\n", strerror(errno)); exit_nicely(); }; if (write(node_cache_fd, &cacheHeader, sizeof(struct persistentCacheHeader)) != sizeof(struct persistentCacheHeader)) { fprintf(stderr, "Failed to update persistent cache header: %s\n", strerror(errno)); exit_nicely(); } free(dummyNodes); fsync(node_cache_fd); }
char * argv_to_label(char * cstring, int len, int argc){ int item_count = 0; int quote_count = 0; for (int n = 0; n < len; n++){ if(cstring[n] == 0) item_count++; else if(cstring[n] == '\"' || cstring[n] == '\'') quote_count++; } // For argv item1\0item2\0item3="escaped quotes"\0 // Format is '{"item1","item2","item3=\"escaped quotes\"}' int newlength = 2 + len + item_count * 3 + quote_count * 2; char * newstring = malloc(newlength); if(!newstring){ printf("Out of memory\n"); exit_nicely(); } int newcursor = 0; int oldcursor = 0; while(oldcursor < len && newcursor < MAXENVLEN){ if(cstring[oldcursor] != 0){ // Escape quotation marks if(cstring[oldcursor] == '\"' || cstring[oldcursor] == '\''){ newstring[newcursor] = '\\'; newcursor++; newstring[newcursor] = '\\'; newcursor++; cstring[oldcursor] = '\"'; } // Replace non-UTF8 encoded bytes with a space else if (cstring[oldcursor] >= 128 || cstring[oldcursor] < 0) cstring[oldcursor] = ' '; newstring[newcursor] = cstring[oldcursor]; //printf("(%c,%d)\n",newstring[newcursor],newstring[newcursor]); newcursor++; } // If we encounter a null terminator it marks a new item or EOL // If new item else if(cstring[oldcursor] == 0 && oldcursor < len-1) { argc -= 1; if(argc == 0){ newstring[newcursor] = '\0'; return newstring; } newstring[newcursor] = ' '; newcursor ++; } oldcursor++; } // If EOL newstring[newcursor] = '\0'; return newstring; }
/* * start an isolation tester process for specified file (including * redirection), and return process ID */ static PID_TYPE isolation_start_test(const char *testname, _stringlist ** resultfiles, _stringlist ** expectfiles, _stringlist ** tags) { PID_TYPE pid; char infile[MAXPGPATH]; char outfile[MAXPGPATH]; char expectfile[MAXPGPATH]; char psql_cmd[MAXPGPATH * 3]; size_t offset = 0; /* * Look for files in the output dir first, consistent with a vpath search. * This is mainly to create more reasonable error messages if the file is * not found. It also allows local test overrides when running pg_regress * outside of the source tree. */ snprintf(infile, sizeof(infile), "%s/specs/%s.spec", outputdir, testname); if (!file_exists(infile)) snprintf(infile, sizeof(infile), "%s/specs/%s.spec", inputdir, testname); snprintf(outfile, sizeof(outfile), "%s/results/%s.out", outputdir, testname); snprintf(expectfile, sizeof(expectfile), "%s/expected/%s.out", outputdir, testname); if (!file_exists(expectfile)) snprintf(expectfile, sizeof(expectfile), "%s/expected/%s.out", inputdir, testname); add_stringlist_item(resultfiles, outfile); add_stringlist_item(expectfiles, expectfile); if (launcher) offset += snprintf(psql_cmd + offset, sizeof(psql_cmd) - offset, "%s ", launcher); snprintf(psql_cmd + offset, sizeof(psql_cmd) - offset, SYSTEMQUOTE "./isolationtester \"dbname=%s\" < \"%s\" > \"%s\" 2>&1" SYSTEMQUOTE, dblist->str, infile, outfile); pid = spawn_process(psql_cmd); if (pid == INVALID_PID) { fprintf(stderr, _("could not start process for test %s\n"), testname); exit_nicely(2); } return pid; }
static void require_slim_mode(void) { if (!Options->slim) { fprintf(stderr, "Cannot apply diffs unless in slim mode\n"); exit_nicely(); } return; }
int main() { PGconn *conn = NULL; PGresult * res = NULL; int i=0, rec_count=0; /* Connect to database */ conn = PQsetdbLogin(NULL, NULL, NULL, NULL, DB_NAME, DB_USER, DB_PASSWORD); if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "Connection to database \"%s\" failed.\n", DB_NAME); fprintf(stderr, "%s", PQerrorMessage(conn)); exit_nicely(conn); } /* */ res = PQexec(conn, "select * from registered_users"); if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT command did not return tuples properly\n"); PQclear(res); exit_nicely(conn); } /* iterate through res : PQgetvalue(res, line, column) */ rec_count = PQntuples(res); for(i = 0; i < rec_count; i = i + 1) { printf("%s %s\n", PQgetvalue(res, i, 1), PQgetvalue(res, i, 2)); } /* End of connection */ PQclear(res); PQfinish(conn); return 0; }
void openConn(const char *conninfo, PGconn **conn) { *conn = PQconnectdb(conninfo); if (PQstatus(*conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(*conn)); exit_nicely(*conn); } }
/* * Fail and die, with a message to stderr. Parameters as for write_msg. */ void exit_horribly(const char *modulename, const char *fmt,...) { va_list ap; va_start(ap, fmt); vwrite_msg(modulename, fmt, ap); va_end(ap); exit_nicely(1); }
/* * Run permutations given in the test spec */ static void run_named_permutations(TestSpec * testspec) { int i, j; int n; int nallsteps; Step **allsteps; /* First create a lookup table of all steps */ nallsteps = 0; for (i = 0; i < testspec->nsessions; i++) nallsteps += testspec->sessions[i]->nsteps; allsteps = malloc(nallsteps * sizeof(Step *)); n = 0; for (i = 0; i < testspec->nsessions; i++) { for (j = 0; j < testspec->sessions[i]->nsteps; j++) allsteps[n++] = testspec->sessions[i]->steps[j]; } qsort(allsteps, nallsteps, sizeof(Step *), &step_qsort_cmp); for (i = 0; i < testspec->npermutations; i++) { Permutation *p = testspec->permutations[i]; Step **steps; steps = malloc(p->nsteps * sizeof(Step *)); /* Find all the named steps using the lookup table */ for (j = 0; j < p->nsteps; j++) { Step **this = (Step **) bsearch(p->stepnames[j], allsteps, nallsteps, sizeof(Step *), &step_bsearch_cmp); if (this == NULL) { fprintf(stderr, "undefined step \"%s\" specified in permutation\n", p->stepnames[j]); exit_nicely(); } steps[j] = *this; } /* And run them */ run_permutation(testspec, p->nsteps, steps); free(steps); } }
char *pl_read(PGconn *conn) { // Sleep until something happens on the connection. We use select(2) //to wait for input, but you could also use poll() or similar // facilities. int sock; fd_set input_mask; PGnotify *notify; char *not_name; sock = PQsocket(conn); if (sock < 0) { fprintf(stderr, "shouldn't happen: sock < 0"); exit_nicely(conn); } FD_ZERO(&input_mask); FD_SET(sock, &input_mask); try_again: if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0) { fprintf(stderr, "select() failed: %s\n", strerror(errno)); exit_nicely(conn); } // Now check for input PQconsumeInput(conn); if ((notify = PQnotifies(conn)) != NULL) { fprintf(stderr, "ASYNC NOTIFY of '%s' received from backend pid %d\n", notify->relname, notify->be_pid); not_name = (char *)malloc((strlen(notify->relname) + 1) * sizeof(char)); strcpy(not_name, notify->relname); PQfreemem(notify); return not_name; } else { goto try_again; } }
int main(int argc, char **argv) { const char *conninfo; PGconn *conn; PGresult *res; if (argc > 1) conninfo = argv[1]; else conninfo = "dbname = minak"; /* Begin the connection/transaction */ conn = PQconnectdb(conninfo); if (PQstatus(conn) != CONNECTION_OK) { exit_nicely(conn); } res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { PQclear(res); exit_nicely(conn); } PQclear(res); /* Main body */ char *method = getenv("REQUEST_METHOD"); if (method == NULL) { /* do nothing */ } else if (strcasecmp(method, "POST") == 0) { upload(0, conn); } else if (strcasecmp(method, "GET") == 0) { int id = atoi(getenv("QUERY_STRING")); download(1, conn, id); } /* End the connection/transaction */ res = PQexec(conn, "END"); PQclear(res); PQfinish(conn); return 0; }
void _pabort(const char *s) { if (s) { //perror(orig_buf); psyslog("%s :STACK:", s); } print_stack(); #ifdef MINERGATE exit_nicely(0, "apAbort"); #else exit(0); #endif }
PGresult *exec(PGconn *conn, char* stmt, int expectedStatus) { PGresult *res; res = PQexec(conn, stmt); if (PQresultStatus(res) != expectedStatus) { fprintf(stderr, "failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } return res; }
void begin(PGconn *conn) { PGresult *res; res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); }
/* Register a callback to be run when exit_nicely is invoked. */ void on_exit_nicely(on_exit_nicely_callback function, void *arg) { if (on_exit_nicely_index >= MAX_ON_EXIT_NICELY) { pg_log_fatal("out of on_exit_nicely slots"); exit_nicely(1); } on_exit_nicely_list[on_exit_nicely_index].function = function; on_exit_nicely_list[on_exit_nicely_index].arg = arg; on_exit_nicely_index++; }
struct binary_search_array * init_search_array(int capacity) { struct binary_search_array * array = calloc(1, sizeof(struct binary_search_array)); array->array = calloc(capacity + 1, sizeof(struct key_val_tuple)); if (!array->array) { fprintf(stderr, "Out of memory trying to allocate %li bytes for binary search array\n", ((capacity + 1) * sizeof(struct key_val_tuple))); exit_nicely(); } array->capacity = capacity; array->size = 0; return array; }
/* * call exit_nicely() if we got a signal, or else output "ok". */ static void check_ok(void) { if (caught_signal) { printf(_("caught signal\n")); fflush(stdout); exit_nicely(); } else if (output_failed) { printf(_("could not write to child process: %s\n"), strerror(output_errno)); fflush(stdout); exit_nicely(); } else { /* all seems well */ printf(_("ok\n")); fflush(stdout); } }
PGconn *pl_connect(const char *conninfo) { PGconn *conn; fprintf(stderr,"connectdb %s\n", conninfo); conn = PQconnectdb(conninfo); // Check to see that the backend connection was successfully made if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); } return conn; }
void realloc_members(struct osmdata_t *osmdata) { if( osmdata->member_max == 0 ) osmdata->member_max = INIT_MAX_NODES; else osmdata->member_max <<= 1; osmdata->members = realloc( osmdata->members, osmdata->member_max * sizeof( osmdata->members[0] ) ); if( !osmdata->members ) { fprintf( stderr, "Failed to expand member list to %d\n", osmdata->member_max ); exit_nicely(); } }
/** * Delay for the specified frame count. I have to write this custom * delay function for these reasons: * - usleep() is not available in Windows * - usleep() and Sleep() will freeze the video for the given interval */ void delay_frames(int nframes) { int i; for (i = 0; i < nframes; i++) { frame = cvQueryFrame(capture); if (!frame) exit_nicely("cannot query frame"); cvShowImage(wnd_name, frame); if (diff) cvShowImage(wnd_debug, diff); cvWaitKey(30); } }