コード例 #1
0
ファイル: lpc.c プロジェクト: synkarae/codec2
void levinson_durbin(
  scalar R[],		/* order+1 autocorrelation coeff */
  scalar lpcs[],		/* order+1 LPC's */
  int order		/* order of the LPC analysis */
)
{
  scalar a[order+1][order+1];
  scalar sum, e, k;
  int i,j;				/* loop variables */

  scalar ZERO = fl_to_numb(0.0);

  e = R[0];				/* Equation 38a, Makhoul */

  for(i=1; i<=order; i++) {
    sum = ZERO;
    for(j=1; j<=i-1; j++)
      sum = s_add(sum, s_mul(a[i-1][j],R[i-j])); 
    k = s_mul(-1.0, s_div(s_add(R[i], sum),e));		/* Equation 38b, Makhoul */
    if (s_abs(k) > fl_to_numb(1.0))
      k = ZERO;

    a[i][i] = k;

    for(j=1; j<=i-1; j++)
      a[i][j] = s_add(a[i-1][j] , s_mul(k,a[i-1][i-j]));	/* Equation 38c, Makhoul */

    e = s_mul(e, s_sub(fl_to_numb(1.0),s_mul(k,k)));				/* Equation 38d, Makhoul */
  }

  for(i=1; i<=order; i++)
    lpcs[i] = a[order][i];
  lpcs[0] = fl_to_numb(1.0);  
}
コード例 #2
0
ファイル: lpc.c プロジェクト: synkarae/codec2
void find_aks(
  scalar Sn[],	/* Nsam samples with order sample memory */
  scalar a[],	/* order+1 LPCs with first coeff 1.0 */
  int Nsam,	/* number of input speech samples */
  int order,	/* order of the LPC analysis */
  scalar *E	/* residual energy */
)
{
  scalar Wn[LPC_MAX_N];	/* windowed frame of Nsam speech samples */
  scalar R[order+1];	/* order+1 autocorrelation values of Sn[] */
  int i;

  assert(Nsam < LPC_MAX_N);

  hanning_window(Sn,Wn,Nsam);
  autocorrelate(Wn,R,Nsam,order);
  levinson_durbin(R,a,order);

  *E = fl_to_numb(0.0);
  for(i=0; i<=order; i++)
    *E = s_add(*E , s_mul(a[i],R[i]));
  if (*E < fl_to_numb(0.0)) {
	#ifdef MATH_Q16_16   
	 *E = 1;
	#else
	 *E = powf(2, -16);//fl_to_numb(1E-12); For debuging purposes. 
	#endif
  }
}
コード例 #3
0
ファイル: lpc.c プロジェクト: synkarae/codec2
void de_emp(
  scalar  Sn_de[],  /* output frame of speech samples                     */
  scalar  Sn[],	   /* input frame of speech samples                      */
  scalar *mem,      /* Sn[-1]single sample memory                         */
  int    Nsam	   /* number of speech samples to use                    */
)
{
    int   i;
    scalar BETA_ = fl_to_numb(BETA);
    for(i=0; i<Nsam; i++) {
	Sn_de[i] = s_add(Sn[i] , s_mul(BETA_, mem[0]));
	mem[0] = Sn_de[i];
    }

}
コード例 #4
0
int main(int argc, const char * argv[]) {
    
    // 头插法
    SLIST singleLinkList0 = s_init();
    for (int i = 0; i < 5; i++) {
        s_add(singleLinkList0, 0, i);
    }
    s_print(singleLinkList0);
    
    // 尾插法
    SLIST singleLinkList = s_init();
    SNODE* endNode = singleLinkList;
    for (int i = 0; i < 5; i++) {
        SNODE* node = (SNODE*)malloc(sizeof(SNODE));
        node->data = i;
        endNode->next = node;
        endNode = node;
        singleLinkList->data++;
    }
    
    s_print(singleLinkList);
    
    s_add(singleLinkList, 3, 5);
    s_print(singleLinkList);
    
    printf("%d\n", s_get(singleLinkList, 3));
    s_print(singleLinkList);
    
    s_delete(singleLinkList, 1);
    s_print(singleLinkList);
    
    s_clear(singleLinkList);
    s_print(singleLinkList);
    
    return 0;
}
コード例 #5
0
ファイル: lpc.c プロジェクト: synkarae/codec2
void inverse_filter(
  scalar Sn[],	/* Nsam input samples */
  scalar a[],	/* LPCs for this frame of samples */
  int Nsam,	/* number of samples */
  scalar res[],	/* Nsam residual samples */
  int order	/* order of LPC */
)
{
  int i,j;	/* loop variables */

  for(i=0; i<Nsam; i++) {
    res[i] = fl_to_numb(0.0);
    for(j=0; j<=order; j++)
      res[i] = s_add(res[i] , s_mul(Sn[i-j],a[j]));
  }    
}
コード例 #6
0
ファイル: lpc.c プロジェクト: synkarae/codec2
void autocorrelate(
  scalar Sn[],	/* frame of Nsam windowed speech samples */
  scalar Rn[],	/* array of P+1 autocorrelation coefficients */
  int Nsam,	/* number of windowed samples to use */
  int order	/* order of LPC analysis */
)
{
  int i,j;	/* loop variables */

  scalar Zero = fl_to_numb(0.0);
  for(j=0; j<order+1; j++) {
    Rn[j] = Zero;
    for(i=0; i<Nsam-j; i++)
      Rn[j] = s_add(Rn[j] , s_mul(Sn[i],Sn[i+j]));
  }
}
コード例 #7
0
ファイル: hashmap.c プロジェクト: GPtpvWKrrZWERTEg/mccp
mccp_result_t
mccp_hashmap_add_no_lock(mccp_hashmap_t *hmptr,
                         void *key, void **valptr,
                         bool allow_overwrite) {
  mccp_result_t ret = MCCP_RESULT_ANY_FAILURES;

  if (hmptr != NULL &&
      *hmptr != NULL &&
      valptr != NULL) {

    ret = s_add(hmptr, key, valptr, allow_overwrite);

  } else {
    ret = MCCP_RESULT_INVALID_ARGS;
  }

  return ret;
}
コード例 #8
0
ファイル: hashmap.c プロジェクト: 1514louluo/lagopus
lagopus_result_t
lagopus_hashmap_add_no_lock(lagopus_hashmap_t *hmptr,
                            void *key, void **valptr,
                            bool allow_overwrite) {
  lagopus_result_t ret = LAGOPUS_RESULT_ANY_FAILURES;

  if (hmptr != NULL &&
      *hmptr != NULL &&
      valptr != NULL) {

    ret = s_add(hmptr, key, valptr, allow_overwrite);

  } else {
    ret = LAGOPUS_RESULT_INVALID_ARGS;
  }

  return ret;
}
コード例 #9
0
ファイル: lockedtable.c プロジェクト: gideonla/w2014
void inc_size(struct locked_table *tab) {
    // First save the size so we can tell if someone else already resized
    int old_size = tab->cap;
    // Stop resizing if we're at allocation.
    if (old_size == PREALLOC_COUNT) {
        printf("Oops -- prealloc count reached\n");
        goto end;
    }

    // Acq all the locks
    for (int i = 0; i < tab->initial_cap; i++) {
        pthread_rwlock_wrlock(tab->locks + i);
    }

    if (tab->cap != old_size)
        goto end;

    // Go through and reposition all the old elements
    for (int i = 0; i < tab->cap; i++) {
        struct serial_list *this_bucket = tab->buckets + i;
        struct serial_list_elem *e = this_bucket->head;
        while (e) {
            int new_ind = e->key & (tab->cap * 2 - 1);
            if (new_ind != i) {
                s_add(tab->buckets + new_ind, e->key, e->pkt);
                int key = e->key;
                e = e->next;
                s_remove (this_bucket, key);
            }
            else {
                e = e->next;
            }
        }
    }

    tab->cap *= 2;

end:
    for (int i = 0; i < tab->initial_cap; i++) {
        pthread_rwlock_unlock(tab->locks + i);
    }
    return;
}
コード例 #10
0
ファイル: lockedtable.c プロジェクト: gideonla/w2014
bool locked_add(struct hashtable *_t, int key, Packet_t *pkt) {
    struct locked_table *tab = (struct locked_table *) _t;
    int lock_ind = key & (tab->initial_cap - 1);

    bool trigger_resize = false;
    pthread_rwlock_wrlock (tab->locks + lock_ind);

    int bucket_ind = key & (tab->cap - 1);
    bool succ = s_add (tab->buckets + bucket_ind, key, pkt);

    if (tab->buckets[bucket_ind].size > RESIZE_THRESH)
        trigger_resize = true;

    pthread_rwlock_unlock (tab->locks + lock_ind);

    if (trigger_resize)
        inc_size(tab);

    return succ;
}
コード例 #11
0
ファイル: win_size.cpp プロジェクト: Lucki/Lix
// old, plus
void WindowSize::draw_calculation(const int y, const int o, const int p)
{
    const int base = (hex.get_checked() ? 16 : 10);

    std::string s_old(4, ' ');
    std::string s_add(4, ' ');
    std::string s_new(4, ' ');
    std::string s_pls(p < 0 ? "-" : "+");
    std::string s_eql("=");

    Torbit& tb = get_torbit();
    BITMAP* bp = tb.get_al_bitmap();

    // Alte Zahl wegputzen
    rectfill(bp, x_offset, y, this_xl-2,y+19,color[COL_API_M]);

    for (int i = 3, temp = o; i >= 0 && temp > 0; --i) {
        s_old[i] = digit_to_character(temp % base);
        temp /= base;
        if (temp == 0 && base == 16 && i > 0) s_old[i-1] = 'x';
    }
    for (int i = 3, temp = o+p; i >= 0 && temp > 0; --i) {
        s_new[i] = digit_to_character(temp % base);
        temp /= base;
        if (temp == 0 && base == 16 && i > 0) s_new[i-1] = 'x';
    }
    s_add[3] = '0';
    for (int i = 3, temp = (p < 0) ? -p : p; i >= 0 && temp > 0; --i) {
        s_add[i] = digit_to_character(temp % base);
        temp /= base;
        if (temp == 0 && base == 16 && i > 0) s_add[i-1] = 'x';
    }
    const int x_here = get_x_here() + x_offset;
    Help::draw_shadow_fixed_text(tb, font_med, s_old, x_here+  0, y, color[COL_TEXT]);
    Help::draw_shadow_fixed_text(tb, font_med, s_pls, x_here+ 55, y, color[COL_TEXT]);
    Help::draw_shadow_fixed_text(tb, font_med, s_add, x_here+ 85, y, color[COL_TEXT]);
    Help::draw_shadow_fixed_text(tb, font_med, s_eql, x_here+135, y, color[COL_TEXT]);
    Help::draw_shadow_fixed_text(tb, font_med, s_new, x_here+160, y, color[COL_TEXT_ON]);
}
コード例 #12
0
ファイル: stest.c プロジェクト: hbkscorpion/apcs
int main(int argc, char** argv) {
    int error = 1;

    printf("Set Testing Framework\n");
    printf("\n");

    // Test equality first so we can use it in later tests
    printf("Phase 0: Testing equality methods.\n");
    {
        set *s1 = malloc(sizeof(set));
        set *s2 = malloc(sizeof(set));
        int numbers[8] = { -1, 5, 8, 2, 3, 5, 9, 10 };
        int order1 [8] = { 0, 7, 3, 2, 4, 5, 6, 1 };
        int order2 [8] = { 6, 2, 7, 3, 1, 0, 5, 4 };
        int i;
        for (i = 0; i < 8; i++) {
            s_add(s1, numbers[order1[i]]);
            s_add(s2, numbers[order2[i]]);
        }
        bool eq = s_eq(s1, s2);
        if (!eq) {
            return error;
        }
        printf("Equal sets are equal.\n");
        error++;

        bool seq = s_subseteq(s1, s2) && s_subseteq(s2, s1);
        if (!seq) {
            return error;
        }
        printf("Subset works both ways.\n");
        error++;
    }

    printf("\n");
    printf("Phase I: Testing single-set operations.\n");
    {
        set *s = malloc(sizeof(set));
        printf("Set created.\n");
        error++;

        printf("Adding numbers.\n");
        s_add(s, 1);
        s_add(s, 0);
        s_add(s, 6);
        s_add(s, 6);
        s_add(s, 1);
        s_add(s, -1);
        // set is now { 1, 0, 6, -1 }

        if (s_size(s) != 4) {
            return error;
        }
        printf("Size correct.\n");
        error++;

        printf("Removing numbers.\n");
        s_remove(s, 3); // nothing
        s_remove(s, 1); // -1
        s_remove(s, 6); // -2
        // set is now { 0, -1 }

        if (s_size(s) != 2) {
            return error;
        }
        printf("Size still correct.\n");
        error++;

        printf("Testing s_contains.\n");
        {
            bool okay = true;
            okay &= s_contains(s, 0);
            okay &= (!s_contains(s, 1));
            okay &= s_contains(s, -1);
            okay &+ (!s_contains(s, 8));
            if (!okay) {
                return error;
            }
        }
        printf("s_contains works as intended.\n");
        error++;

    }

    printf("\n");
    printf("Phase II: Testing Multi-Set Operations\n");
    {
        set *s1 = malloc(sizeof(set)), *s2 = malloc(sizeof(set));
        printf("Two sets created.\n");
        error++;

        s_add(s1, 1);
        s_add(s1, 3);
        s_add(s1, 7);

        s_add(s2, 5);
        s_add(s2, -2);
        s_add(s2, 3);

        printf("Two sets filled.\n");
        error++;

        {
            set *sr_union = s_union(s1, s2);
            printf("Union created.\n");
            error++;

            int shouldBe[5] = { -2, 1, 3, 5, 7 };
            int size = sizeof(shouldBe) / sizeof(int);
            if (s_size(sr_union) != size) {
                node *n = sr_union -> first;
                while (n != NULL ) {
                    printf("%d ", n -> value);
                    n = n -> next;
                }
                printf("\n");
                printf("Size is %d but should be %d!\n", s_size(sr_union), size);
                return error;
            }
            printf("Size correct (getting good at this).\n");
            error++;

            int i;
            for (i = 0; i < size; i++) {
                if (!s_contains(sr_union, shouldBe[i])) {
                    return error;
                }
            }
            printf("Union set contains all required elements.\n");
            error++;

        }{
            set *sr_isect = s_isect(s1, s2);
            printf("Intersection created.\n");
            error++;

            int shouldBe[1] = { 3 };
            int size = sizeof(shouldBe) / sizeof(int);
            if (s_size(sr_isect) != size) {
                return error;
            }
            printf("Size correct (again).\n");
            error++;

            int i;
            for (i = 0; i < size; i++) {
                if (!s_contains(sr_isect, shouldBe[i])) {
                    return error;
                }
            }
            printf("Intersection set contains all required elements.\n");
            error++;

        }{
            set *sr_diff = s_diff(s1, s2);
            printf("Difference created.\n");
            error++;

            int shouldBe[2] = { 1, 7 };
            int size = sizeof(shouldBe) / sizeof(int);
            if (s_size(sr_diff) != size) {
                return error;
            }
            printf("Size correct (miraculously).\n");
            error++;

            int i;
            for (i = 0; i < size; i++) {
                if (!s_contains(sr_diff, shouldBe[i])) {
                    return error;
                }
            }
            printf("Difference set contains all required elements.\n");
            error++;

        }
    }

    printf("\n");
    printf("Phase III: Testing Specification");
    {
        set *s = malloc(sizeof(set));
        printf("Set created.\n");
        error++;

        int list[6] = { -2, -1, 1, 4, 8, 9 };
        int size = sizeof(list) / sizeof(int);

        int i;
        for (i = 0; i < size; i++) {
            s_add(s, list[i]);
        }
        printf("Set filled.\n");
        error++;

        printf("Testing specification with p(x) = (x >= 3).\n");
        {
            set *sr_p1 = s_spec(s, p1);
            printf("Specification complete.\n");
            error++;

            int expected[3] = { 4, 8, 9 };
            int expectedSize = sizeof(expected) / sizeof(int);

            if (s_size(sr_p1) != expectedSize) {
                return error;
            }
            printf("Specification size correct - phew!\n");
            error++;

            int j;
            for (j = 0; j < expectedSize; j++) {
                if (!s_contains(sr_p1, expected[j])) {
                    return error;
                }
            }
            printf("Set contains all required elements.\n");
        }

        printf("Testing specification with p(x) = (x %% 2 == 0).\n");
        {
            set *sr_p1 = s_spec(s, p2);
            printf("Specification complete.\n");
            error++;

            int expected[3] = { -2, 4, 8 };
            int expectedSize = sizeof(expected) / sizeof(int);

            if (s_size(sr_p1) != expectedSize) {
                return error;
            }
            printf("Specification size correct; what a surprise.\n");
            error++;

            int j;
            for (j = 0; j < expectedSize; j++) {
                if (!s_contains(sr_p1, expected[j])) {
                    return error;
                }
            }
            printf("Set contains all required elements.\n");
        }

    }
    printf("\n");
    printf("Phase IV: Testing Image\n");
    {
        set *s = malloc(sizeof(set));
        set *control  = malloc(sizeof(set));
        set *control2 = malloc(sizeof(set)); // image with predicate lambda x: x >= 3
        int toadd[6]     = { -1,  3,  5, 2, 0, 1 };
        int expected[6]  = {  3, 11, 27, 6, 2, 3 };
        int expected2[6] = {     11, 27          };
        int i;
        for (i = 0; i< 6; i++) {
            s_add(s, toadd[i]);
            s_add(control, expected[i]);
            if (i < 2) s_add(control2, expected2[i]);
        }
        set *image = s_fullimage(s, f);
        bool eq = s_eq(image, control);
        if (!eq) {
            return error;
        }
        printf("Full image set matches control set.\n");
        error++;

        set *pimage = s_image(s, p1, f);
        bool peq = s_eq(pimage, control2);
        if (!peq) {
            return error;
        }
        printf("Partial image set matches control set.\n");
        error++;
    }

    printf("\n");
    printf("Completed without error.\n");
    return 0;
}
コード例 #13
0
ファイル: main.c プロジェクト: kdhp/play
/* s_add from file ``file'' */
static void
s_file(struct songs **songs, const char *file) {
	FILE	*f = stdin;
	char	 b[PATH_MAX];
	char	*t = NULL;
	char	*dnam = NULL;
	size_t	 s = 0;
	ssize_t	 l = 0;
	size_t	 dlen = 0;
	assert(songs != NULL);
	if (file != NULL && strcmp(file, "-") != 0) {
		char *p;
		ssize_t s;
		dnam = dirname(file);
		if ((dnam = dirname(file)) == NULL) {
			warn("dirname %s", file);
			return;
		}
		if (strcmp(dnam, ".") == 0)
			dnam = NULL;
		else if ((dlen = strlen(dnam)) == 0)
			/* probably unreachable */
			errx(EX_NOINPUT, "strlen");
		if ((f = fopen(file, "r")) == NULL) {
			warn("fopen %s", file);
			return;
		}
	}
	while ((l = getline(&t, &s, f)) > 0) {
		size_t	i = 0;
		int	err;
		/* skip trailing whitespace */
		while (l > 0 && isspace(t[l - 1]))
			l--;
		/* skip leading whitespace */
		while (l > 0 && isspace(t[i])) {
			i++;
			l--;
		}
		if (l == 0)
			continue;
		if (t[i] == '/' || dnam == NULL) {
			if (l + 1 >= sizeof(b)) {
				warnx("s_file path too long");
				return;
			}
			if (snprintf(b, l + 1, "%*s", (int)l, t + i)
			    >= sizeof(b)) {
				/* probably unreachable */
				warnx("snprintf path too long");
				return;
			}
		} else { /* prepend the file's directory */
			/* skip "./" prefix */
			if (l >= 2 && t[i] == '.' && t[i + 1] == '/') {
				i += 2;
				l -= 2;
				if (l == 0)
					continue;
			}
			if (dlen + l + 2 >= sizeof(b)) {
				warnx("s_file path too long");
				return;
			}
			if (snprintf(b, dlen + l + 2, "%s/%*s",
			    dnam, (int)l, t + i) >= sizeof(b)) {
				/* probably unreachable */
				warnx("snprintf path too long");
				return;
			}
		}
		s_add(songs, b);
	}
	if (t != NULL)
		free(t);
	if (file != NULL && strcmp(file, "-") != 0)
		fclose(f);
	return;
}
コード例 #14
0
ファイル: main.c プロジェクト: kdhp/play
/* add ``f'' to songs, or its contents if ``f'' is a directory */ 
static void
s_add(struct songs **songs, const char *path) {
	struct stat	 st;
	struct songs	*s;
	DIR		*d;
	struct dirent	*e;
	char		*p;
	size_t		 l;
	assert(songs != NULL && path != NULL);
	s = *songs;
	if (s == NULL) {
		if ((s = malloc(sizeof(struct songs)
		    + ISNGSIZ * sizeof(char *))) == NULL)
			err(EX_OSERR, "malloc");
		s->size = ISNGSIZ;
		s->cur = 0;
		*songs = s;
	}
	if (stat(path, &st) != 0) {
		warn("stat %s", path);
		return;
	}
	if ((st.st_mode & S_IFDIR) != 0) {
		DIR		*d;
		struct dirent	*e;
		char b[PATH_MAX];
		if ((d = opendir(path)) == NULL) {
			warn("opendir %s", path);
			return;
		}
		while ((e = readdir(d)) != NULL) {
			if (snprintf(b, sizeof(b), "%s/%*s", path,
			    (int)e->d_namlen, e->d_name) >= sizeof(b)) {
				warnx("snprintf path too long");
				break;
			}
			if (stat(b, &st) != 0) { /* removal race */
				warn("stat %s", path);
				continue;
			}
			/* do not recursively search directories */
			if (!(st.st_mode & S_IFDIR))
				s_add(songs, b);
		}
		closedir(d);
		return;
	}
	if (s->cur + 1 >= s->size) {
		void *p;
		if (s->size > 0xFFFF) /* (not so) sane cap */
			err(EX_SOFTWARE, "'songs' sanity check");
		s->size *= 2;
		if ((p = realloc(s, sizeof(struct songs) +
		    s->size * sizeof(char *))) == NULL)
			err(EX_OSERR, "realloc");
		s = p;
		*songs = s;
	}
	/* allocate paths here to simplify freeing */
	if ((l = strlen(path)) + 1 >= PATH_MAX) {
		warnx("s_add path too long");
		return;
	}
	if ((p = malloc(l + 1)) == NULL)
		err(EX_OSERR, "malloc");
	strncpy(p, path, l);
	p[l] = '\0';
	s->songs[s->cur++] = p;
	s->songs[s->cur] = NULL;
	return;
}
コード例 #15
0
ファイル: main.c プロジェクト: kdhp/play
/*
 * Play audio, normally as a background process.
 */
