void flux_cli_del(flux_cli_t * client) { if(client->verbose) printf("Client closed.\n"); for(size_t i = 0; i < client->n_servers; i++) { nn_shutdown(client->servers[i].sock, 0); } client->n_servers = 0; nn_shutdown(client->broker_sock, 0); free(servers_string); free(client); }
ccx_share_status ccx_share_stop() { dbg_print(CCX_DMT_SHARE, "[share] ccx_share_stop: stopping service\n"); nn_shutdown(ccx_share_ctx.nn_sock, ccx_share_ctx.nn_binder); free(ccx_share_ctx.stream_name); return CCX_SHARE_OK; }
JNIEXPORT jint JNICALL Java_org_nanomsg_NanoLibrary_nn_1shutdown(JNIEnv* env, jobject obj, jint socket, jint how) { return nn_shutdown(socket, how); }
/* --- server --- */ int node0(const char *url) { int sz_date = strlen(DATE) + 1; int sock = nn_socket(AF_SP, NN_REP); assert(sock >= 0); assert(nn_bind(sock, url) >= 0); while(1) { char *buf = NULL; int bytes = nn_recv(sock, &buf, NN_MSG, 0); assert(bytes >= 0); if(strncmp(DATE, buf, sz_date) == 0) { printf("NODE0: RECEIVED DATE REQUEST\n"); char *st_date = date(); int sz_date = strlen(st_date) + 1; printf("NODE0: SENDING DATE %s\n", st_date); bytes = nn_send(sock, st_date, sz_date, 0); assert(bytes == sz_date); } nn_freemsg(buf); } return nn_shutdown(sock, 0); }
/** * Disconnects from a given object key */ void subscribe_socket::disconnect(std::string objectkey) { std::lock_guard<mutex> guard(lock); if (publishers.count(objectkey)) { nn_shutdown(z_socket, publishers[objectkey]); publishers.erase(objectkey); } }
int node (const int argc, const char **argv) { int sock = nn_socket (AF_SP, NN_BUS); assert (sock >= 0); assert (nn_bind (sock, argv[2]) >= 0); sleep (1); // wait for connections if (argc >= 3) { int x=3; for(x; x<argc; x++) assert (nn_connect (sock, argv[x]) >= 0); } sleep (1); // wait for connections int to = 100; assert (nn_setsockopt (sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof (to)) >= 0); // SEND int sz_n = strlen(argv[1]) + 1; // '\0' too printf ("%s: SENDING '%s' ONTO BUS\n", argv[1], argv[1]); int send = nn_send (sock, argv[1], sz_n, 0); assert (send == sz_n); while (1) { // RECV char *buf = NULL; int recv = nn_recv (sock, &buf, NN_MSG, 0); if (recv >= 0) { printf ("%s: RECEIVED '%s' FROM BUS\n", argv[1], buf); nn_freemsg (buf); } } return nn_shutdown (sock, 0); }
int node1(const char *url) { int sock = nn_socket(AF_SP, NN_PAIR); assert(sock >= 0); assert(nn_connect(sock, url) >= 0); send_recv(sock, NODE1); return nn_shutdown (sock, 0); }
static int nn_really_shutdown(int s, int how) { int result; do { result = nn_shutdown(s, how); } while (result == -1 && nn_errno() == EINTR); return result; }
/* --- client --- */ int node1(const char *url, const char *msg) { int sz_msg = strlen(msg) + 1; // '\0' too int sock = nn_socket(AF_SP, NN_PUSH); assert(sock >= 0); assert(nn_connect (sock, url) >= 0); printf("NODE1: SENDING \"%s\"\n", msg); int bytes = nn_send(sock, msg, sz_msg, 0); assert(bytes == sz_msg); return nn_shutdown(sock, 0); }
static PyObject *sockShutdown(sock_t *self) { if (self->sock == -1 || self->endpoint == -1) return NULL; if (nn_shutdown(self->sock, self->endpoint) != 0){ ERR; return NULL; } self->endpoint = -1; Py_RETURN_NONE; }
static void ocnotify_newmail(TALLOC_CTX *mem_ctx, struct ocnotify_private ocnotify, uint32_t count, const char **hosts, const char *data) { enum mapistore_error retval; int sock; int endpoint; int i; int bytes; int timeout; int rc; uint8_t *blob = NULL; size_t msglen; if (ocnotify.backend == NULL) { oc_log(OC_LOG_ERROR, "No backend specified"); exit (1); } retval = mapistore_notification_payload_newmail(mem_ctx, ocnotify.backend, (char *)data, ocnotify.dstfolder, ocnotify.sep, &blob, &msglen); if (retval != MAPISTORE_SUCCESS) { oc_log(OC_LOG_ERROR, "unable to generate newmail payload"); exit (1); } sock = nn_socket(AF_SP, NN_PUSH); if (sock < 0) { oc_log(OC_LOG_FATAL, "unable to create socket"); exit (1); } timeout = 200; rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &timeout, sizeof(timeout)); if (rc < 0) { oc_log(OC_LOG_WARNING, "unable to set timeout on socket send"); } for (i = 0; i < count; i++) { endpoint = nn_connect(sock, hosts[i]); if (endpoint < 0) { oc_log(OC_LOG_ERROR, "unable to connect to %s", hosts[i]); ocnotify_flush(ocnotify, hosts[i]); continue; } bytes = nn_send(sock, (char *)blob, msglen, 0); if (bytes != msglen) { oc_log(OC_LOG_WARNING, "Error sending msg: %d sent but %d expected", bytes, msglen); } oc_log(OC_LOG_INFO, "message sent to %s", hosts[i]); nn_shutdown(sock, endpoint); } }
int node (const int argc, const char **argv) { int sock = nn_socket (AF_SP, NN_BUS); int sock_fd, efd, nfds; struct epoll_event event, events[MAX_EVENTS]; size_t sz = sizeof(sock_fd); nn_getsockopt(sock, NN_SOL_SOCKET, NN_RCVFD, &sock_fd, &sz); assert(sock >= 0); assert(nn_bind (sock, argv[2]) >= 0); sleep (1); // wait for connections if (argc >= 3) { int x; for(x = 3; x < argc; x++) assert(nn_connect(sock, argv[x]) >= 0); } efd = epoll_create(MAX_EVENTS); assert(efd != -1); event.data.fd = sock_fd; event.events = EPOLLIN; assert(epoll_ctl(efd, EPOLL_CTL_ADD, sock_fd, &event) != -1); // wait for connections sleep(1); int to = 100; assert(nn_setsockopt (sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof(to)) >= 0); // SEND int sz_n = strlen(argv[1]) + 1; // '\0' too printf ("%s: SENDING '%s' ONTO BUS\n", argv[1], argv[1]); int send = nn_send (sock, argv[1], sz_n, 0); assert (send == sz_n); for(;;) { nfds = epoll_wait(efd, events, MAX_EVENTS, -1); assert(nfds != -1); int n, recv; for (n = 0; n < nfds; ++n) { if (events[n].data.fd == sock_fd) { char *buf = NULL; recv = nn_recv(sock, &buf, NN_MSG, 0); if (recv >= 0) { printf ("%s: RECEIVED '%s' FROM BUS\n", argv[1], buf); nn_freemsg (buf); } } } } return nn_shutdown (sock, 0); }
void process_json(cJSON *json,char *remoteaddr,int32_t localaccess) { int32_t sock,len,checklen,sendtimeout,recvtimeout; uint32_t apitag; uint64_t tag; char endpoint[128],numstr[64],*resultstr,*jsonstr; jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' '); len = (int32_t)strlen(jsonstr)+1; apitag = _crc32(0,jsonstr,len); sprintf(endpoint,"ipc://api.%u",apitag); free(jsonstr); if ( (recvtimeout= juint(json,"timeout")) == 0 ) recvtimeout = 30000; sendtimeout = 30000; randombytes((uint8_t *)&tag,sizeof(tag)); if ( cJSON_GetObjectItem(json,"tag") == 0 ) sprintf(numstr,"%llu",(long long)tag), cJSON_AddItemToObject(json,"tag",cJSON_CreateString(numstr)); if ( cJSON_GetObjectItem(json,"apitag") == 0 ) cJSON_AddItemToObject(json,"apitag",cJSON_CreateString(endpoint)); if ( remoteaddr != 0 ) cJSON_AddItemToObject(json,"broadcast",cJSON_CreateString("remoteaccess")); if ( localaccess != 0 ) cJSON_AddItemToObject(json,"localaccess",cJSON_CreateNumber(1)); jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' '); //fprintf(stderr,"localacess.%d remote.(%s) jsonstr.(%s)\r\n",localaccess,remoteaddr!=0?remoteaddr:"",jsonstr); len = (int32_t)strlen(jsonstr)+1; if ( jsonstr != 0 ) { if ( (sock= nn_socket(AF_SP,NN_PAIR)) >= 0 ) { if ( sendtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_SNDTIMEO,&sendtimeout,sizeof(sendtimeout)) < 0 ) fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr()); if ( nn_connect(sock,SUPERNET_APIENDPOINT) < 0 ) printf("error connecting to apiendpoint sock.%d type.%d (%s) %s\r\n",sock,NN_PUSH,SUPERNET_APIENDPOINT,nn_errstr()); else if ( (checklen= nn_send(sock,jsonstr,len,0)) != len ) printf("checklen.%d != len.%d for nn_send to (%s)\r\n",checklen,len,SUPERNET_APIENDPOINT); else { if ( recvtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_RCVTIMEO,&recvtimeout,sizeof(recvtimeout)) < 0 ) fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr()); if ( nn_recv(sock,&resultstr,NN_MSG,0) > 0 ) { printf("Content-Length: %ld\r\n\r\n",strlen(resultstr)+2); printf("%s\r\n",resultstr); nn_freemsg(resultstr); } else printf("error getting results %s\r\n",nn_errstr()); } nn_shutdown(sock,0); } else printf("error getting pushsock.%s\r\n",nn_errstr()); } free(jsonstr); }
int server (const char *url) { int sock = nn_socket (AF_SP, NN_PUB); assert (sock >= 0); assert (nn_bind (sock, url) >= 0); while (1) { char *d = date(); int sz_d = strlen(d) + 1; // '\0' too printf ("SERVER: PUBLISHING DATE %s\n", d); int bytes = nn_send (sock, d, sz_d, 0); assert (bytes == sz_d); sleep(1); } return nn_shutdown (sock, 0); }
int testshutdown() { int s; int rc; int eid; printf("test shutdown\n"); /* Run endpoint shutdown and socket shutdown in parallel. */ s = test_socket (AF_SP, NN_REQ); eid = test_connect (s, "tcp://127.0.0.1:5590"); rc = nn_shutdown (s, eid); errno_assert (rc == 0); test_close (s); return 0; }
int node1 (const char *url) { int sz_date = strlen(DATE) + 1; // '\0' too char *buf = NULL; int bytes = -1; int sock = nn_socket (AF_SP, NN_REQ); assert (sock >= 0); assert (nn_connect (sock, url) >= 0); printf ("NODE1: SENDING DATE REQUEST %s\n", DATE); bytes = nn_send (sock, DATE, sz_date, 0); assert (bytes == sz_date); bytes = nn_recv (sock, &buf, NN_MSG, 0); assert (bytes >= 0); printf ("NODE1: RECEIVED DATE %s\n", buf); nn_freemsg (buf); return nn_shutdown (sock, 0); }
int client (const char *url, const char *name) { int sock = nn_socket (AF_SP, NN_SUB); assert (sock >= 0); // TODO learn more about publishing/subscribe keys assert (nn_setsockopt (sock, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) >= 0); assert (nn_connect (sock, url) >= 0); while (1) { char *buf = NULL; int bytes = nn_recv (sock, &buf, NN_MSG, 0); assert (bytes >= 0); printf ("CLIENT (%s): RECEIVED %s\n", name, buf); nn_freemsg (buf); } return nn_shutdown (sock, 0); }
void pnet_socket_destroy(pnet_socket *socket) { if (unlikely(!socket)) { plog_error("pnet_socket_destroy() нет объекта socket"); return; } if (unlikely(!socket->socket_fd)) { return; } nn_shutdown(socket->socket_fd, 0); nn_close(socket->socket_fd); socket->socket_fd = 0; socket->endpoint_id = 0; socket->started = false; }
void process_json(cJSON *json) { int32_t sock,i,len,checklen,sendtimeout,recvtimeout; uint32_t apitag; uint64_t tag; char endpoint[128],*resultstr,*jsonstr; jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' '); //fprintf(stderr,"jsonstr.(%s)\r\n",jsonstr); len = (int32_t)strlen(jsonstr)+1; apitag = _crc32(0,jsonstr,len); sprintf(endpoint,"ipc://api.%u",apitag); free(jsonstr); recvtimeout = get_API_int(cJSON_GetObjectItem(json,"timeout"),10000); sendtimeout = 5000; randombytes(&tag,sizeof(tag)); cJSON_AddItemToObject(json,"tag",cJSON_CreateNumber(tag)); cJSON_AddItemToObject(json,"apitag",cJSON_CreateString(endpoint)); //cJSON_AddItemToObject(json,"timeout",cJSON_CreateNumber(recvtimeout)); jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' '); len = (int32_t)strlen(jsonstr)+1; if ( json != 0 ) { if ( (sock= nn_socket(AF_SP,NN_PAIR)) >= 0 ) { if ( sendtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_SNDTIMEO,&sendtimeout,sizeof(sendtimeout)) < 0 ) fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr()); if ( nn_connect(sock,SUPERNET_APIENDPOINT) < 0 ) printf("error connecting to apiendpoint sock.%d type.%d (%s) %s\r\n",sock,NN_PUSH,SUPERNET_APIENDPOINT,nn_errstr()); else if ( (checklen= nn_send(sock,jsonstr,len,0)) != len ) printf("checklen.%d != len.%d for nn_send to (%s)\r\n",checklen,len,SUPERNET_APIENDPOINT); else { if ( recvtimeout > 0 && nn_setsockopt(sock,NN_SOL_SOCKET,NN_RCVTIMEO,&recvtimeout,sizeof(recvtimeout)) < 0 ) fprintf(stderr,"error setting sendtimeout %s\n",nn_errstr()); if ( nn_recv(sock,&resultstr,NN_MSG,0) > 0 ) { printf("Content-Length: %ld\r\n\r\n",strlen(resultstr)+2); printf("%s\r\n",resultstr); nn_freemsg(resultstr); } else printf("error getting results %s\r\n",nn_errstr()); } nn_shutdown(sock,0); } else printf("error getting pushsock.%s\r\n",nn_errstr()); } free(jsonstr); }
int main (int argc, const char *argv[]) { int s; int rc; int eid; char socket_address[128]; test_addr_from(socket_address, "tcp", "127.0.0.1", get_test_port(argc, argv)); /* Run endpoint shutdown and socket shutdown in parallel. */ s = test_socket (AF_SP, NN_REQ); eid = test_connect (s, socket_address); rc = nn_shutdown (s, eid); errno_assert (rc == 0); test_close (s); return 0; }
int32_t crypto777_peer(struct crypto777_node *nn,struct crypto777_node *peer) { struct crypto777_peer *ptr; int32_t err=0,err2=0,timeout = 1;//,insock; struct crypto777_transport *transport = &nn->transport; if ( nn->numpeers < MAXPEERS ) { ptr = &transport->peers[transport->numpeers++]; printf("%p peer.(%s).%d\n",peer->ip_port,peer->ip_port,peer->transport.port); strcpy(ptr->type,peer->transport.type), strcpy(ptr->ip_port,peer->ip_port), ptr->port = peer->transport.port; //if ( nn_connect(transport->bus,peer->ip_port) < 0 ) // printf("error %d nn_connect.%d bus (%s) | %s\n",err,transport->bus,peer->ip_port,nn_strerror(nn_errno())), getchar(); if ( (ptr->subsock= nn_socket(AF_SP,NN_SUB)) < 0 || (err= nn_setsockopt(ptr->subsock,NN_SUB,NN_SUB_SUBSCRIBE,"",0)) < 0 || (err2= nn_connect(ptr->subsock,ptr->ip_port)) < 0 ) { printf("error %d too many subs.%d nodeid.%d peerid.%d err.%s err.%d err2.%d ip_port.(%s)\n",ptr->subsock,nn->numpeers,nn->nodeid,peer->nodeid,nn_strerror(nn_errno()),err,err2,ptr->ip_port); if ( ptr->subsock >= 0 ) nn_shutdown(ptr->subsock,0); return(-1); } if ( nn_setsockopt(ptr->subsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout)) < 0 ) printf("error setting recv timeout to %d\n",timeout); /*if ( (ptr->pairsock= nn_socket(AF_SP,NN_PAIR)) < 0 ) printf("error %d nn_socket err.%s\n",ptr->pairsock,nn_strerror(nn_errno())); else if ( (err= nn_bind(ptr->pairsock,transport->ip_port)) < 0 ) printf("error %d nn_bind.%d (%s) | %s\n",err,ptr->pairsock,transport->ip_port,nn_strerror(nn_errno())); else if ( nn_connect(ptr->pairsock,peer->ip_port) < 0 ) printf("error %d nn_connect.%d pairsock (%s) | %s\n",err,ptr->pairsock,peer->ip_port,nn_strerror(nn_errno())); if ( nn_setsockopt(ptr->pairsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout)) < 0 ) printf("error setting recv timeout to %d\n",timeout); if ( (insock= nn_socket(AF_SP,NN_PAIR)) < 0 ) printf("error %d nn_socket err.%s\n",insock,nn_strerror(nn_errno())); else if ( (err= nn_bind(insock,peer->ip_port)) < 0 ) printf("error %d nn_bind.%d (%s) | %s\n",err,insock,peer->ip_port,nn_strerror(nn_errno())); else if ( nn_connect(insock,nn->ip_port) < 0 ) printf("error %d nn_connect.%d insock (%s) | %s\n",err,insock,nn->ip_port,nn_strerror(nn_errno())); else peer->transport.insocks[peer->transport.numpairs++] = insock;*/ set_bloombits(&nn->blooms[0],peer->nxt64bits); nn->peers[nn->numpeers++] = peer; return(nn->numpeers); } else return(-1); }
int bus_on(int sock, const char *name) { int to = 100; assert(nn_setsockopt(sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to, sizeof(to)) >= 0); /* SEND */ int sz_n = strlen(name) + 1; printf("%s: SENDING '%s' ONTO BUS\n", name, name); int send = nn_send(sock, name, sz_n, 0); assert (send == sz_n); while (1) { /* RECV */ char *buf = NULL; int recv = nn_recv(sock, &buf, NN_MSG, 0); if (recv >= 0) { printf("%s: RECEIVED '%s' FROM BUS\n", name, buf); nn_freemsg(buf); } } return nn_shutdown(sock, 0); }
int client(const char *url, const char *name) { int sock = nn_socket(AF_SP, NN_SUB); nn_setsockopt(sock, NN_SUB, NN_SUB_SUBSCRIBE, "", 0); nn_connect(sock, url); Sleep(1000); // Subscribe on start char d[] = "Shello."; int sz_d = strlen(&d) + 1; // '\0' too nn_send(sock, &d, sz_d, 0); while (1) { char *buf = NULL; int bytes = nn_recv(sock, &buf, NN_MSG, 0); assert(bytes >= 0); printf("MESSAGE: %s\n", buf); nn_freemsg(buf); } return nn_shutdown(sock, 0); }
int main(const int argc, const char **argv) { int request = nn_socket(AF_SP, NN_REQ); nn_connect(request, BACKROUTER); char msg [100]; char *buf = "ready for work"; sprintf(msg, "%s says ready for work", argv[1]); int i = 0; while(++i < 5){ printf("%s\n",msg); nn_send(request,msg,strlen(msg),0); int n = nn_recv(request,&buf,NN_MSG,0); printf("%s got response %.*s\n", argv[1], n, buf); nn_freemsg(buf); sleep(1); } printf("%s is quitting\n", argv[1]); nn_shutdown(request,0); return 0; }
int server(const char *url) { int sock = nn_socket(AF_SP, NN_PUB); nn_bind(sock, url); char msg[] = "Mhello.world"; int sz_d = strlen(&msg) + 1; // '\0' too while (1) { //char *d = date(); //int sz_d = strlen(d) + 1; // '\0' too //printf("SERVER: PUBLISHING DATE %s\n", d); printf("PUBLISH: '%s'\n", msg); int bytes = nn_send(sock, &msg, sz_d, 0); assert(bytes == sz_d); // Receive and wait char *buf = NULL; nn_recv(sock, &buf, NN_MSG, NN_DONTWAIT); Sleep(1000); } return nn_shutdown(sock, 0); }
int main(int argc, char **argv) { /* These variables are for command-line options. */ double mag = 1.0, etol = 10e-3, detol = 10e-8, rate = 0.1; int seed = 0, minepochs = 10, maxepochs = 100; char *afunc = "tanh", *alg = "cgpr", *srch = "cubic"; /* The OPTION array is used to easily parse command-line options. */ OPTION opts[] = { { "-seed", OPT_INT, &seed, "random number seed" }, { "-minepochs", OPT_INT, &minepochs, "minimum # of training steps" }, { "-maxepochs", OPT_INT, &maxepochs, "maximum # of training steps" }, { "-afunc", OPT_STRING, &afunc, "act. function for hidden node"}, { "-mag", OPT_DOUBLE, &mag, "max size of initial weights" }, { "-etol", OPT_DOUBLE, &etol, "error tolerance" }, { "-detol", OPT_DOUBLE, &detol, "delta error tolerance" }, { "-rate", OPT_DOUBLE, &rate, "learning rate" }, { "-alg", OPT_STRING, &alg, "training algorithm" }, { "-srch", OPT_STRING, &srch, "line search" }, { NULL, OPT_NULL, NULL, NULL } }; /* The DATASET and the NN that we will use. */ DATASET *data; NN *nn; /* Get the command-line options. */ get_options(argc, argv, opts, help_string, NULL, 0); /* Set the random seed. */ srandom(seed); nn = nn_create("4 2 4"); /* 2-2-1 architecture. */ nn_link(nn, "0 -l-> 1"); /* Inputs to hidden link. */ nn_link(nn, "1 -l-> 2"); /* Hidden to output link. */ /* Set the Activation functions of the hidden and output layers and * initialize the weights to uniform random values between -/+mag. */ nn_set_actfunc(nn, 1, 0, afunc); nn_set_actfunc(nn, 2, 0, "logistic"); nn_init(nn, mag); /* Convert the C matrix into a DATASET. There are two inputs, one * output, and four patterns total. */ data = dataset_create(&dsm_matrix_method, dsm_c_matrix(&rawdata[0][0], 4, 4, 4)); /* Tell the NN how to train itself. */ nn->info.train_set = data; nn->info.opt.min_epochs = minepochs; nn->info.opt.max_epochs = maxepochs; nn->info.opt.error_tol = etol; nn->info.opt.delta_error_tol = detol; nn->info.opt.hook = training_hook; nn->info.opt.rate = rate; if(strcmp(srch, "hybrid") == 0) nn->info.opt.stepf = opt_lnsrch_hybrid; else if(strcmp(srch, "golden") == 0) nn->info.opt.stepf = opt_lnsrch_golden; else if(strcmp(srch, "cubic") == 0) nn->info.opt.stepf = opt_lnsrch_cubic; else if(strcmp(srch, "none") == 0) nn->info.opt.stepf = NULL; if(strcmp(alg, "cgpr") == 0) nn->info.opt.engine = opt_conjgrad_pr; else if(strcmp(alg, "cgfr") == 0) nn->info.opt.engine = opt_conjgrad_fr; else if(strcmp(alg, "qndfp") == 0) nn->info.opt.engine = opt_quasinewton_dfp; else if(strcmp(alg, "qnbfgs") == 0) nn->info.opt.engine = opt_quasinewton_bfgs; else if(strcmp(alg, "lm") == 0) nn->info.opt.engine = opt_levenberg_marquardt; else if(strcmp(alg, "bp") == 0) { nn->info.opt.engine = opt_gradient_descent; nn->info.opt.stepf = NULL; nn->info.subsample = 1; nn->info.opt.stepf = nn_lnsrch_search_then_converge; nn->info.opt.momentum = 0.9; nn->info.stc_eta_0 = 1; nn->info.stc_tau = 100; } /* Do the training. This will print out the epoch number and * The error level until trianing halts via one of the stopping * criterion. */ nn_train(nn); /* Print out each input training pattern and the respective * NN output. */ printf("--------------------\n"); nn_offline_test(nn, data, testing_hook); #if 1 { const double dw = 0.000001; double jj1, jj2, *Rg, Rin[4], Rdout[4], dedy[4], err; int j, k, l, n = nn->numweights; Rg = allocate_array(1, sizeof(double), nn->numweights); nn->need_all_grads = 1; for(k = 0; k < 4; k++) { nn_forward(nn, &rawdata[k][0]); for(l = 0; l < nn->numout; l++) dedy[l] = nn->y[l] - rawdata[k][l]; nn_backward(nn, dedy); for(l = 0; l < nn->numout; l++) /* Fixed */ Rin[l] = nn->dx[l] - dedy[l]; nn_Rforward(nn, Rin, NULL); for(l = 0; l < nn->numout; l++) /* Fixed */ Rdout[l] = nn->Ry[l] - nn->Rx[l]; nn_Rbackward(nn, Rdout); nn_get_Rgrads(nn, Rg); for(j = 0; j < n; j++) { nn_forward(nn, &rawdata[k][0]); for(l = 0; l < nn->numout; l++) dedy[l] = nn->y[l] - rawdata[k][l]; nn_backward(nn, dedy); jj1 = 0; for(l = 0; l < nn->numout; l++) jj1 += 0.5 * (dedy[l] - nn->dx[l]) * (dedy[l] - nn->dx[l]); *nn->weights[j] += dw; nn_forward(nn, &rawdata[k][0]); for(l = 0; l < nn->numout; l++) dedy[l] = nn->y[l] - rawdata[k][l]; nn_backward(nn, dedy); jj2 = 0; for(l = 0; l < nn->numout; l++) jj2 += 0.5 * (dedy[l] - nn->dx[l]) * (dedy[l] - nn->dx[l]); err = fabs(Rg[j] - (jj2 - jj1) / dw) / fabs(Rg[j]); printf("(%d, %2d) ja = % .5e jn = % .5e error = % .2e %s\n", k, j, Rg[j], (jj2 - jj1) / dw, err, (err > 10e-4) ? "BAD" : "GOOD"); *nn->weights[j] -= dw; } } } #endif /* Free up everything. */ nn_destroy(nn); dsm_destroy_matrix(dataset_destroy(data)); nn_shutdown(); /* Bye. */ exit(0); }
int main(int argc, char **argv) { double dt = 0.1, tau = 10.0, gain = 0.5, scale = 0.5; int steps = 400, seed = 0; OPTION opts[] = { { "-dt", OPT_DOUBLE, &dt, "time step increment" }, { "-tau", OPT_DOUBLE, &tau, "decay term" }, { "-gain", OPT_DOUBLE, &gain, "sigmoidal gain" }, { "-scale", OPT_DOUBLE, &scale, "scaling for inputs" }, { "-seed", OPT_INT, &seed, "random seed for initial state" }, { "-steps", OPT_INT, &steps, "number of time steps" }, { NULL, OPT_NULL, NULL, NULL } }; NN *nn; double *data; int i, j, k, ii, sz, n, sum; /* Get the command-line options. */ get_options(argc, argv, opts, help_string, NULL, 0); /* How many neurons? What is the N x N size? */ sz = sizeof(task_assigment_scores) / sizeof(double); n = sqrt(sz); /* Set the random seed. */ srandom(seed); /* Create the Hopfield network. */ nn = create_hopfield_net(gain, tau, dt); /* Create the input data. Note that if we changed the data for this * task assigment problem, then this would be the only thing that * would need changing for this example. */ data = create_external_input(scale, dt); for(ii = 0; ii < steps; ii++) { /* Print out the network's activation values. */ for(i = 0, k = 0; i < n; i++) { for(j = 0; j < n; j++, k++) printf("% .3f\t", nn->y[k]); printf("\n"); } printf("----------------------------------------------\n"); /* Simulate a single time step. */ nn_forward(nn, data); } /* Note that I am beeing lazy and not checking that the solution forms * a permutation matrix. */ sum = 0; for(i = 0; i < sz; i++) if(nn->y[i] > 0.5) sum += task_assigment_scores[i]; printf("\nFinal score = %d\n\n", sum); /* Free up everything. */ deallocate_array(data); nn_destroy(nn); nn_shutdown(); exit(0); }
int main(int argc, char **argv) { /* These variables are for command-line options. */ double var = 0.0; int seed = 0, nbasis = 4, norm = 0; /* The OPTION array is used to easily parse command-line options. */ OPTION opts[] = { { "-var", OPT_DOUBLE, &var, "variance of basis functions" }, { "-seed", OPT_INT, &seed, "random number seed" }, { "-nbasis", OPT_INT, &nbasis, "number of basis functions" }, { "-norm", OPT_SWITCH, &norm, "normalized basis functions?" }, { NULL, OPT_NULL, NULL, NULL } }; /* The DATASET and the NN that we will use. */ SERIES *trainser, *testser; DATASET *trainds, *testds; NN *nn; /* Get the command-line options. */ get_options(argc, argv, opts, help_string, NULL, 0); /* Set the random seed. */ srandom(seed); testser = series_read_ascii("hp41.dat"); testser->x_width = 2; testser->y_width = testser->offset = testser->x_delta = testser->y_delta = 1; testser->step = testser->x_width + testser->y_width; testds = dataset_create(&dsm_series_method, testser); trainser = series_read_ascii("hp21.dat"); trainser->x_width = 2; trainser->y_width = trainser->offset = trainser->x_delta = trainser->y_delta = 1; trainser->step = trainser->x_width + trainser->y_width; trainds = dataset_create(&dsm_series_method, trainser); nn_rbf_basis_normalized = norm; nn = nn_create_rbf(nbasis, var, trainds); nn->links[0]->need_grads = 1; nn->info.train_set = trainds; nn->info.opt.min_epochs = 20; nn->info.opt.max_epochs = 200; nn->info.opt.error_tol = 1e-3; nn->info.opt.delta_error_tol = 1e-8; nn->info.opt.hook = training_hook; nn->info.opt.stepf = opt_lnsrch_cubic; nn->info.opt.engine = opt_quasinewton_bfgs; nn_train(nn); /* Now, let's see how well the RBF performs. */ nn_offline_test(nn, testds, testing_hook); /* Free up everything. */ nn_destroy(nn); series_destroy(dataset_destroy(testds)); series_destroy(dataset_destroy(trainds)); nn_shutdown(); /* Bye. */ exit(0); }
int32_t main #endif (int argc,const char *argv[]) { char *retbuf,*line,*jsonargs,*transportstr,registerbuf[MAX_JSON_FIELD]; struct plugin_info *plugin; double startmilli; cJSON *argjson; int32_t max,sendflag,sleeptime=1,len = 0; #ifndef BUNDLED portable_OS_init(); #endif milliseconds2(); max = 1000000; retbuf = malloc(max+1); plugin = calloc(1,sizeof(*plugin));// + PLUGIN_EXTRASIZE); //plugin->extrasize = PLUGIN_EXTRASIZE; plugin->ppid = OS_getppid(); strcpy(plugin->name,PLUGINSTR); if ( 0 ) { int32_t i; for (i=0; i<argc; i++) printf("(%s) ",argv[i]); printf("argc.%d\n",argc); } //printf("%s (%s).argc%d parent PID.%d\n",plugin->name,argv[0],argc,plugin->ppid); plugin->timeout = 1; if ( argc <= 2 ) { jsonargs = (argc > 1) ? stringifyM((char *)argv[1]) : stringifyM("{}"); configure_plugin(retbuf,max,plugin,jsonargs,-1); free(jsonargs); //fprintf(stderr,"PLUGIN_RETURNS.[%s]\n",retbuf), fflush(stdout); return(0); } randombytes((uint8_t *)&plugin->myid,sizeof(plugin->myid)); plugin->permanentflag = atoi(argv[1]); plugin->daemonid = calc_nxt64bits(argv[2]); #ifdef BUNDLED plugin->bundledflag = 1; #endif transportstr = get_localtransport(plugin->bundledflag); sprintf(plugin->connectaddr,"%s://SuperNET.agents",transportstr); sprintf(plugin->bindaddr,"%s://%llu",transportstr,(long long)plugin->daemonid); jsonargs = (argc >= 3) ? ((char *)argv[3]) : 0; configure_plugin(retbuf,max,plugin,jsonargs,1); printf("CONFIGURED.(%s) argc.%d: %s myid.%llu daemonid.%llu NXT.%s serviceNXT.%s\n",plugin->name,argc,plugin->permanentflag != 0 ? "PERMANENT" : "WEBSOCKET",(long long)plugin->myid,(long long)plugin->daemonid,plugin->NXTADDR,plugin->SERVICENXT);//,jsonargs!=0?jsonargs:""); if ( init_pluginsocks(plugin,plugin->permanentflag,plugin->myid,plugin->daemonid,plugin->timeout) == 0 ) { argjson = cJSON_Parse(jsonargs); if ( (len= registerAPI(registerbuf,sizeof(registerbuf)-1,plugin,argjson)) > 0 ) { //fprintf(stderr,">>>>>>>>>>>>>>> plugin.(%s) sends REGISTER SEND.(%s)\n",plugin->name,registerbuf); nn_local_broadcast2(plugin->pushsock,0,0,(uint8_t *)registerbuf,(int32_t)strlen(registerbuf)+1), plugin->numsent++; } else printf("error register API\n"); if ( argjson != 0 ) free_json(argjson); } else printf("error init_pluginsocks\n"); while ( OS_getppid() == plugin->ppid ) { retbuf[0] = 0; if ( (len= nn_recv(plugin->pullsock,&line,NN_MSG,0)) > 0 ) { len = (int32_t)strlen(line); //printf("(s%d r%d) <<<<<<<<<<<<<< %s.RECEIVED (%s).%d -> bind.(%s) connect.(%s) %s\n",plugin->numsent,plugin->numrecv,plugin->name,line,len,plugin->bindaddr,plugin->connectaddr,plugin->permanentflag != 0 ? "PERMANENT" : "WEBSOCKET"), fflush(stdout); if ( (len= process_plugin_json(retbuf,max,&sendflag,plugin,plugin->permanentflag,plugin->daemonid,plugin->myid,line)) > 0 ) { if ( plugin->bundledflag == 0 ) printf("%s\n",retbuf), fflush(stdout); if ( sendflag != 0 ) { nn_local_broadcast2(plugin->pushsock,0,0,(uint8_t *)retbuf,(int32_t)strlen(retbuf)+1), plugin->numsent++; //fprintf(stderr,">>>>>>>>>>>>>> returned.(%s)\n",retbuf); } } //else printf("null return from process_plugin_json\n"); nn_freemsg(line); } else { startmilli = milliseconds2(); if ( PLUGNAME(_idle)(plugin) == 0 ) { if ( plugin->sleepmillis != 0 ) { sleeptime = plugin->sleepmillis - (milliseconds2() - startmilli); //printf("%s sleepmillis.%d sleeptime.%d\n",plugin->name,plugin->sleepmillis,sleeptime); if ( sleeptime > 0 ) msleep2(sleeptime); } } } } fprintf(stderr,"ppid.%d changed to %d\n",plugin->ppid,OS_getppid()); PLUGNAME(_shutdown)(plugin,len); // rc == 0 -> parent process died nn_shutdown(plugin->pushsock,0); if ( plugin->pushsock != plugin->pullsock ) nn_shutdown(plugin->pullsock,0); free(plugin); return(len); }
int publishDestroy () { return nn_shutdown (pubSock, 0); }