本文整理汇总了C++中random函数的典型用法代码示例。如果您正苦于以下问题:C++ random函数的具体用法?C++ random怎么用?C++ random使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: greeting
//Cracked by Roath
// d/emei/npc/daoming.c 道明小师父
// Shan 96/09/24
inherit NPC;
void greeting(object);
void init();
void create()
{
set_name("道明小师父", ({"daoming", "dao ming"}) );
set("rank_info/respect", "小师父");
set("gender", "男性" );
set("age", 14+random(6));
set("long",
"这是个年龄不大的小师父。他见有人来到,轻轻点头笑了笑。\n");
set("attitude", "friendly");
set("shen_type", 1);
set("class", "bonze");
set("str", 20);
set("int", 28);
set("con", 24);
set("dex", 20);
set("max_qi", 150);
set("max_jing", 100);
set("neili", 150);
set("max_neili", 150);
示例2: radius_msg_add_mppe_keys
int radius_msg_add_mppe_keys(struct radius_msg *msg,
const u8 *req_authenticator,
const u8 *secret, size_t secret_len,
const u8 *send_key, size_t send_key_len,
const u8 *recv_key, size_t recv_key_len)
{
struct radius_attr_hdr *attr;
u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
u8 *buf;
struct radius_attr_vendor *vhdr;
u8 *pos;
size_t elen;
int hlen;
u16 salt;
hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
/* MS-MPPE-Send-Key */
buf = malloc(hlen + send_key_len + 16);
if (buf == NULL) {
return 0;
}
pos = buf;
memcpy(pos, &vendor_id, sizeof(vendor_id));
pos += sizeof(vendor_id);
vhdr = (struct radius_attr_vendor *) pos;
vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
pos = (u8 *) (vhdr + 1);
salt = random() | 0x8000;
*pos++ = salt >> 8;
*pos++ = salt;
encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
secret_len, pos, &elen);
vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
buf, hlen + elen);
free(buf);
if (attr == NULL) {
return 0;
}
/* MS-MPPE-Recv-Key */
buf = malloc(hlen + send_key_len + 16);
if (buf == NULL) {
return 0;
}
pos = buf;
memcpy(pos, &vendor_id, sizeof(vendor_id));
pos += sizeof(vendor_id);
vhdr = (struct radius_attr_vendor *) pos;
vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
pos = (u8 *) (vhdr + 1);
salt ^= 1;
*pos++ = salt >> 8;
*pos++ = salt;
encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
secret_len, pos, &elen);
vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
buf, hlen + elen);
free(buf);
if (attr == NULL) {
return 0;
}
return 1;
}
示例3: rhizome_direct_http_dispatch
void rhizome_direct_http_dispatch(rhizome_direct_sync_request *r)
{
DEBUGF("Dispatch size_high=%lld",r->cursor->size_high);
rhizome_direct_transport_state_http *state = r->transport_specific_state;
int sock=socket(AF_INET, SOCK_STREAM, 0);
if (sock==-1) {
WHY_perror("socket");
goto end;
}
struct hostent *hostent;
hostent = gethostbyname(state->host);
if (!hostent) {
DEBUGF("could not resolve hostname");
goto end;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(state->port);
addr.sin_addr = *((struct in_addr *)hostent->h_addr);
bzero(&(addr.sin_zero),8);
if (connect(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr)) == -1) {
WHY_perror("connect");
close(sock);
goto end;
}
char boundary[20];
char buffer[8192];
strbuf bb = strbuf_local(boundary, sizeof boundary);
strbuf_sprintf(bb, "%08lx%08lx", random(), random());
assert(!strbuf_overrun(bb));
strbuf content_preamble = strbuf_alloca(200);
strbuf content_postamble = strbuf_alloca(40);
strbuf_sprintf(content_preamble,
"--%s\r\n"
"Content-Disposition: form-data; name=\"data\"; filename=\"IHAVEs\"\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n",
boundary
);
strbuf_sprintf(content_postamble, "\r\n--%s--\r\n", boundary);
assert(!strbuf_overrun(content_preamble));
assert(!strbuf_overrun(content_postamble));
int content_length = strbuf_len(content_preamble)
+ r->cursor->buffer_offset_bytes
+ r->cursor->buffer_used
+ strbuf_len(content_postamble);
strbuf request = strbuf_local(buffer, sizeof buffer);
strbuf_sprintf(request,
"POST /rhizome/enquiry HTTP/1.0\r\n"
"Content-Length: %d\r\n"
"Content-Type: multipart/form-data; boundary=%s\r\n"
"\r\n%s",
content_length, boundary, strbuf_str(content_preamble)
);
assert(!strbuf_overrun(request));
/* TODO: Refactor this code so that it uses our asynchronous framework.
*/
int len = strbuf_len(request);
int sent=0;
while(sent<len) {
DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
int count=write(sock,&buffer[sent],len-sent);
if (count == -1) {
if (errno==EPIPE) goto rx;
WHYF_perror("write(%d)", len - sent);
close(sock);
goto end;
}
sent+=count;
}
len=r->cursor->buffer_offset_bytes+r->cursor->buffer_used;
sent=0;
while(sent<len) {
int count=write(sock,&r->cursor->buffer[sent],len-sent);
if (count == -1) {
if (errno == EPIPE)
goto rx;
WHYF_perror("write(%d)", count);
close(sock);
goto end;
}
sent+=count;
}
strbuf_reset(request);
strbuf_puts(request, strbuf_str(content_postamble));
len = strbuf_len(request);
sent=0;
while(sent<len) {
DEBUGF("write(%d, %s, %d)", sock, alloca_toprint(-1, &buffer[sent], len-sent), len-sent);
int count=write(sock,&buffer[sent],len-sent);
if (count == -1) {
//.........这里部分代码省略.........
示例4: create
#include <ansi.h>
inherit NPC;
void create()
{
set_name("张聋子", ({ "zhang longzi", "zhang","longzi" }) );
set("long","一个手艺高超的补鞋皮匠。\n");
set("attitude", "heroism");
set("title", "老皮匠");
set("combat_exp", 220000);
set_skill("unarmed", 70+random(100));
set_skill("sword", 70+random(100));
set_skill("parry", 70+random(100));
set_skill("dodge", 70+random(100));
set_skill("dagger", 150);
set_skill("move", 100+random(100));
set_temp("apply/attack", 70);
set_temp("apply/dodge", 70);
set_temp("apply/damage", 30);
set("chat_chance", 1);
set("chat_msg", ({
"张聋子耷拉着脑袋,喃喃自语:臭小马,死哪里去了!\n",
}) );
setup();
carry_object("/obj/armor/cloth")->wear();
carry_object(__DIR__"obj/skinblade")->wield();
示例5: Migd_GatherLoad
void
Migd_GatherLoad()
{
int oldAllow;
int oldInput;
int oldForeign;
static int iteration = 0;
int numWritten;
int error;
int status;
oldAllow = curVecPtr->allowMigration;
oldInput = curVecPtr->noInput;
oldForeign = curVecPtr->foreignProcs;
if (migd_Debug > 2) {
fprintf(stderr, "Migd_GatherLoad - time %d, oldAllow %d, oldInput %d\n",
time((int *) NULL), oldAllow, oldInput);
}
GetStats(curVecPtr->lengths, &curVecPtr->noInput,
&curVecPtr->foreignProcs);
curVecPtr->timestamp = time((time_t *)0);
ExamineLoads(curVecPtr);
if ((oldInput > migd_Parms.noInput) &&
(curVecPtr->noInput < migd_Parms.noInput) &&
!ignoreInput && !migd_NeverEvict && !refuseMigration) {
Migd_Evict(TRUE);
}
/*
* Send the new load vector to the global daemon periodically,
* or if our migration status changes, or if the number of
* foreign processes goes from zero to non-zero or vice-versa.
* This way the global daemon can track things like the last use
* of a machine by a process that won't release the host when it
* finishes.
*/
if (iteration == 0 || (oldAllow != curVecPtr->allowMigration) ||
(oldForeign > 0 && curVecPtr->foreignProcs == 0) ||
(oldForeign == 0 && curVecPtr->foreignProcs > 0)) {
if (migd_Debug > 2) {
fprintf(stderr,
"Notifying global server, iteration %d, oldAllow %d, newAllow %d, oldForeign %d, newForeign %d.\n",
iteration, oldAllow, curVecPtr->allowMigration,
oldForeign, curVecPtr->foreignProcs);
}
iteration = 0;
/*
* Get the kernel's variable determining whether to refuse
* migrations. We keep rechecking periodically in case it changes.
*/
status = Sys_Stats(SYS_PROC_MIGRATION, SYS_PROC_MIG_GET_STATE,
(Address) &migd_Parms.criteria);
if (status != SUCCESS) {
SYSLOG1(LOG_ERR, "Error in Sys_Stats getting migration state: %s.\n",
Stat_GetMsg(status));
exit(Compat_MapCode(status));
}
ParseMigStatus();
if (curVecPtr->lengths[1] >= 1.0) {
struct timeval tv;
struct timeval curTime;
/*
* The 5-minute load average is over 1. This could
* happen if there is a long-running process but it
* also seems to happen without anything running.
* Sleep a short period of time to try to
* keep from being in lock-step with someone else. There's
* nothing too magical about the number except that it's
* intended to be something that other processes are unlikely
* to sleep for.
*/
tv.tv_sec = 0;
tv.tv_usec = ((random() % 999) + 1) * 1000;
;
if (migd_Debug > 2) {
if (gettimeofday(&curTime,
(struct timezone *) NULL) < 0) {
perror("Error in gettimeofday");
exit(1);
}
fprintf(stderr,
"Sleeping %d usec to avoid lock step, time %d.%d.\n",
tv.tv_usec, curTime.tv_sec, curTime.tv_usec);
}
if (select(0, (int *) NULL, (int *) NULL, (int *) NULL,
&tv) < 0) {
if (migd_Debug > 2) {
perror("select");
}
}
if (migd_Debug > 2) {
if (gettimeofday(&curTime,
(struct timezone *) NULL) < 0) {
perror("Error in gettimeofday");
//.........这里部分代码省略.........
示例6: perform
int perform(object me, object target)
{
string msg,temp,temp1;
int extra,num,num1;
int myexp,yourexp, exp_bonus,cond;
object weapon,shadow,hisweapon,newweapon;
extra = me->query_skill("xinyue-dagger",1);
exp_bonus = (me->query("combat_exp")-3000000)/3000*extra/1000;
if (exp_bonus> extra) exp_bonus=extra;
if(me->query("class")!="wolfmount")
return notify_fail("只有狼山弟子才能使出「斗转星移」的绝技。\n");
if ( extra < 106) return notify_fail("你的[新月斩]还不够纯熟!\n");
if( !target ) target = offensive_target(me);
if( !target
|| !target->is_character()
|| !me->is_fighting(target) )
return notify_fail("[斗转星移]只能对战斗中的对手使用。\n");
weapon = me->query_temp("weapon");
myexp=me->query("combat_exp");
yourexp=target->query("combat_exp");
msg = HIR "$N一声长啸:"NOR+" "+HIC"斗"NOR+" "+HIY"转"NOR+
" "+HIW"星"NOR+" "+HIB"移"NOR+"\n";
message_vision(msg,me);
if ((myexp*3/4+random(myexp*4)>yourexp)&& !target->query_temp("is_unconcious")) {
msg= MAG"\n$N仿佛置身于一个极大的漩涡中,攻出的招式竟然反击回来!\n\n"NOR;
message_vision(msg,target);
seteuid(getuid());
if (!userp(target)) {
sscanf(file_name(target),"%s#%d",temp,num);
shadow=new(temp);
}
else {
shadow=new("/d/fy/npc/shadefigure");
shadow->changeshape(target);
if(hisweapon=target->query_temp("weapon")) {
sscanf(file_name(hisweapon),"%s#%d",temp1,num1);
newweapon=new(temp1);
newweapon->move(shadow);
newweapon->wield();
}
}
shadow->set("owner",me);
shadow->set("possessed",me);
shadow->move(environment(me));
if (!target->query_temp("weapon"))
if (newweapon=shadow->query_temp("weapon"))
newweapon->unequip();
shadow->add_killer(target->query("id"));
simulate_set(target,shadow);
shadow->add_temp("apply/attack", extra/2);
message_vision(HIC " 斗\n" NOR,me);
COMBAT_D->do_attack(shadow,target,msg);
if (target->query_temp("damaged_during_attack"))
target->set_temp("last_damage_from",me);
message_vision(YEL " 转\n" NOR,me);
simulate_set(target,shadow);
COMBAT_D->do_attack(shadow,target,msg);
if (target->query_temp("damaged_during_attack"))
target->set_temp("last_damage_from",me);
message_vision(HIW " 星\n" NOR,me);
simulate_set(target,shadow);
COMBAT_D->do_attack(shadow,target,msg);
if (target->query_temp("damaged_during_attack"))
target->set_temp("last_damage_from",me);
message_vision(HIB " 移\n" NOR,me);
simulate_set(target,shadow);
COMBAT_D->do_attack(shadow,target,msg);
if (target->query_temp("damaged_during_attack"))
target->set_temp("last_damage_from",me);
shadow->add_temp("apply/attack", -extra/2);
if (me->is_killing(target->query("id"))) cond=1;
destruct(shadow);
}
示例7: init_drone_tank
/*QUAKED monster_mytank_commander (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
*/
void init_drone_tank (edict_t *self)
{
// if (deathmatch->value)
// {
// G_FreeEdict (self);
// return;
// }
self->s.modelindex = gi.modelindex ("models/monsters/tank/tris.md2");
VectorSet (self->mins, -24, -24, -16);
VectorSet (self->maxs, 24, 24, 64);
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
sound_pain = gi.soundindex ("tank/tnkpain2.wav");
sound_thud = gi.soundindex ("tank/tnkdeth2.wav");
sound_idle = gi.soundindex ("tank/tnkidle1.wav");
sound_die = gi.soundindex ("tank/death.wav");
sound_step = gi.soundindex ("tank/step.wav");
sound_windup = gi.soundindex ("tank/tnkatck4.wav");
sound_strike = gi.soundindex ("tank/tnkatck5.wav");
sound_sight = gi.soundindex ("tank/sight1.wav");
gi.soundindex ("tank/tnkatck1.wav");
gi.soundindex ("tank/tnkatk2a.wav");
gi.soundindex ("tank/tnkatk2b.wav");
gi.soundindex ("tank/tnkatk2c.wav");
gi.soundindex ("tank/tnkatk2d.wav");
gi.soundindex ("tank/tnkatk2e.wav");
gi.soundindex ("tank/tnkatck3.wav");
// if (self->activator && self->activator->client)
self->health = 100 + 65*self->monsterinfo.level;
//else self->health = 100 + 65*self->monsterinfo.level;
self->max_health = self->health;
self->gib_health = -200;
//if (self->activator && self->activator->client)
self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;
//else self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;
self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD;
self->monsterinfo.max_armor = self->monsterinfo.power_armor_power;
self->monsterinfo.control_cost = M_TANK_CONTROL_COST;
self->monsterinfo.cost = M_TANK_COST;
self->mtype = M_TANK;
if (random() > 0.5)
self->item = FindItemByClassname("ammo_bullets");
else
self->item = FindItemByClassname("ammo_rockets");
self->mass = 500;
//self->pain = mytank_pain;
self->die = mytank_die;
//self->touch = mytank_touch;
self->monsterinfo.stand = mytank_stand;
self->monsterinfo.walk = tank_walk;
self->monsterinfo.run = mytank_run;
self->monsterinfo.dodge = NULL;
self->monsterinfo.attack = mytank_attack;
self->monsterinfo.melee = mytank_melee;
self->monsterinfo.sight = mytank_sight;
self->monsterinfo.idle = mytank_idle;
self->monsterinfo.jumpup = 64;
self->monsterinfo.jumpdn = 512;
self->monsterinfo.aiflags |= AI_NO_CIRCLE_STRAFE;
//self->monsterinfo.melee = 1;
gi.linkentity (self);
self->monsterinfo.currentmove = &mytank_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
// walkmonster_start(self);
self->nextthink = level.time + FRAMETIME;
// self->activator->num_monsters += self->monsterinfo.control_cost;
}
示例8: set
set("str", 10);
set("max_kee", 100);
set("max_gin", 100);
set("force", 100);
set("max_force", 100);
set("force_factor", 4);
set_skill("unarmed", 10);
set_skill("parry", 10);
set_skill("dodge", 10);
set_skill("blade", 10);
set("chat_chance", 25);
set("chat_msg", ({ (: random_move :) }));
setup();
carry_object("/d/obj/cloth/skirt")->wear();
}
int random_move ()
{
object me = this_object();
string *strs = ({
"$N迷人一笑。\n",
"$N张开樱桃小口轻唱起来。\n",
"$N面颊桃红,唱着曲儿。\n",
});
message_vision (strs[random(sizeof(strs))],me);
return 1;
}
示例9: player_die
//.........这里部分代码省略.........
// attacker->client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT /*| EF_AWARD_GAUNTLET*/ );
// attacker->client->ps.eFlags |= EF_AWARD_EXCELLENT;
attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME;
}
// Ridah
}
// done.
attacker->client->lastKillTime = level.time;
}
} else {
AddScore( self, -1 );
}
// Add team bonuses
Team_FragBonuses( self, inflictor, attacker );
// if client is in a nodrop area, don't drop anything
// JPW NERVE new drop behavior
if ( g_gametype.integer == GT_SINGLE_PLAYER ) { // only drop here in single player; in multiplayer, drop @ limbo
contents = trap_PointContents( self->r.currentOrigin, -1 );
if ( !( contents & CONTENTS_NODROP ) ) {
TossClientItems( self );
}
}
// drop flag regardless
if ( g_gametype.integer != GT_SINGLE_PLAYER ) {
if ( self->client->ps.powerups[PW_REDFLAG] ) {
item = BG_FindItem( "Red Flag" );
}
if ( self->client->ps.powerups[PW_BLUEFLAG] ) {
item = BG_FindItem( "Blue Flag" );
}
launchvel[0] = crandom() * 20;
launchvel[1] = crandom() * 20;
launchvel[2] = 10 + random() * 10;
if ( item ) {
flag = LaunchItem( item,self->r.currentOrigin,launchvel );
flag->s.modelindex2 = self->s.otherEntityNum2; // JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
}
}
// jpw
Cmd_Score_f( self ); // show scores
// send updated scores to any clients that are following this one,
// or they would get stale scoreboards
for ( i = 0 ; i < level.maxclients ; i++ ) {
gclient_t *client;
client = &level.clients[i];
if ( client->pers.connected != CON_CONNECTED ) {
continue;
}
if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
continue;
}
if ( client->sess.spectatorClient == self->s.number ) {
Cmd_Score_f( g_entities + i );
}
}
self->takedamage = qtrue; // can still be gibbed
self->s.powerups = 0;
// JPW NERVE -- only corpse in SP; in MP, need CONTENTS_BODY so medic can operate
if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
示例10: G_ArmorDamage
/*
==============
G_ArmorDamage
brokeparts is how many should be broken off now
curbroke is how many are broken
the difference is how many to pop off this time
==============
*/
void G_ArmorDamage( gentity_t *targ ) {
int brokeparts, curbroke;
int numParts;
int dmgbits = 16; // 32/2;
int i;
if ( !targ->client ) {
return;
}
if ( targ->s.aiChar == AICHAR_PROTOSOLDIER ) {
numParts = 9;
} else if ( targ->s.aiChar == AICHAR_SUPERSOLDIER ) {
numParts = 14;
} else if ( targ->s.aiChar == AICHAR_HEINRICH ) {
numParts = 20;
} else {
return;
}
if ( numParts > dmgbits ) {
numParts = dmgbits; // lock this down so it doesn't overwrite any bits that it shouldn't. TODO: fix this
}
// determined here (on server) by location of hit and existing armor, you're updating here so
// the client knows which pieces are still in place, and by difference with previous state, which
// pieces to play an effect where the part is blown off.
// Need to do it here so we have info on where the hit registered (head, torso, legs or if we go with more detail; arm, leg, chest, codpiece, etc)
// ... Ick, just discovered that the refined hit detection ("hit nearest to which tag") is clientside...
// For now, I'll randomly pick a part that hasn't been cleared. This might end up looking okay, and we won't need the refined hits.
// however, we still have control on the server-side of which parts come off, regardless of what shceme is used.
brokeparts = (int)( ( 1 - ( (float)( targ->health ) / (float)( targ->client->ps.stats[STAT_MAX_HEALTH] ) ) ) * numParts );
// RF, remove flame protection after enough parts gone
if ( AICast_NoFlameDamage( targ->s.number ) && ( (float)brokeparts / (float)numParts >= 5.0 / 6.0 ) ) { // figure from DM
AICast_SetFlameDamage( targ->s.number, qfalse );
}
if ( brokeparts && ( ( targ->s.dmgFlags & ( ( 1 << numParts ) - 1 ) ) != ( 1 << numParts ) - 1 ) ) { // there are still parts left to clear
// how many are removed already?
curbroke = 0;
for ( i = 0; i < numParts; i++ ) {
if ( targ->s.dmgFlags & ( 1 << i ) ) {
curbroke++;
}
}
// need to remove more
if ( brokeparts - curbroke >= 1 && curbroke < numParts ) {
for ( i = 0; i < ( brokeparts - curbroke ); i++ ) {
int remove = rand() % ( numParts );
if ( !( ( targ->s.dmgFlags & ( ( 1 << numParts ) - 1 ) ) != ( 1 << numParts ) - 1 ) ) { // no parts are available any more
break;
}
// FIXME: lose the 'while' loop. Still should be safe though, since the check above verifies that it will eventually find a valid part
while ( targ->s.dmgFlags & ( 1 << remove ) ) {
remove = rand() % ( numParts );
}
targ->s.dmgFlags |= ( 1 << remove ); // turn off 'undamaged' part
if ( (int)( random() + 0.5 ) ) { // choose one of two possible replacements
targ->s.dmgFlags |= ( 1 << ( numParts + remove ) );
}
}
}
}
}
示例11: ms_discover_mtu
int ms_discover_mtu(const char *host){
int sock;
int err,mtu=0,new_mtu;
socklen_t optlen;
char port[10];
struct addrinfo hints,*ai=NULL;
int rand_port;
int retry=0;
struct timeval tv;
memset(&hints,0,sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_DGRAM;
gettimeofday(&tv,NULL);
srandom(tv.tv_usec);
rand_port=random() & 0xFFFF;
if (rand_port<1000) rand_port+=1000;
snprintf(port,sizeof(port),"%i",rand_port);
err=getaddrinfo(host,port,&hints,&ai);
if (err!=0){
ms_error("getaddrinfo(): %s\n",gai_strerror(err));
return -1;
}
sock=socket(PF_INET,SOCK_DGRAM,0);
if(sock < 0)
{
ms_error("socket(): %s",strerror(errno));
return sock;
}
mtu=IP_PMTUDISC_DO;
optlen=sizeof(mtu);
err=setsockopt(sock,IPPROTO_IP,IP_MTU_DISCOVER,&mtu,optlen);
if (err!=0){
ms_error("setsockopt(): %s",strerror(errno));
err = close(sock);
if (err!=0)
ms_error("close(): %s", strerror(errno));
return -1;
}
err=connect(sock,ai->ai_addr,ai->ai_addrlen);
freeaddrinfo(ai);
if (err!=0){
ms_error("connect(): %s",strerror(errno));
err = close(sock);
if (err !=0)
ms_error("close(): %s", strerror(errno));
return -1;
}
mtu=1500;
do{
int send_returned;
int datasize=mtu-28;/*minus IP+UDP overhead*/
char *buf=ms_malloc0(datasize);
send_returned = send(sock,buf,datasize,0);
if (send_returned==-1){
/*ignore*/
}
ms_free(buf);
usleep(500000);/*wait for an icmp message come back */
err=getsockopt(sock,IPPROTO_IP,IP_MTU,&new_mtu,&optlen);
if (err!=0){
ms_error("getsockopt(): %s",strerror(errno));
err = close(sock);
if (err!=0)
ms_error("close(): %s", strerror(errno));
return -1;
}else{
ms_message("Partial MTU discovered : %i",new_mtu);
if (new_mtu==mtu) break;
else mtu=new_mtu;
}
retry++;
}while(retry<10);
ms_message("mtu to %s is %i",host,mtu);
err = close(sock);
if (err!=0)
ms_error("close() %s", strerror(errno));
return mtu;
}
示例12: hasPathSum
bool hasPathSum(TreeNode *root, int sum) {
if (random()%2){
return hasPathSum1(root, sum);
}
return hasPathSum2(root, sum);
}
示例13: outchinese
void outchinese(int x0,int y0,char *hz,int color,int size,int speed) /*******汉字输出*********/
{
FILE *fp;
int flag=0;
register int i,j,x,y;
char mat[ZIKU*ZIKU/8];
unsigned char high,low;
unsigned long position=0;
unsigned MASK=0x80;
if ((fp=fopen(".\\source\\hzk16","rb"))==NULL)
{
closegraph();
printf("Error!!!");
exit(0);
}
if (color==EOF) flag=1;
while(*(hz))
{
high=*(hz)-0xa0;
low=*(hz+1)-0xa0;
position = ((high-1)*94+(low-1))*(ZIKU*ZIKU/8L);
fseek(fp, position, SEEK_SET);
fread(mat,sizeof(char),ZIKU*ZIKU/8,fp);
y=y0;
for (i=0;i<10*speed;i++)
delay(20000);
if (size==1)
{
for(i=0;i<ZIKU;i++)
{
x=x0;
for (j = 0; j < ZIKU; j++)
{
if((MASK>>(j%8) & *(mat+ZIKU/8*i+j/8)))
putpixel(x,y,(color==EOF)?random(16):color);
x++;
}
y++;
}
}
else
{
setlinestyle(0,0,1);
setwritemode(COPY_PUT);
for(i=0;i<ZIKU;i++)
{
x=x0;
for (j = 0; j < ZIKU; ++j)
{
if((MASK>>(j%8) & *(mat+ZIKU/8*i+j/8)))
{
if (flag) color=random(16);
setcolor(color);
rectangle(x,y,x+size-1,y+size-1);
setfillstyle(SOLID_FILL,color);
floodfill(x+1,y+1,color);
}
x+=size;
}
y+=size;
}
}
hz+=2;
if (x0+(ZIKU+1)*size>getmaxx()-(ZIKU+1)*size) /*超出屏幕自动换行*/
{
y0+=(ZIKU+1)*size;
x0=0;
}
else
x0+=(ZIKU+1)*size;
}
示例14: read_power
int read_power(double *voltage, double *current)
{
*voltage = ((double)random()-RAND_MAX/2)/(RAND_MAX/2)*1+48;
*current = ((double)random()-RAND_MAX/2)/(RAND_MAX/2)*0.5+1;
return TRUE;
}
示例15: tablesample_init
/*
* Initialize the TABLESAMPLE Descriptor and the TABLESAMPLE Method.
*/
TableSampleDesc *
tablesample_init(SampleScanState *scanstate, TableSampleClause *tablesample)
{
FunctionCallInfoData fcinfo;
int i;
List *args = tablesample->args;
ListCell *arg;
ExprContext *econtext = scanstate->ss.ps.ps_ExprContext;
TableSampleDesc *tsdesc = (TableSampleDesc *) palloc0(sizeof(TableSampleDesc));
/* Load functions */
fmgr_info(tablesample->tsminit, &(tsdesc->tsminit));
fmgr_info(tablesample->tsmnextblock, &(tsdesc->tsmnextblock));
fmgr_info(tablesample->tsmnexttuple, &(tsdesc->tsmnexttuple));
if (OidIsValid(tablesample->tsmexaminetuple))
fmgr_info(tablesample->tsmexaminetuple, &(tsdesc->tsmexaminetuple));
else
tsdesc->tsmexaminetuple.fn_oid = InvalidOid;
fmgr_info(tablesample->tsmreset, &(tsdesc->tsmreset));
fmgr_info(tablesample->tsmend, &(tsdesc->tsmend));
InitFunctionCallInfoData(fcinfo, &tsdesc->tsminit,
list_length(args) + 2,
InvalidOid, NULL, NULL);
tsdesc->tupDesc = scanstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
tsdesc->heapScan = scanstate->ss.ss_currentScanDesc;
/* First argument for init function is always TableSampleDesc */
fcinfo.arg[0] = PointerGetDatum(tsdesc);
fcinfo.argnull[0] = false;
/*
* Second arg for init function is always REPEATABLE
* When tablesample->repeatable is NULL then REPEATABLE clause was not
* specified.
* When specified, the expression cannot evaluate to NULL.
*/
if (tablesample->repeatable)
{
ExprState *argstate = ExecInitExpr((Expr *) tablesample->repeatable,
(PlanState *) scanstate);
fcinfo.arg[1] = ExecEvalExpr(argstate, econtext,
&fcinfo.argnull[1], NULL);
if (fcinfo.argnull[1])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("REPEATABLE clause must be NOT NULL numeric value")));
}
else
{
fcinfo.arg[1] = UInt32GetDatum(random());
fcinfo.argnull[1] = false;
}
/* Rest of the arguments come from user. */
i = 2;
foreach(arg, args)
{
Expr *argexpr = (Expr *) lfirst(arg);
ExprState *argstate = ExecInitExpr(argexpr, (PlanState *) scanstate);
if (argstate == NULL)
{
fcinfo.argnull[i] = true;
fcinfo.arg[i] = (Datum) 0;;
}
fcinfo.arg[i] = ExecEvalExpr(argstate, econtext,
&fcinfo.argnull[i], NULL);
i++;
}