int
main(int argc, char **argv) {
	struct conf conf;
	char *cmdfile = NULL;
	sigset_t sigmask;
	int fd;
	int e;
	int c;
	conf.cmd.f = stdin;
	conf.cmd.i = 0;
	conf.cmd.conn = 1;
	conf.buffer = NULL;
	conf.songs = NULL;
	conf.dev = NULL;
	conf.flags = 0;
	while ((c = getopt(argc, argv, "c:d:f:hilrv")) != -1)
		switch (c) {
		case 'c':
			if (strcmp(optarg, "-") == 0) {
				cmdfile = NULL;
				conf.flags |= CFLAG;
			} else
				cmdfile = optarg;
			break;
		case 'd':
			conf.dev = optarg;
			break;
		case 'f': /* file-list */
			s_file(&conf.songs, optarg);
			break;
		case 'h':
			usage(0); /* does not return */
		case 'i':
			info();
			return 0;
		case 'l': /* loop */
			conf.flags |= LFLAG;
			break;
		case 'r': /* random shuffle */
			conf.flags |= RFLAG;
			break;
		case 'v': /* verbose */
			conf.flags |= VFLAG;
			break;
		case '?':
			usage(1); /* does not return */
		}
	if (cmdfile != NULL) {
		if ((fd = open(cmdfile, O_RDONLY | O_NONBLOCK)) < 0)
			err(EX_NOINPUT, "open %s", cmdfile);
		if ((conf.cmd.f = fdopen(fd, "r")) == NULL) {
			close(fd);
			err(EX_NOINPUT, "open %s", cmdfile);
		}
	}
	while (optind < argc)
		s_add(&conf.songs, argv[optind++]);
	if (((cmdfile != NULL || !isatty(0)) && !(conf.flags & CFLAG))
	    && conf.songs == NULL) {
		s_file(&conf.songs, NULL);
		if (cmdfile == NULL)
			conf.cmd.f = NULL;
	}
	if (conf.songs == NULL)
		exit(EX_NOINPUT);
	if (signal(SIGINFO, sig_info) == SIG_ERR ||
	    signal(SIGINT, sig_int) == SIG_ERR ||
	    signal(SIGUSR1, sig_usr1) == SIG_ERR ||
	    signal(SIGUSR2, sig_usr2) == SIG_ERR ||
	    signal(SIGTERM, sig_term) == SIG_ERR ||
	    signal(SIGTTIN, SIG_IGN) == SIG_ERR)
		err(EX_OSERR, "signal");
	if (sigemptyset(&sigmask) != 0 ||
	    sigaddset(&sigmask, SIGINFO) != 0 ||
	    sigaddset(&sigmask, SIGINT) != 0 ||
	    sigaddset(&sigmask, SIGUSR1) != 0 ||
	    sigaddset(&sigmask, SIGUSR2) != 0 ||
	    sigaddset(&sigmask, SIGTERM) != 0 ||
	    sigaddset(&sigmask, SIGTTIN) != 0)
		err(EX_OSERR, "sigaddset");
	if (signal(SIGQUIT, sig_term) != SIG_ERR &&
	    sigaddset(&sigmask, SIGQUIT) != 0)
			err(EX_SOFTWARE, "SIGQUIT");
	if (sigprocmask(SIG_UNBLOCK, &sigmask, NULL)	!= 0 ||
	    sigprocmask(0, NULL, &sigmask)		!= 0)
		err(EX_OSERR, "sigprocmask");
#ifndef OSS
	if ((conf.out = a_open(conf.dev)) == NULL)
		err(EX_SOFTWARE, "a_open");
#endif
	conf.songs->shuffle = NULL;
	if ((conf.flags & RFLAG) && (conf.songs->shuffle =
	    malloc(conf.songs->cur * sizeof(uint16_t))) == NULL)
		err(EX_OSERR, "malloc");
	if (conf.cmd.f != NULL) {
		if ((conf.kq = kqueue()) < 0)
			err(EX_OSERR, "kqueue");
		EV_SET(&conf.ev, fileno(conf.cmd.f), EVFILT_READ,
		    EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL);
		if (kevent(conf.kq, &conf.ev, 1, NULL, 0, NULL) != 0)
			err(EX_OSERR, "kevent");
	}
	if (conf.cmd.f == stdin)
		nonblock(0);
	if ((conf.buffer = malloc(BUFSIZE)) == NULL)
		err(EX_OSERR, "malloc");
#ifdef TAME
	tame(TAME_MALLOC | TAME_STDIO | TAME_RPATH, NULL);
#else
#ifdef __OpenBSD__
	pledge("malloc stdio rpath", NULL);
#endif
#endif
	do
		c = play(&conf);
	while ((conf.flags & LFLAG) && c == CNULL);
ex:
	if (conf.songs != NULL) {
		if (conf.songs->shuffle != NULL)
			free(conf.songs->shuffle);
		while (conf.songs->cur-- > 0)
			free(conf.songs->songs[conf.songs->cur]);
		free(conf.songs);
	}
	if (conf.buffer != NULL)
		free(conf.buffer);
	return EX_OK;
}
コード例 #16
0
ファイル: receiver.cpp プロジェクト: rexyl/Proxy
int main(int argc, char **argv)
{
    if (argc<6) {
        fprintf(stderr,"ERROR, not enough argument\n");
        exit(1);
    }
    std::string filename(argv[1]);
    int SERVICE_PORT =atoi(argv[2]);
    std::string s_add(argv[3]);
    int portno = atoi(argv[4]);
    std::string logname(argv[5]);
    
    char cCurrentPath[FILENAME_MAX];
    if (!getcwd(cCurrentPath, sizeof(cCurrentPath)))
    {
        return errno;
    }
    std::string pathname(cCurrentPath);
    filename = pathname + "/" + filename;
    
    if (logname=="stdout") {
        logfs = stdout;
    }
    else{
        logname = pathname + "/" + logname;
        logfs = fopen(logname.c_str(), "w");
    }
    FILE *ofs = fopen(filename.c_str(), "w");
    //FILE *ofs = fopen("/Users/Rex/Desktop/cn_second/cn_second/o.txt", "w");
    
    
    struct sockaddr_in myaddr;  /* our address */
    struct sockaddr_in remaddr; /* remote address */
    socklen_t addrlen = sizeof(remaddr);        /* length of addresses */
    int recvlen;            /* # bytes received */
    int fd;             /* our socket */
    
    
    /* create a UDP socket */
    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("cannot create socket\n");
        return 0;
    }
    
    /* bind the socket to any valid IP address and a specific port */
    
    memset((char *)&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(SERVICE_PORT);
    
    if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
        perror("bind failed");
        return 0;
    }
    
    /////intial ack related sender tcp//////
    int n,sockfd;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        printf("ERROR opening socket");
    server = gethostbyname(s_add.c_str());
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
          (char *)&serv_addr.sin_addr.s_addr,
          server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        printf("ERROR connecting");
    int ws;
    char addtmp[256];
    read(sockfd, &ws, sizeof(int));
    read(sockfd, addtmp, 255);
    write(sockfd,s_add.c_str() , s_add.size() );
    //local = string(addtmp,strlen(addtmp));
    local = "127.0.0.1";
    //////////
    std::vector<out_order_buffer_unit> out_order_buf;
    
    for(int i = 0; i<ws; i ++){
        byte *temp = new byte[BUFSIZE+20];
        out_order_buffer_unit tmp(-1,temp);
        out_order_buf.push_back(tmp);
    }
    
    /* now loop, receiving data and printing what we received */
    //printf("waiting on port %d\n", SERVICE_PORT);
    byte *tcp_packet = new byte[20+BUFSIZE];
    short flag,checksum,trash_short;
    short len = BUFSIZE;
    int totalbyte = 0,countretrans=0;
    int seq = 0,acknum = 0,rcv_base = 0,trash_int = 0,hehe;
    
    while(1){
        recvlen = recvfrom(fd, tcp_packet, 20+BUFSIZE, 0, (struct sockaddr *)&serv_addr, &addrlen);
        len = parse_packet(tcp_packet, &seq, &acknum, &flag, &checksum);
        
        writelog(time(0), s_add, local, seq*BUFSIZE, seq*BUFSIZE+1, flag, -1);
        if (flag == END) {
            break;
        }
        if (len==-1){
            continue;
        }
        else{
            if (seq==rcv_base) {
                totalbyte += 20+len;
                //string tmp = "len is "+std::to_string(len)+"\n";
                //fwrite(tmp.c_str(), 1, tmp.size(), logfs);
                //std::cout<<"len is "<<len<<"\n";
                //std::cout<<"Write seq # "<<seq<<" with len = "<<len<<"\n";
                fwrite(tcp_packet+20, 1, len, ofs);
                
                //greedy check buffer
                int target = seq+1;
                rcv_base++;
                for(int i = 0; i<ws; i++){
                    if (out_order_buf[i].first == target){
                        short len_t = parse_packet(out_order_buf[i].second, &hehe, &trash_int, &trash_short, &trash_short);
                        //tmp = "len_t is "+std::to_string(len_t)+"\n";
                        //fwrite(tmp.c_str(), 1, tmp.size(), logfs);
                        fwrite( (out_order_buf[i].second)+ 20, 1, len_t, ofs);
                        totalbyte += 20+len_t;
                        rcv_base++;
                        target++;
                        out_order_buf[i].first = -1;
                    }
                }
                acknum = seq+1;
                flag = ACK;
                
                make_packet(tcp_packet, &seq, &acknum, &flag, &checksum, ofs);
                n = write(sockfd, tcp_packet, 20);
                if (n < 0)
                    printf("ERROR writing to socket");
                writelog(time(0), local, s_add, seq*BUFSIZE, seq*BUFSIZE+1, flag, -1);
                
            }
            else  //out of order, buffer it
            {
                for(int i = 0; i<ws; i++){
                    if (out_order_buf[i].first == -1){
                        memcpy(out_order_buf[i].second, tcp_packet, 20+BUFSIZE);
                        out_order_buf[i].first = seq;
                        sort(out_order_buf.begin(),out_order_buf.end());
                        break;
                    }
                }
                
                acknum = seq + 1;
                flag = ACK;
                checksum = 0;
                make_packet(tcp_packet, &seq, &acknum, &flag, &checksum, ofs);
                n = write(sockfd, tcp_packet, 20);
                if (n < 0)
                    printf("ERROR writing to socket");
                writelog(time(0), local, s_add, seq*BUFSIZE, seq*BUFSIZE+1, flag, -1);
            }
        }
        //printf("seq is %d\n",seq);
    }
    string summary = "Transmission was successful!\nTotal bytes sent is "+std::to_string(totalbyte)+
    "\nNumber of sent segment is "+std::to_string(seq)+"\n";
    fwrite(summary.c_str(), 1, summary.size(), logfs);
    fclose(logfs);
    fclose(ofs);
    free(tcp_packet);
    for(int i = 0; i<ws; i ++){
        free(out_order_buf[i].second);
    }
    return 0;
}
コード例 #17
0
/* learn AdaBoost stage A[i,j] */
void learnA( int posCount, int negCount, int blockCount, int *rejectCount, bool rejected[], 
	float ***POS, float ***NEG, Ada *H, float *F_current, float d_minA, float f_maxA, FILE *fout ) {

	int selectTable[ posCount ]; /* image selection table */
	int imgCount = posCount * 2;
	float initialW = 1.f / (float)imgCount;
	Matrix posWeight, negWeight; /* data weight in AdaBoost */
	int hAllocated = 10;
	int hUsed = 0;
	int Iid, t;
    float f_local = 1.f;
	float threshold = 0.f; /* threshold of the strong classifier A[i,j], should be recorded */
	Matrix posResult, negResult;

	ones( &posWeight, 1, posCount, 1 );
	ones( &negWeight, 1, posCount, 1 );
	H = (Ada *)malloc( hAllocated * sizeof( Ada ) );
	zeros( &posResult, 1, posCount, 1 );
	zeros( &negResult, 1, posCount, 1 );

	/* Initialize the data weight */
	s_mul( &posWeight, initialW );
	s_mul( &negWeight, initialW );
    /* [0] Randomly select NEG examples from the bootstrap set 
	 * Report an error if NEG images are not enough
	 */
	if ( posCount + (*rejectCount) > negCount ) {
		fprintf( fout, "Warning: Not enough NEG images.\n" );
		error( "learnA(): Not enough NEG images." );
	}
    select_neg( posCount, negCount, rejected, selectTable );

    while ( f_local > f_maxA ) {
		int fpCount; /* false positive count */
		float d_local = 0.f;

        /* [1] Add a weak learner h to the strong classifier A[i,j] */
		/* Use realloc() if H is full */
		if ( hUsed == hAllocated ) {
			hAllocated *= 2;
			printf( "call realloc()\n" );
			H = (Ada*)realloc( H, hAllocated * sizeof( Ada ) );
		}
        addWeak( posCount, negCount, blockCount, selectTable, 
			POS, NEG, &posWeight, &negWeight, H, &hUsed );

		threshold = 0.f; /*** Adjust by the threshold ONLY WHEN NECESSARY ***/

		float minPosResult = 0.f; /* minimum value of the positive result */
		int detect = 0; /* detection count */
		fpCount = 0;

		/* [2.1] Use the H(x) so far to trial-classify 
		 * H(x) = sign( sum[alpha_t * h_t(x)] )
		 * Process the POS and NEG together in one loop
		 */
		for ( Iid = 0; Iid < posCount; Iid++ ) {
			float posTemp = 0.f;
			float negTemp = 0.f;
			for ( t = 0; t < hUsed; t++ ) {
				int Bid = H[ t ].Bid;
				int Fid = H[ t ].Fid;
				short parity = H[ t ].parity;
				float decision = H[ t ].decision;
				float alpha = H[ t ].alpha;
				/* determine that positive is positive */
				if ( parity * POS[ Iid ][ Bid ][ Fid ] >= parity * decision ) {
					posTemp += alpha;	
				}
				/* determine that positive is negative */
				else {
					posTemp -= alpha;
				}
				/* determine that negative is positive */
				if ( parity * NEG[ selectTable[ Iid ] ][ Bid ][ Fid ] >= parity * decision ) {
					negTemp += alpha;	
				}
				/* determine that negative is negative */
				else {
					negTemp -= alpha;
				}
			} /* end of loop "t" */
		
			/* Record into posResult or negResult, and collect min( posResult ) */
			posResult.data[ 0 ][ 0 ][ Iid ] = posTemp;
			negResult.data[ 0 ][ 0 ][ Iid ] = negTemp;
			if ( posTemp < minPosResult ) {
				minPosResult = posTemp;
			}

		} /* end of loop "Iid" */

#if 0
		full_dump( &posResult, "posResult", ALL, FLOAT );
		full_dump( &negResult, "negResult", ALL, FLOAT );
#endif

#if 1
		/* count for detections and false positives */
		for ( Iid = 0; Iid < posCount; Iid++ ) {
			if ( posResult.data[ 0 ][ 0 ][ Iid ] >= 0.f ) {
				detect++;
			}
			if ( negResult.data[ 0 ][ 0 ][ Iid ] >= 0.f ) {
				fpCount++;
			}
		}
		d_local = (float)detect / (float)posCount;
		printf( "Before modify threshold:\n  Detection rate: %f ( %d / %d )\n", d_local, detect, posCount );
        /* [3] Calculate f_local of H(x) */
		f_local = (float)fpCount / (float)posCount;
		printf( "  False positive rate: %f ( %d / %d )\n", f_local, fpCount, posCount );
#endif
				
        /* [2.2] Modify the threshold of H(x) to fulfill d_minA 
		 * If min( posResult ) < 0, then let
		 * result = result - min( posResult ) so that all POS data are
		 * determined as positive, i.e., detection rate = 100% 
		 */
		if ( minPosResult < 0.f ) {
			threshold = minPosResult;
			s_add( &posResult, -threshold );
			s_add( &negResult, -threshold );
		}
		printf( "threshold: %f\n", threshold );
#if 0
		full_dump( &posResult, "posResult", ALL, FLOAT );
		full_dump( &negResult, "negResult", ALL, FLOAT );
#endif

		/* count for detections and false positives */
		detect = 0;
		fpCount = 0;
		for ( Iid = 0; Iid < posCount; Iid++ ) {
			if ( posResult.data[ 0 ][ 0 ][ Iid ] >= 0.f ) {
				detect++;
			}
			if ( negResult.data[ 0 ][ 0 ][ Iid ] >= 0.f ) {
				fpCount++;
			}
		}
		d_local = (float)detect / (float)posCount;
		printf( "  After modify threshold:\n  Detection rate: %f ( %d / %d )\n", d_local, detect, posCount );
		//assert( d_local >= d_minA );

        /* [3] Calculate f_local of H(x) */
		f_local = (float)fpCount / (float)posCount;
		printf( "False positive rate: %f ( %d / %d )\n", f_local, fpCount, posCount );

    } /* end of loop "f_local > f_maxA" */

    *F_current *= f_local;
	printf( "\nWeak learners used: %d\n", hUsed );
    printf( "Overall false positive rate: %f\n", *F_current );

	/* [4] Put in the "rejection list" the negative images rejected by H(x) */
	for ( Iid = 0; Iid < posCount; Iid++ ) {
		if ( negResult.data[ 0 ][ 0 ][ Iid ] < 0.f ) {
			rejected[ selectTable[ Iid ] ] = true;
			(*rejectCount)++;
		}
	}
	printf( "Rejected %d negative images in total.\n", *rejectCount );
	getchar();

	/* [5] Output H(x) information to file */
	fprintf( fout, "%d %f\n", hUsed, threshold );
	for ( t = 0; t < hUsed; t++ ) {
		fprintf( fout, "%d %d %d %f %f\n", 
			H[ t ].Bid, H[ t ].Fid, H[ t ].parity, H[ t ].decision, H[ t ].alpha );
	}

	/* Free memory space */
	freeMatrix( &posWeight );
	freeMatrix( &negWeight );
	free( H );
	freeMatrix( &posResult );
	freeMatrix( &negResult );
}