コード例 #1
0
 String PhraseQuery::toString(const String& field)
 {
     StringStream buffer;
     if (this->field != field)
         buffer << this->field << L":";
     buffer << L"\"";
     Collection<String> pieces(Collection<String>::newInstance(maxPosition + 1));
     for (int32_t i = 0; i < terms.size(); ++i)
     {
         int32_t pos = positions[i];
         String s(pieces[pos]);
         if (!s.empty())
             s += L"|";
         s += terms[i]->text();
         pieces[pos] = s;
     }
     for (int32_t i = 0; i < pieces.size(); ++i)
     {
         if (i > 0)
             buffer << L" ";
         String s(pieces[i]);
         buffer << (s.empty() ? L"?" : s);
     }
     buffer << L"\"";
     
     if (slop != 0)
         buffer << L"~" << slop;
     
     buffer << boostString();
     
     return buffer.str();
 }
コード例 #2
0
ファイル: grader.c プロジェクト: Sandeepk94/informatics
int main() {
  int R, N, i;
  int res;

  FILE *f = fopen("birthday.in", "r");
  if (!f)
    fail("Failed to open input file.");

  res = fscanf(f, "%d", &R);
  if (res != 1)
    fail("Failed to read R from input file.");

  res = fscanf(f, "%d", &N);
  if (res != 1)
    fail("Failed to read N from input file.");

  if (N < 1 || N > MAX_N)
    fail("N is out of bounds.");

  for (i = 0; i < N; i++) {
    res = fscanf(f, "%d%d%d%d", &X1[i], &Y1[i], &X2[i], &Y2[i]);
    if (res != 4)
      fail("Failed to read data from input file.");
  }
  fclose(f);

  int answer = pieces(R, N, X1, Y1, X2, Y2);

  printf("%d\n", answer);

  return 0;
}
コード例 #3
0
ファイル: polybook.c プロジェクト: syzygy1/Cfish
static bool check_do_search(const Pos *pos)
{
  akt_position = pieces();
  akt_anz_pieces = popcount(akt_position);

  Bitboard b = akt_position ^ last_position;
  int n2 = popcount(b);

  bool pos_changed =   n2 > 6
                    || akt_position == last_position
                    || akt_anz_pieces > last_anz_pieces
                    || akt_anz_pieces < last_anz_pieces - 2
                    || pos_key() == 0xB4D30CD15A43432D;

  // Reset do_search and book depth counter if postion changed more
  // than one move can do or in initial position
  if (pos_changed) {
    book_depth_count = 0;
    do_search = true;
  }

  last_position = akt_position;
  last_anz_pieces = akt_anz_pieces;

  return do_search;
}
コード例 #4
0
ファイル: polybook.c プロジェクト: syzygy1/Cfish
static Key polyglot_key(const Pos *pos)
{
  Key key = 0;
  Bitboard b = pieces();

  while (b) {
    Square s = pop_lsb(&b);
    Piece p = piece_on(s);

    // PolyGlot pieces are: BP = 0, WP = 1, BN = 2, ... BK = 10, WK = 11
    key ^= PG.Zobrist.psq[2 * (type_of_p(p) - 1) + (color_of(p) == WHITE)][s];
  }

  b = can_castle_any();

  while (b)
    key ^= PG.Zobrist.castle[pop_lsb(&b)];

  if (ep_square())
    key ^= PG.Zobrist.enpassant[file_of(ep_square())];

  if (pos_stm() == WHITE)
    key ^= PG.Zobrist.turn;

  return key;
}
コード例 #5
0
ファイル: search.c プロジェクト: syzygy1/Cfish
static void TB_rank_root_moves(Pos *pos, RootMoves *rm)
{
  TB_RootInTB = 0;
  TB_UseRule50 = option_value(OPT_SYZ_50_MOVE);
  TB_ProbeDepth = option_value(OPT_SYZ_PROBE_DEPTH) * ONE_PLY;
  TB_Cardinality = option_value(OPT_SYZ_PROBE_LIMIT);
  int dtz_available = 1, dtm_available = 0;

  if (TB_Cardinality > TB_MaxCardinality) {
    TB_Cardinality = TB_MaxCardinality;
    TB_ProbeDepth = DEPTH_ZERO;
  }

  TB_CardinalityDTM =  option_value(OPT_SYZ_USE_DTM)
                     ? min(TB_Cardinality, TB_MaxCardinalityDTM)
                     : 0;

  if (TB_Cardinality >= popcount(pieces()) && !can_castle_any()) {
    // Try to rank moves using DTZ tables.
    TB_RootInTB = TB_root_probe_dtz(pos, rm);

    if (!TB_RootInTB) {
      // DTZ tables are missing.
      dtz_available = 0;

      // Try to rank moves using WDL tables as fallback.
      TB_RootInTB = TB_root_probe_wdl(pos, rm);
    }

    // If ranking was successful, try to obtain mate values from DTM tables.
    if (TB_RootInTB && TB_CardinalityDTM >= popcount(pieces()))
      dtm_available = TB_root_probe_dtm(pos, rm);
  }

  if (TB_RootInTB) { // Ranking was successful.
    // Sort moves according to TB rank.
    stable_sort(rm->move, rm->size);

    // Only probe during search if DTM and DTZ are not available
    // and we are winning.
    if (dtm_available || dtz_available || rm->move[0].tbRank <= 0)
      TB_Cardinality = 0;
  }
  else // Ranking was not successful.
    for (int i = 0; i < rm->size; i++)
      rm->move[i].tbRank = 0;
}
コード例 #6
0
QString CaparandomBoard::defaultFenString() const
{
    const int empty = Piece::NoPiece;
    QVector<int> pieces(10);

    // Generate positions until we get one where all the pawns are
    // protected. This usually takes a handful of tries.
    do
    {
        pieces.fill(empty);
        if ((qrand() % 2) == 0)
        {
            addPiece(pieces, Queen, qrand() % 5, 0, 2);
            addPiece(pieces, Archbishop, qrand() % 5, 1, 2);
        }
        else
        {
            addPiece(pieces, Archbishop, qrand() % 5, 0, 2);
            addPiece(pieces, Queen, qrand() % 5, 1, 2);
        }
        addPiece(pieces, Bishop, qrand() % 4, 0, 2);
        addPiece(pieces, Bishop, qrand() % 4, 1, 2);
        addPiece(pieces, Chancellor, qrand() % 6);
        addPiece(pieces, Knight, qrand() % 5);
        addPiece(pieces, Knight, qrand() % 4);
        addPiece(pieces, Rook, 0);
        addPiece(pieces, King, 0);
        addPiece(pieces, Rook, 0);
    }
    while (!pawnsAreSafe(pieces));

    QString fen;

    // Black pieces
    foreach (int pieceType, pieces)
        fen += pieceSymbol(Piece(Side::Black, pieceType));
    fen += '/';
    // Black pawns
    for (int i = 0; i < width(); i++)
        fen += pieceSymbol(Piece(Side::Black, Pawn));
    fen += '/';

    // Empty squares
    for (int i = 0; i < height() - 4; i++)
        fen += QString::number(pieces.size()) + '/';

    // White pawns
    for (int i = 0; i < width(); i++)
        fen += pieceSymbol(Piece(Side::White, Pawn));
    fen += '/';
    // White pieces
    foreach (int pieceType, pieces)
        fen += pieceSymbol(Piece(Side::White, pieceType));

    // Side to move, castling rights, enpassant square, etc.
    fen += " w KQkq - 0 1";

    return fen;
}
コード例 #7
0
boost::optional<Doublet> Higgs::MassDrop(Doublet const& doublet)
{
    INFO0;
    auto cluster_sequence = ClusterSequence{doublet.Constituents(), Settings::JetDefinition(doublet.DeltaR() + 2. * Settings::JetConeSize())};
    auto exclusive_jets = cluster_sequence.ExclusiveJets(1);
    if (exclusive_jets.empty()) return boost::none;
    auto mass_drop_tagger = fastjet::MassDropTagger{0.667, 0.09};
    auto mass_drop_jet = mass_drop_tagger(exclusive_jets.front().FastJet());
    if (mass_drop_jet == 0) return boost::none;

    auto radius = boca::Jet(mass_drop_jet.pieces().at(0)).DeltaRTo(mass_drop_jet.pieces().at(1));
    radius = std::min(radius / 2., 300_mrad);
    auto filter = fastjet::Filter{Settings::JetDefinition(radius), fastjet::SelectorNHardest(3)};
    auto filtered_jet = filter.result(mass_drop_jet);
    if (!filtered_jet.has_pieces()) return boost::none;
    auto pieces = SortedByPt(JetVector(filtered_jet.pieces()));
    if (pieces.size() < 2) return boost::none;
    return Doublet(bottom_reader_.Multiplet(pieces.at(0)), bottom_reader_.Multiplet(pieces.at(1)));
}
コード例 #8
0
ファイル: row.cpp プロジェクト: Bobspadger/pyodbc
static PyObject* Row_repr(PyObject* o)
{
    Row* self = (Row*)o;

    if (self->cValues == 0)
        return PyString_FromString("()");

    Object pieces(PyTuple_New(self->cValues));
    if (!pieces)
        return 0;

    Py_ssize_t length = 2 + (2 * (self->cValues-1)); // parens + ', ' separators

    for (Py_ssize_t i = 0; i < self->cValues; i++)
    {
        PyObject* piece = PyObject_Repr(self->apValues[i]);
        if (!piece)
            return 0;

        length += Text_Size(piece);

        PyTuple_SET_ITEM(pieces.Get(), i, piece);
    }

    if (self->cValues == 1)
    {
        // Need a trailing comma: (value,)
        length += 2;
    }

    PyObject* result = Text_New(length);
    if (!result)
        return 0;
    TEXT_T* buffer = Text_Buffer(result);
    Py_ssize_t offset = 0;
    buffer[offset++] = '(';
    for (Py_ssize_t i = 0; i < self->cValues; i++)
    {
        PyObject* item = PyTuple_GET_ITEM(pieces.Get(), i);
        memcpy(&buffer[offset], Text_Buffer(item), Text_Size(item) * sizeof(TEXT_T));
        offset += Text_Size(item);

        if (i != self->cValues-1 || self->cValues == 1)
        {
            buffer[offset++] = ',';
            buffer[offset++] = ' ';
        }
    }
    buffer[offset++] = ')';

    I(offset == length);

    return result;
}
コード例 #9
0
ファイル: ANUDTC.cpp プロジェクト: anubhav914/spoj-problems
int main(){
	int T, N;
	const char *ans = "ny";
	scanf("%d", &T);
	while(T--){
		scanf("%d", &N);
		printf("%c %c %c\n", 
				ans[equalPieces(360, N)],
				ans[pieces(360, N)],
				ans[allUnequalPices(360, N)]
			);
	}
}
コード例 #10
0
ファイル: Patch.cpp プロジェクト: AmbientMalice/pcsx2
	void patchHelper(const wxString& cmd, const wxString& param) {
		// Error Handling Note:  I just throw simple wxStrings here, and then catch them below and
		// format them into more detailed cmd+data+error printouts.  If we want to add user-friendly
		// (translated) messages for display in a popup window then we'll have to upgrade the
		// exception a little bit.

		// print the actual patch lines only in verbose mode (even in devel)
		if (DevConWriterEnabled)
			DevCon.WriteLn(cmd + L" " + param);

		try
		{
			if (isCheat && cheatnumber >= MAX_CHEAT)
				throw wxString( L"Maximum number of cheats reached" );
			if(!isCheat && patchnumber >= MAX_PATCH)
				throw wxString( L"Maximum number of patches reached" );

			IniPatch& iPatch = isCheat ? Cheat[cheatnumber] : Patch[patchnumber];
			PatchPieces pieces(param);

			iPatch.enabled = 0;

			iPatch.placetopatch	= StrToU32(pieces.PlaceToPatch(), 10);
			iPatch.cpu			= (patch_cpu_type)PatchTableExecute(pieces.CpuType(), cpuCore);
			iPatch.addr			= StrToU32(pieces.MemAddr(), 16);
			iPatch.type			= (patch_data_type)PatchTableExecute(pieces.OperandSize(), dataType);
			iPatch.data			= StrToU64(pieces.WriteValue(), 16);

			if (iPatch.cpu  == 0)
				throw wxsFormat(L"Unrecognized CPU Target: '%s'", WX_STR(pieces.CpuType()));

			if (iPatch.type == 0)
				throw wxsFormat(L"Unrecognized Operand Size: '%s'", WX_STR(pieces.OperandSize()));

			iPatch.enabled = 1; // omg success!!

			if (isCheat) cheatnumber++;
			else		 patchnumber++;
		}
		catch( wxString& exmsg )
		{
			Console.Error(L"(Patch) Error Parsing: %s=%s", WX_STR(cmd), WX_STR(param));
			Console.Indent().Error( exmsg );
		}
	}
コード例 #11
0
ファイル: GamePlayScene.cpp プロジェクト: marcnialet/eljoc
void GamePlay::setNeighbours()
{
    if(this->vectorOfPieces.size()<=0) return;
    
    for (auto &p: this->vectorOfPieces)
    {
        p->clearNeighbours();
    }
    
    vector<Piece *> pieces(this->vectorOfPieces);
    while (!pieces.empty())
    {
        auto piece = pieces.back();
        pieces.pop_back();
        
        vector<Piece *> neighbours = this->getPieceNeighbours(piece, pieces);
        this->setPieceNeighbours(piece, neighbours);
    }
}
コード例 #12
0
ファイル: video.c プロジェクト: marek5050/Telescope-Guvcview
/* run in a thread (SDL overlay)*/
void *main_loop(void *data)
{
    struct ALL_DATA *all_data = (struct ALL_DATA *) data;

    struct VidState *s = all_data->s;
    struct paRecordData *pdata = all_data->pdata;
    struct GLOBAL *global = all_data->global;
    struct focusData *AFdata = all_data->AFdata;
    struct vdIn *videoIn = all_data->videoIn;

    struct particle* particles = NULL; //for the particles video effect

    SDL_Event event;
    /*the main SDL surface*/
    SDL_Surface *pscreen = NULL;
    SDL_Overlay *overlay = NULL;
    SDL_Rect drect;

    int width = global->width;
    int height = global->height;
    int format = global->format;

    SAMPLE vuPeak[2];  // The maximum vuLevel seen recently
    int vuPeakFreeze[2]; // The vuPeak values will be frozen for this many frames.
    vuPeak[0] = vuPeak[1] = 0;
    vuPeakFreeze[0] = vuPeakFreeze[1] = 0;

    BYTE *p = NULL;

    Control *focus_control = NULL;
    int last_focus = 0;

    if (global->AFcontrol)
    {
        focus_control = get_ctrl_by_id(s->control_list, AFdata->id);
        get_ctrl(videoIn->fd, s->control_list, AFdata->id, all_data);
        last_focus = focus_control->value;
        /*make sure we wait for focus to settle on first check*/
        if (last_focus < 0) last_focus = AFdata->f_max;
    }

    gboolean capVid = FALSE;
    gboolean signalquit = FALSE;

    /*------------------------------ SDL init video ---------------------*/
    if(!global->no_display)
    {
        overlay = video_init(data, &(pscreen));

        if(overlay == NULL)
        {
            g_print("FATAL: Couldn't create yuv overlay - please disable hardware accelaration\n");
            signalquit = TRUE; /*exit video thread*/
        }
        else
        {
            p = (unsigned char *) overlay->pixels[0];

            drect.x = 0;
            drect.y = 0;
            drect.w = pscreen->w;
            drect.h = pscreen->h;
        }
    }

    while (!signalquit)
    {
        __LOCK_MUTEX(__VMUTEX);
            capVid = videoIn->capVid;
            signalquit = videoIn->signalquit;
        __UNLOCK_MUTEX(__VMUTEX);

        /*-------------------------- Grab Frame ----------------------------------*/
        if (uvcGrab(videoIn, format, width, height, &global->fps, &global->fps_num) < 0)
        {
            g_printerr("Error grabbing image \n");
            continue;
        }
        else
        {
            if(!videoIn->timestamp)
            {
                global->skip_n++; //skip this frame
            }

            if(capVid)
            {
                if(global->framecount < 1)
                {
					/*reset video start time to first frame capture time */
					global->Vidstarttime = videoIn->timestamp;
					/** set current time for audio ts(0) reference (MONOTONIC)
					 *  only used if we have no audio capture before video
					 */
					__LOCK_MUTEX(__AMUTEX);
						pdata->ts_ref = ns_time_monotonic();
					__UNLOCK_MUTEX(__AMUTEX);
					//printf("video ts ref: %llu audio ts_ ref: %llu\n",global->Vidstarttime, pdata->ts_ref);
					global->v_ts = 0;
                }
                else
                {
                    global->v_ts = videoIn->timestamp - global->Vidstarttime;
                    /*always use the last frame time stamp for video stop time*/
                    global->Vidstoptime = videoIn->timestamp;
                }
            }

            if (global->FpsCount && !global->no_display)
            {/* sets fps count in window title bar */
                global->frmCount++;
                if (global->DispFps>0)
                { /*set every 2 sec*/
                    g_snprintf(global->WVcaption,24,"GUVCVideo - %3.2f fps",global->DispFps);
                    SDL_WM_SetCaption(global->WVcaption, NULL);

                    global->frmCount=0;/*resets*/
                    global->DispFps=0;
                }
            }

            /*---------------- autofocus control ------------------*/

            if (global->AFcontrol && (global->autofocus || AFdata->setFocus))
            { /*AFdata = NULL if no focus control*/
                if (AFdata->focus < 0)
                {
                    /*starting autofocus*/
                    AFdata->focus = AFdata->left; /*start left*/
                    focus_control->value = AFdata->focus;
                    if (set_ctrl (videoIn->fd, s->control_list, AFdata->id) != 0)
                        g_printerr("ERROR: couldn't set focus to %d\n", AFdata->focus);
                    /*number of frames until focus is stable*/
                    /*1.4 ms focus time - every 1 step*/
                    AFdata->focus_wait = (int) abs(AFdata->focus-last_focus)*1.4/(1000/global->fps)+1;
                    last_focus = AFdata->focus;
                }
                else
                {
                    if (AFdata->focus_wait == 0)
                    {
                        AFdata->sharpness=getSharpness (videoIn->framebuffer, width, height, 5);
                        if (global->debug)
                            g_print("sharp=%d focus_sharp=%d foc=%d right=%d left=%d ind=%d flag=%d\n",
                                AFdata->sharpness,AFdata->focus_sharpness,
                                AFdata->focus, AFdata->right, AFdata->left,
                                AFdata->ind, AFdata->flag);
                        AFdata->focus=getFocusVal (AFdata);
                        if ((AFdata->focus != last_focus))
                        {
                            focus_control->value = AFdata->focus;
                            if (set_ctrl (videoIn->fd, s->control_list, AFdata->id) != 0)
                                g_printerr("ERROR: couldn't set focus to %d\n",
                                    AFdata->focus);
                            /*number of frames until focus is stable*/
                            /*1.4 ms focus time - every 1 step*/
                            AFdata->focus_wait = (int) abs(AFdata->focus-last_focus)*1.4/(1000/global->fps)+1;
                        }
                        last_focus = AFdata->focus;
                    }
                    else
                    {
                        AFdata->focus_wait--;
                        if (global->debug) g_print("Wait Frame: %d\n",AFdata->focus_wait);
                    }
                }
            }
        }
        /*------------------------- Filter Frame ---------------------------------*/
        __LOCK_MUTEX(__GMUTEX);
        if(global->Frame_Flags>0)
        {
            if((global->Frame_Flags & YUV_PARTICLES)==YUV_PARTICLES)
                particles = particles_effect(videoIn->framebuffer, width, height, 20, 4, particles);

            if((global->Frame_Flags & YUV_MIRROR)==YUV_MIRROR)
                yuyv_mirror(videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_UPTURN)==YUV_UPTURN)
                yuyv_upturn(videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_NEGATE)==YUV_NEGATE)
                yuyv_negative (videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_MONOCR)==YUV_MONOCR)
                yuyv_monochrome (videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_PIECES)==YUV_PIECES)
                pieces (videoIn->framebuffer, width, height, 16 );

        }
        __UNLOCK_MUTEX(__GMUTEX);
        /*-------------------------capture Image----------------------------------*/
        if (videoIn->capImage)
        {
            /*
             * format and resolution can change(enabled) while capturing the frame
             * but you would need to be speedy gonzalez to press two buttons
             * at almost the same time :D
             */
            int ret = 0;
            if((ret=store_picture(all_data)) < 0)
                g_printerr("saved image to:%s ...Failed \n",videoIn->ImageFName);
            else if (!ret && global->debug) g_print("saved image to:%s ...OK \n",videoIn->ImageFName);

            videoIn->capImage=FALSE;
        }
        /*---------------------------capture Video---------------------------------*/
        if (capVid && !(global->skip_n))
        {
            __LOCK_MUTEX(__VMUTEX);
                if(videoIn->VidCapStop) videoIn->VidCapStop = FALSE;
            __UNLOCK_MUTEX(__VMUTEX);
            int res=0;

			/* format and resolution don't change(disabled) while capturing video
			 * store_video_frame may sleep if needed to avoid buffer overrun
			 */
            if((res=store_video_frame(all_data))<0) g_printerr("WARNING: droped frame (%i)\n",res);

        } /*video and audio capture have stopped */
        else
        {
            __LOCK_MUTEX(__VMUTEX);
                if(!(videoIn->VidCapStop)) videoIn->VidCapStop=TRUE;
            __UNLOCK_MUTEX(__VMUTEX);
        }

        /* decrease skip frame count */
        if (global->skip_n > 0)
        {
            if (global->debug && capVid) g_print("skiping frame %d...\n", global->skip_n);
            global->skip_n--;
        }

        __LOCK_MUTEX( __AMUTEX );
            if (global->Sound_enable && capVid) pdata->skip_n = global->skip_n;
        __UNLOCK_MUTEX( __AMUTEX );

        /*------------------------- Display Frame --------------------------------*/
        if(!global->no_display)
        {
			if (global->osdFlags && pdata->audio_buff[0])
			{
				draw_vu_meter(width, height, vuPeak, vuPeakFreeze, data);
			}
            SDL_LockYUVOverlay(overlay);
            memcpy(p, videoIn->framebuffer, width * height * 2);
            SDL_UnlockYUVOverlay(overlay);
            SDL_DisplayYUVOverlay(overlay, &drect);

            /*------------------------- Read Key events ------------------------------*/
            /* Poll for events */
            while( SDL_PollEvent(&event) )
            {
                //printf("event type:%i  event key:%i\n", event.type, event.key.keysym.scancode);
                if(event.type==SDL_KEYDOWN)
                {
                    if (videoIn->PanTilt)
                    {
                        switch( event.key.keysym.sym )
                        {
                            /* Keyboard event */
                            /* Pass the event data onto PrintKeyInfo() */
                            case SDLK_DOWN:
                                /*Tilt Down*/
                                uvcPanTilt (videoIn->fd, s->control_list, 0, 1);
                                break;

                            case SDLK_UP:
                                /*Tilt UP*/
                                uvcPanTilt (videoIn->fd, s->control_list, 0, -1);
                                break;

                            case SDLK_LEFT:
                                /*Pan Left*/
                                uvcPanTilt (videoIn->fd, s->control_list, 1, 1);
                                break;

                            case SDLK_RIGHT:
                                /*Pan Right*/
                                uvcPanTilt (videoIn->fd, s->control_list, 1, -1);
                                break;
                            default:
                                break;
                        }
                    }
                    switch( event.key.keysym.scancode )
                    {
                        case 220: /*webcam button*/
                            //gdk_threads_enter();
                           	if (all_data->global->default_action == 0)
                           		g_main_context_invoke(NULL, image_capture_callback, (gpointer) all_data);
							else
                            	g_main_context_invoke(NULL, video_capture_callback, (gpointer) all_data);
                       
                            break;
                    }
                    switch( event.key.keysym.sym )
                    {
                        case SDLK_q:
                            //shutDown
                            g_timeout_add(200, shutd_timer, all_data);
                            g_print("q pressed - Quiting...\n");
                            break;
                        case SDLK_SPACE:
							{
                            if(global->AFcontrol > 0)
                                setfocus_clicked(NULL, all_data);
							}
                            break;
                        case SDLK_i:
							g_main_context_invoke(NULL, image_capture_callback, (gpointer) all_data);
							break;
						case SDLK_v:
							g_main_context_invoke(NULL, video_capture_callback, (gpointer) all_data);
							break;
                        default:
                            break;
                    }
                }
                if(event.type==SDL_VIDEORESIZE)
                {
                    pscreen =
                        SDL_SetVideoMode(event.resize.w,
                                 event.resize.h,
                                 global->bpp,
                                 SDL_VIDEO_Flags);
                    drect.w = event.resize.w;
                    drect.h = event.resize.h;
                }
                if(event.type==SDL_QUIT)
                {
                    //shutDown
                    g_timeout_add(200, shutd_timer, all_data);
                }
            }
        }
        /* if set make the thread sleep - default no sleep (full throttle)*/
        if(global->vid_sleep) sleep_ms(global->vid_sleep);

        /*------------------------------------------*/
        /*  restart video (new resolution/format)   */
        /*------------------------------------------*/
        if (global->change_res)
        {
            g_print("setting new resolution (%d x %d)\n", global->width, global->height);
            /*clean up */

            if(particles) g_free(particles);
            particles = NULL;

            if (global->debug) g_print("cleaning buffer allocations\n");
            fflush(NULL);//flush all output buffers

            if(!global->no_display)
            {
                SDL_FreeYUVOverlay(overlay);
                overlay = NULL;
            }
            /*init device*/
            restart_v4l2(videoIn, global);
            /*set new resolution for video thread*/
            width = global->width;
            height = global->height;
            format = global->format;
            /* restart SDL with new values*/
            if(!global->no_display)
            {
                overlay = video_init(data, &(pscreen));
                if(overlay == NULL)
                {
                    g_print("FATAL: Couldn't create yuv overlay - please disable hardware accelaration\n");
                    signalquit = TRUE; /*exit video thread*/
                }
                else
                {
                    if (global->debug) g_print("yuv overlay created (%ix%i).\n", overlay->w, overlay->h);
                    p = (unsigned char *) overlay->pixels[0];

                    drect.x = 0;
                    drect.y = 0;
                    drect.w = pscreen->w;
                    drect.h = pscreen->h;

                    global->change_res = FALSE;
                }
            }
            else global->change_res = FALSE;
        }

    }/*loop end*/

    __LOCK_MUTEX(__VMUTEX);
        capVid = videoIn->capVid;
    __UNLOCK_MUTEX(__VMUTEX);
    /*check if thread exited while in Video capture mode*/
    if (capVid)
    {
        /*stop capture*/
        if (global->debug) g_print("stoping Video capture\n");
        //global->Vidstoptime = ns_time_monotonic(); /*this is set in IO thread*/
        videoIn->VidCapStop=TRUE;
        capVid = FALSE;
        __LOCK_MUTEX(__VMUTEX);
            videoIn->capVid = capVid;
        __UNLOCK_MUTEX(__VMUTEX);
        __LOCK_MUTEX(__AMUTEX);
            pdata->capVid = capVid;
        __UNLOCK_MUTEX(__AMUTEX);
        /*join IO thread*/
        if (global->debug) g_print("Shuting Down IO Thread\n");
        __THREAD_JOIN( all_data->IO_thread );
        if (global->debug) g_print("IO Thread finished\n");
    }

    if (global->debug) g_print("Thread terminated...\n");
    p = NULL;
    if(particles) g_free(particles);
    particles=NULL;

    if (global->debug) g_print("cleaning Thread allocations: 100%%\n");
    fflush(NULL);//flush all output buffers

    if(!global->no_display)
    {
        if(overlay)
            SDL_FreeYUVOverlay(overlay);
        //SDL_FreeSurface(pscreen);

        SDL_Quit();
    }

    if (global->debug) g_print("Video thread completed\n");

    global = NULL;
    AFdata = NULL;
    videoIn = NULL;
    return ((void *) 0);
}
コード例 #13
0
bool QgsGeoPackageCollectionItem::deleteGeoPackageRasterLayer( const QString &uri, QString &errCause )
{
  bool result = false;
  // Better safe than sorry
  if ( ! uri.isEmpty( ) )
  {
    QVariantMap pieces( QgsProviderRegistry::instance()->decodeUri( QStringLiteral( "gdal" ), uri ) );
    QString baseUri = pieces[QStringLiteral( "path" )].toString();
    QString layerName = pieces[QStringLiteral( "layerName" )].toString();

    if ( baseUri.isEmpty() || layerName.isEmpty() )
    {
      errCause = QStringLiteral( "Layer URI is malformed: layer <b>%1</b> cannot be deleted!" ).arg( uri );
    }
    else
    {
      sqlite3_database_unique_ptr database;
      int status = database.open_v2( baseUri, SQLITE_OPEN_READWRITE, nullptr );
      if ( status != SQLITE_OK )
      {
        errCause = sqlite3_errmsg( database.get() );
      }
      else
      {
        // Remove table
        char *errmsg = nullptr;
        char *sql = sqlite3_mprintf(
                      "DROP table IF EXISTS \"%w\";"
                      "DELETE FROM gpkg_contents WHERE table_name = '%q';"
                      "DELETE FROM gpkg_tile_matrix WHERE table_name = '%q';"
                      "DELETE FROM gpkg_tile_matrix_set WHERE table_name = '%q';",
                      layerName.toUtf8().constData(),
                      layerName.toUtf8().constData(),
                      layerName.toUtf8().constData(),
                      layerName.toUtf8().constData() );
        status = sqlite3_exec(
                   database.get(),               /* An open database */
                   sql,                          /* SQL to be evaluated */
                   nullptr,                      /* Callback function */
                   nullptr,                      /* 1st argument to callback */
                   &errmsg                       /* Error msg written here */
                 );
        sqlite3_free( sql );
        // Remove from optional tables, may silently fail
        QStringList optionalTables;
        optionalTables << QStringLiteral( "gpkg_extensions" )
                       << QStringLiteral( "gpkg_metadata_reference" );
        for ( const QString &tableName : qgis::as_const( optionalTables ) )
        {
          char *sql = sqlite3_mprintf( "DELETE FROM %w WHERE table_name = '%q'",
                                       tableName.toUtf8().constData(),
                                       layerName.toUtf8().constData() );
          ( void )sqlite3_exec(
            database.get(),                      /* An open database */
            sql,                                 /* SQL to be evaluated */
            nullptr,                             /* Callback function */
            nullptr,                             /* 1st argument to callback */
            nullptr                              /* Error msg written here */
          );
          sqlite3_free( sql );
        }
        // Other tables, ignore errors
        {
          char *sql = sqlite3_mprintf( "DELETE FROM gpkg_2d_gridded_coverage_ancillary WHERE tile_matrix_set_name = '%q'",
                                       layerName.toUtf8().constData() );
          ( void )sqlite3_exec(
            database.get(),                      /* An open database */
            sql,                                 /* SQL to be evaluated */
            nullptr,                             /* Callback function */
            nullptr,                             /* 1st argument to callback */
            nullptr                              /* Error msg written here */
          );
          sqlite3_free( sql );
        }
        {
          char *sql = sqlite3_mprintf( "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE tpudt_name = '%q'",
                                       layerName.toUtf8().constData() );
          ( void )sqlite3_exec(
            database.get(),                      /* An open database */
            sql,                                 /* SQL to be evaluated */
            nullptr,                             /* Callback function */
            nullptr,                             /* 1st argument to callback */
            nullptr                              /* Error msg written here */
          );
          sqlite3_free( sql );
        }

        if ( status == SQLITE_OK )
        {
          result = true;
        }
        else
        {
          errCause = tr( "There was an error deleting the layer %1: %2" ).arg( layerName, QString::fromUtf8( errmsg ) );
        }
        sqlite3_free( errmsg );
      }
    }
  }
  else
  {
    // This should never happen!
    errCause = tr( "Layer URI is empty: layer cannot be deleted!" );
  }
  return result;
}
コード例 #14
0
ファイル: GamePlayScene.cpp プロジェクト: marcnialet/eljoc
void GamePlay::findChains()
{
    vector<vector<Piece *>> chains;
    
    vector<Piece *> pieces(this->vectorOfPieces);
    
    while (!pieces.empty())
    {
        auto piece = pieces.back();
        pieces.pop_back();
        if(piece->hasNeighbours())
        {
            vector<Piece *> list;
            list.push_back(piece);
            
            this->findChildChain(list, piece, pieces);
            
            chains.push_back(list);
        }
    }
    if(chains.size()>0)
    {
        // log("Chain in found: %d", (int)chains.size());
        if(chains.size()>0)
        {
            int combosize = 0;
            for (auto &chain: chains)
            {
                if(chain.size()>=3)
                {
                    this->statistics->addChain(chain.size());
                    combosize++;
                    for (auto &piece: chain)
                    {
                        for( vector<Piece*>::iterator iter = this->vectorOfPieces.begin(); iter != this->vectorOfPieces.end(); ++iter )
                        {
                            if( *iter == piece )
                            {
                                for (int k=0; k<this->vectorOfGlasses.size();k++)
                                {
                                    auto glasspiece = vectorOfGlasses[k];
                                    if(glasspiece->getIndexPosition()==piece->getIndexPosition())
                                    {
                                        glasspiece->decreaseStrong();
                                        if(glasspiece->getStrong()==0)
                                        {
                                            this->vectorOfGlasses.erase (vectorOfGlasses.begin()+k);
                                            this->removeChild(glasspiece);
                                            break;
                                        }
                                    }
                                }
                                
                                auto callback = CallFunc::create(CC_CALLBACK_0(GamePlay::removePieceCallback, this, piece));
                                auto scale = ScaleTo::create(0.500,0.1);
                                auto fadeOut = FadeOut::create(0.100);
                                auto sequence = Sequence::create(scale, fadeOut, callback, NULL);
                                piece->runAction(sequence);
                                
                                this->vectorOfPositions.push_back(piece->getIndexPosition());
                                this->vectorOfPieces.erase( iter );
                                break;
                            }
                        }
                    }
                }
            }
            if(combosize>1)
            {
                this->statistics->addCombo(combosize);
            }
        }
    }
}
コード例 #15
0
ファイル: Halite.cpp プロジェクト: chmullig/Halite
std::vector<bool> Halite::processNextFrame(std::vector<bool> alive) {

	//Update alive frame counts
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) alive_frame_count[a]++;

	//Create threads to send/receive data to/from players. The threads should return a float of how much time passed between the end of their message being sent and the end of the AI's message being sent.
	std::vector< std::future<unsigned int> > frameThreads(std::count(alive.begin(), alive.end(), true));
	unsigned char threadLocation = 0; //Represents place in frameThreads.

	//Figure out how long each AI is permitted to respond without penalty in milliseconds.
	std::vector<int> allowableTimesToRespond(number_of_players);
	const int BOT_FRAME_TIMEOUT_MILLIS = 50 + ((game_map.map_width * game_map.map_height) / 2);
	for(unsigned char a = 0; a < number_of_players; a++) allowableTimesToRespond[a] = BOT_FRAME_TIMEOUT_MILLIS;

	//Stores the messages sent by bots this frame
	for(unsigned char a = 0; a < number_of_players; a++) {
		if(alive[a]) {
			frameThreads[threadLocation] = std::async(&Networking::handleFrameNetworking, &networking, allowableTimesToRespond[a], a + 1, game_map, &player_moves[a]);
			threadLocation++;
		}
	}

	std::vector< std::vector<unsigned char> > moveDirections(game_map.map_height, std::vector<unsigned char>(game_map.map_width, 0));

	//Join threads. Figure out if the player responded in an allowable amount of time or if the player has timed out.
	std::vector<unsigned short> permissibleTime(number_of_players, false);
	threadLocation = 0; //Represents place in frameThreads.
	for(unsigned char a = 0; a < number_of_players; a++) {
		if(alive[a]) {
			unsigned short millis = frameThreads[threadLocation].get();
			if(millis < BOT_FRAME_TIMEOUT_MILLIS) {
				permissibleTime[a] = true;
			}
			//	There was an exception in the networking thread or the player timed out. Either way, kill their thread
			else {
				if(!program_output_style) std::cout << player_names[a] << " timed out\n";
				permissibleTime[a] = false;
				networking.killPlayer(a + 1);
			}
			threadLocation++;
			total_response_time[a] += millis;
		}
	}

	std::vector< std::map<hlt::Location, unsigned char> > pieces(number_of_players);

	//For each player, use their moves to create the pieces map.
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) {
		//Add in pieces according to their moves. Also add in a second piece corresponding to the piece left behind.
		for(auto b = player_moves[a].begin(); b != player_moves[a].end(); b++) if(game_map.inBounds(b->loc) && game_map.getSite(b->loc, STILL).owner == a + 1) {
			if(b->dir == STILL) {
				if(game_map.getSite(b->loc, STILL).strength + game_map.getSite(b->loc, STILL).production <= 255) game_map.getSite(b->loc, STILL).strength += game_map.getSite(b->loc, STILL).production;
				else game_map.getSite(b->loc, STILL).strength = 255;
				//Update full still count
				full_still_count[a]++;
				//Add to full production
				full_production_count[a] += game_map.getSite(b->loc, STILL).production;
			}
			//Update full caridnal count.
			else full_cardinal_count[a]++;

			//Update moves
			moveDirections[b->loc.y][b->loc.x] = b->dir;

			hlt::Location newLoc = game_map.getLocation(b->loc, b->dir);
			if(pieces[a].count(newLoc)) {
				if(short(pieces[a][newLoc]) + game_map.getSite(b->loc, STILL).strength <= 255) pieces[a][newLoc] += game_map.getSite(b->loc, STILL).strength;
				else pieces[a][newLoc] = 255;
			}
			else {
				pieces[a].insert(std::pair<hlt::Location, unsigned char>(newLoc, game_map.getSite(b->loc, STILL).strength));
			}

			//Add in a new piece with a strength of 0 if necessary.
			if(!pieces[a].count(b->loc)) {
				pieces[a].insert(std::pair<hlt::Location, unsigned char>(b->loc, 0));
			}

			//Erase from the game map so that the player can't make another move with the same piece.
			game_map.getSite(b->loc, STILL).owner = 0;
			game_map.getSite(b->loc, STILL).strength = 0;
		}
	}

	//Add in all of the remaining pieces whose moves weren't specified.
	for(unsigned short a = 0; a < game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) {
		hlt::Location l = { b, a };
		hlt::Site & s = game_map.getSite(l, STILL);
		if(s.owner != 0) {
			if(short(s.strength) + s.production <= 255) {
				s.strength += s.production;
			}
			else s.strength = 255;
			if(pieces[s.owner - 1].count(l)) {
				if(short(pieces[s.owner - 1][l]) + s.strength <= 255) pieces[s.owner - 1][l] += s.strength;
				else pieces[s.owner - 1][l] = 255;
			}
			else {
				pieces[s.owner - 1].insert(std::pair<hlt::Location, unsigned char>(l, s.strength));
			}
			//Add to full production
			full_production_count[s.owner - 1] += s.production;
			//Update full still count
			full_still_count[s.owner - 1]++;
			//Erase from game map.
			s.owner = 0;
			s.strength = 0;
		}
	}

	std::vector< std::map<hlt::Location, unsigned short> > toInjure(number_of_players);
	std::vector< std::vector<unsigned short> > injureMap(game_map.map_height, std::vector<unsigned short>(game_map.map_width, 0));

	//Sweep through locations and find the correct damage for each piece. Start by applying damage within only the active strengths.
	for(unsigned char a = 0; a != game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) {
		hlt::Location l = { b, a };
		for(unsigned short c = 0; c < number_of_players; c++) if(alive[c] && pieces[c].count(l)) {
			for(unsigned short d = 0; d < number_of_players; d++) if(d != c && alive[d]) {
				hlt::Location tempLoc = l;
				//Check 'STILL' square. We also need to deal with the threshold here:
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'NORTH' square:
				tempLoc = game_map.getLocation(l, NORTH);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'EAST' square:
				tempLoc = game_map.getLocation(l, EAST);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'SOUTH' square:
				tempLoc = game_map.getLocation(l, SOUTH);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
				//Check 'WEST' square:
				tempLoc = game_map.getLocation(l, WEST);
				if(pieces[d].count(tempLoc)) {
					//Apply damage, but not more than they have strength:
					if(toInjure[d].count(tempLoc)) toInjure[d][tempLoc] += pieces[c][l];
					else toInjure[d].insert(std::pair<hlt::Location, unsigned short>(tempLoc, pieces[c][l]));
				}
			}
			if(game_map.getSite(l, STILL).strength > 0) {
				if(toInjure[c].count(l)) toInjure[c][l] += game_map.getSite(l, STILL).strength;
				else toInjure[c].insert(std::pair<hlt::Location, unsigned short>(l, game_map.getSite(l, STILL).strength));
				injureMap[l.y][l.x] += pieces[c][l];
			}
		}
	}

	//Injure and/or delete pieces. Note >= rather than > indicates that pieces with a strength of 0 are killed.
	for(unsigned char a = 0; a < number_of_players; a++) if(alive[a]) {
		for(auto b = toInjure[a].begin(); b != toInjure[a].end(); b++) {
			//Apply damage.
			if(b->second >= pieces[a][b->first]) pieces[a].erase(b->first);
			else pieces[a][b->first] -= b->second;
		}
	}

	//Apply damage to map pieces.
	for(int a = 0; a < game_map.map_height; a++) for(int b = 0; b < game_map.map_width; b++) {
		if(game_map.contents[a][b].strength < injureMap[a][b]) game_map.contents[a][b].strength = 0;
		else game_map.contents[a][b].strength -= injureMap[a][b];
		game_map.contents[a][b].owner = 0;
	}


	//Add pieces back into the map.
	for(unsigned char a = 0; a < number_of_players; a++) {
		for(auto b = pieces[a].begin(); b != pieces[a].end(); b++) {
			game_map.getSite(b->first, STILL).owner = a + 1;
			game_map.getSite(b->first, STILL).strength = b->second;
		}
	}

	std::vector<unsigned char> * turn = new std::vector<unsigned char>; turn->reserve(game_map.map_height * game_map.map_width * 2.25);
	for(auto a = moveDirections.begin(); a != moveDirections.end(); a++) for(auto b = a->begin(); b != a->end(); b++) {
		turn->push_back(*b);
	}
	unsigned char presentOwner = game_map.contents.begin()->begin()->owner;
	std::list<unsigned char> strengths;
	short numPieces = 0;
	for(auto a = game_map.contents.begin(); a != game_map.contents.end(); a++) for(auto b = a->begin(); b != a->end(); b++) {
		if(numPieces == 255 || b->owner != presentOwner) {
			turn->push_back(numPieces);
			turn->push_back(presentOwner);
			for(auto b = strengths.begin(); b != strengths.end(); b++) turn->push_back(*b);
			strengths.clear();
			numPieces = 0;
			presentOwner = b->owner;
		}
		numPieces++;
		strengths.push_back(b->strength);
	}

	//Final output set:
	turn->push_back(numPieces);
	turn->push_back(presentOwner);
	for(auto b = strengths.begin(); b != strengths.end(); b++) turn->push_back(*b);
	turn->shrink_to_fit();
	//Add to full game:
	full_game.push_back(turn);

	//Check if the game is over:
	std::vector<bool> stillAlive(number_of_players, false);

	for(unsigned short a = 0; a < game_map.map_height; a++) for(unsigned short b = 0; b < game_map.map_width; b++) if(game_map.contents[a][b].owner != 0) {
		full_territory_count[game_map.contents[a][b].owner - 1]++;
		full_strength_count[game_map.contents[a][b].owner - 1] += game_map.contents[a][b].strength;
		full_production_count[game_map.contents[a][b].owner - 1] += game_map.contents[a][b].strength;

		stillAlive[game_map.contents[a][b].owner - 1] = true;
	}

	//Check for bots which have timed out.
	for(unsigned char a = 0; a < permissibleTime.size(); a++) if(alive[a] && !permissibleTime[a]) {
		stillAlive[a] = false;
		timeout_tags.insert(a + 1);
	}

	return stillAlive;
}
コード例 #16
0
ファイル: mate_n_ply.cpp プロジェクト: yaneurao/YaneuraOu
// 利きのある場所への取れない近接王手からの3手詰め
Move Position::weak_mate_n_ply(int ply) const
{
	// 1手詰めであるならこれを返す
	Move m = mate1ply();
	if (m)
		return m;

	// 詰まない
	if (ply <= 1)
		return MOVE_NONE;

	Color us = side_to_move();
	Color them = ~us;
	Bitboard around8 = kingEffect(king_square(them));

	// const剥がし
	Position* This = ((Position*)this);

	StateInfo si;
	StateInfo si2;

	// 近接王手で味方の利きがあり、敵の利きのない場所を探す。
	for (auto m : MoveList<CHECKS>(*this))
	{
		// 近接王手で、この指し手による駒の移動先に敵の駒がない。
		Square to = to_sq(m);
		if ((around8 & to)

#ifndef LONG_EFFECT_LIBRARY
			// toに利きがあるかどうか。mが移動の指し手の場合、mの元の利きを取り除く必要がある。
			&& (is_drop(m) ? effected_to(us, to) : (attackers_to(us, to, pieces() ^ from_sq(m)) ^ from_sq(m)))

			// 敵玉の利きは必ずtoにあるのでそれを除いた利きがあるかどうか。
			&& (attackers_to(them,to,pieces()) ^ king_square(them))
#else
			&& (is_drop(m) ? effected_to(us, to) :
					board_effect[us].effect(to) >= 2 ||
					(long_effect.directions_of(us, from_sq(m)) & Effect8::directions_of(from_sq(m), to)) != 0)

			// 敵玉の利きがあるので2つ以上なければそれで良い。
			&& (board_effect[them].effect(to) <= 1)
#endif
			)
		{
			if (!legal(m))
				continue;

			ASSERT_LV3(gives_check(m));

			This->do_move(m,si,true);

			ASSERT_LV3(in_check());

			// この局面ですべてのevasionを試す
			for (auto m2 : MoveList<EVASIONS>(*this))
			{
				if (!legal(m2))
					continue;

				// この指し手で逆王手になるなら、不詰めとして扱う
				if (gives_check(m2))
					goto NEXT_CHECK;

				This->do_move(m2, si2, false);

				ASSERT_LV3(!in_check());

				if (!weak_mate_n_ply(ply-2))
				{
					// 詰んでないので、m2で詰みを逃れている。
					This->undo_move(m2);
					goto NEXT_CHECK;
				}

				This->undo_move(m2);
			}

			// すべて詰んだ
			This->undo_move(m);

			// mによって3手で詰む。
			return m;

		NEXT_CHECK:;
			This->undo_move(m);
		}
	}
	return MOVE_NONE;
}