text:
Q: I would like to replace a rect with an image in sdl I am trying to make the paddle an actual image instead of a rect in this breakout clone. I would also like to change the bricks into images. I just don't know how to use images like rects and am trying to figure it out.
//The headers
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <ctime>

//For cap fps
#define fps 60

//The screen attributes
const int SCREEN_WIDTH = 1008;
const int SCREEN_HEIGHT = 720;
const int SCREEN_BPP = 32;

//coordinates of ball
const int BALL_X = 500;
const int BALL_Y = 600;

//Declaring for color
Uint32 white;

//The surfaces
SDL_Surface *mainScreen = NULL;
SDL_Surface *difficultyScreen = NULL;
SDL_Surface *screen = NULL;
SDL_Surface *result = NULL;
SDL_Surface *result2 = NULL;

//The event structure
SDL_Event event;

//Rects
SDL_Rect Paddle;
SDL_Rect Ball;
SDL_Rect Block1;
SDL_Rect Block2;
SDL_Rect Block3;
SDL_Rect Block4;
SDL_Rect Block5;
SDL_Rect Block6;
SDL_Rect Block7;
SDL_Rect Block8;
SDL_Rect Block9;
SDL_Rect Block10;
SDL_Rect Block11;
SDL_Rect Block12;
SDL_Rect Block13;
SDL_Rect Block14;
SDL_Rect Block15;
SDL_Rect Block16;
SDL_Rect Block17;
SDL_Rect Block18;
SDL_Rect Block19;
SDL_Rect Block20;
SDL_Rect Block21;
SDL_Rect Block22;
SDL_Rect Block23;
SDL_Rect Block24;
SDL_Rect Block25;
SDL_Rect Block26;

int xVel, yVel;

bool PointInRect(int x, int y, SDL_Rect rec)
{
    if (x > rec.x && y > rec.y && x < rec.x + rec.w && y < rec.y + rec.h)
    {
        return true;
    }
    return false;
}

bool CheckCollision(SDL_Rect r1, SDL_Rect r2)
{
    if (PointInRect(r1.x, r1.y, r2) == true ||
        PointInRect(r1.x + r1.w, r1.y, r2) == true ||
        PointInRect(r1.x, r1.y + r1.h, r2) == true ||
        PointInRect(r1.x + r1.w, r1.y + r1.h, r2) == true)
    {
        return true;
    }
    return false;
}

/*bool ChackCollision(SDL_Rect r3, SDL_Rect r4)
{
    if (PointInRect(r3.x, r3.y, r4) == true ||
         PointInRect(r3.x + r3.w, r3.y, r4) == true)
    {
         return true;
    }
    return false;
}*/

void ResetBall()
{
    Ball.x = BALL_X;
    Ball.y = BALL_Y;
    xVel = 3;
    yVel = 3;
}

void LoadGame()
{
    Paddle.x = 425;
    Paddle.y = 650;
    Paddle.h = 20;
    Paddle.w = 150;

    Ball.x = BALL_X;
    Ball.y = BALL_Y;
    Ball.h = 15;
    Ball.w = 15;

    Block1.x = 58;
    Block1.y = 28;
    Block1.h = 15;
    Block1.w = 100;

    Block2.x = 216;
    Block2.y = 28;
    Block2.h = 15;
    Block2.w = 100;

    Block3.x = 374;
    Block3.y = 28;
    Block3.h = 15;
    Block3.w = 100;

    Block4.x = 533;
    Block4.y = 28;
    Block4.h = 15;
    Block4.w = 100;

    Block5.x = 691;
    Block5.y = 28;
    Block5.h = 15;
    Block5.w = 100;

    Block6.x = 849;
    Block6.y = 28;
    Block6.h = 15;
    Block6.w = 100;

    Block7.x = 84;
    Block7.y = 71;
    Block7.h = 15;
    Block7.w = 100;

    Block8.x = 269;
    Block8.y = 71;
    Block8.h = 15;
    Block8.w = 100;

    Block9.x = 453;
    Block9.y = 71;
    Block9.h = 15;
    Block9.w = 100;

    Block10.x = 638;
    Block10.y = 71;
    Block10.h = 15;
    Block10.w = 100;

    Block11.x = 822;
    Block11.y = 71;
    Block11.h = 15;
    Block11.w = 100;

    Block12.x = 23;
    Block12.y = 114;
    Block12.h = 15;
    Block12.w = 100;

    Block13.x = 146;
    Block13.y = 114;
    Block13.h = 15;
    Block13.w = 100;

    Block14.x = 269;
    Block14.y = 114;
    Block14.h = 15;
    Block14.w = 100;

    Block15.x = 392;
    Block15.y = 114;
    Block15.h = 15;
    Block15.w = 100;

    Block16.x = 516;
    Block16.y = 114;
    Block16.h = 15;
    Block16.w = 100;

    Block17.x = 639;
    Block17.y = 114;
    Block17.h = 15;
    Block17.w = 100;

    Block18.x = 762;
    Block18.y = 114;
    Block18.h = 15;
    Block18.w = 100;

    Block19.x = 885;
    Block19.y = 114;
    Block19.h = 15;
    Block19.w = 100;

    Block20.x = 88;
    Block20.y = 157;
    Block20.h = 15;
    Block20.w = 100;

    Block21.x = 820;
    Block21.y = 157;
    Block21.h = 15;
    Block21.w = 100;

    Block22.x = 138;
    Block22.y = 200;
    Block22.h = 15;
    Block22.w = 100;

    Block23.x = 296;
    Block23.y = 200;
    Block23.h = 15;
    Block23.w = 100;

    Block24.x = 454;
    Block24.y = 200;
    Block24.h = 15;
    Block24.w = 100;

    Block25.x = 612;
    Block25.y = 200;
    Block25.h = 15;
    Block25.w = 100;

    Block26.x = 770;
    Block26.y = 200;
    Block26.h = 15;
    Block26.w = 100;

    white = SDL_MapRGB(screen->format, 255, 255, 255);

    srand(time(NULL));

    ResetBall();
}
void Logic()
{
    SDL_Event occur;
    SDL_PollEvent(&occur);
    Uint8 *keystates = SDL_GetKeyState(NULL);
    if (keystates[SDLK_LEFT])
    {
        Paddle.x -= 8;
    }
    if (keystates[SDLK_RIGHT])
    {
        Paddle.x += 8;
    }
    if (Paddle.x < 1)
    {
        Paddle.x = 1;
    }
    if (Paddle.x + Paddle.w > 1007)
    {
        Paddle.x = 1007 - Paddle.w;
    }

    //For ball movement
    Ball.x += xVel;
    Ball.y += yVel;

    //Change the direction of the ball if ball hits the walls
    if (Ball.y < 1)
    {
        yVel = -yVel;
    }
    if (Ball.x < 1)
    {
        xVel = -xVel;
    }
    if (Ball.x + Ball.w > 1007)
    {
        xVel = -xVel;
    }

    //Change the direction of the ball if ball hits the paddle
    if (CheckCollision(Ball, Paddle) == true)
    {
        yVel = -yVel;
    }

    //Change the direction of the ball if ball hits the blocks
    if (CheckCollision(Ball, Block1) == true)
    {
        yVel = -yVel;
        Block1.x = -200;
        Block1.y = -200;
    }
    if (CheckCollision(Ball, Block2) == true)
    {
        yVel = -yVel;
        Block2.x = -200;
        Block2.y = -200;
    }
    if (CheckCollision(Ball, Block3) == true)
    {
        yVel = -yVel;
        Block3.x = -200;
        Block3.y = -200;
    }
    if (CheckCollision(Ball, Block4) == true)
    {
        yVel = -yVel;
        Block4.x = -200;
        Block4.y = -200;
    }
    if (CheckCollision(Ball, Block5) == true)
    {
        yVel = -yVel;
        Block5.x = -200;
        Block5.y = -200;
    }
    if (CheckCollision(Ball, Block6) == true)
    {
        yVel = -yVel;
        Block6.x = -200;
        Block6.y = -200;
    }
    if (CheckCollision(Ball, Block7) == true)
    {
        yVel = -yVel;
        Block7.x = -200;
        Block7.y = -200;
    }
    if (CheckCollision(Ball, Block8) == true)
    {
        yVel = -yVel;
        Block8.x = -200;
        Block8.y = -200;
    }
    if (CheckCollision(Ball, Block9) == true)
    {
        yVel = -yVel;
        Block9.x = -200;
        Block9.y = -200;
    }
    if (CheckCollision(Ball, Block10) == true)
    {
        yVel = -yVel;
        Block10.x = -200;
        Block10.y = -200;
    }
    if (CheckCollision(Ball, Block11) == true)
    {
        yVel = -yVel;
        Block11.x = -200;
        Block11.y = -200;
    }
    if (CheckCollision(Ball, Block12) == true)
    {
        yVel = -yVel;
        Block12.x = -200;
        Block12.y = -200;
    }
    if (CheckCollision(Ball, Block13) == true)
    {
        yVel = -yVel;
        Block13.x = -200;
        Block13.y = -200;
    }
    if (CheckCollision(Ball, Block14) == true)
    {
        yVel = -yVel;
        Block14.x = -200;
        Block14.y = -200;
    }
    if (CheckCollision(Ball, Block15) == true)
    {
        yVel = -yVel;
        Block15.x = -200;
        Block15.y = -200;
    }
    if (CheckCollision(Ball, Block16) == true)
    {
        yVel = -yVel;
        Block16.x = -200;
        Block16.y = -200;
    }
    if (CheckCollision(Ball, Block17) == true)
    {
        yVel = -yVel;
        Block17.x = -200;
        Block17.y = -200;
    }
    if (CheckCollision(Ball, Block18) == true)
    {
        yVel = -yVel;
        Block18.x = -200;
        Block18.y = -200;
    }
    if (CheckCollision(Ball, Block19) == true)
    {
        yVel = -yVel;
        Block19.x = -200;
        Block19.y = -200;
    }
    if (CheckCollision(Ball, Block20) == true)
    {
        yVel = -yVel;
        Block20.x = -200;
        Block20.y = -200;
    }
    if (CheckCollision(Ball, Block21) == true)
    {
        yVel = -yVel;
        Block21.x = -200;
        Block21.y = -200;
    }
    if (CheckCollision(Ball, Block22) == true)
    {
        yVel = -yVel;
        Block22.x = -200;
        Block22.y = -200;
    }
    if (CheckCollision(Ball, Block23) == true)
    {
        yVel = -yVel;
        Block23.x = -200;
        Block23.y = -200;
    }
    if (CheckCollision(Ball, Block24) == true)
    {
        yVel = -yVel;
        Block24.x = -200;
        Block24.y = -200;
    }
    if (CheckCollision(Ball, Block25) == true)
    {
        yVel = -yVel;
        Block25.x = -200;
        Block25.y = -200;
    }
    if (CheckCollision(Ball, Block26) == true)
    {
        yVel = -yVel;
        Block26.x = -200;
        Block26.y = -200;
    }

//Function to load image
SDL_Surface *load_Image( std::string filename )
{
    //Temporary storage for the image that's loaded
    SDL_Surface* loadedImage = NULL;

    //The optimized image that will be used
    SDL_Surface* optimizedImage = NULL;
    loadedImage = SDL_LoadBMP(filename.c_str());

    //If nothing went wrong in loading the image
    if(loadedImage != NULL)
    {
        //Create an optimized image
        optimizedImage = SDL_DisplayFormat(loadedImage);

        //Free the old surface
        SDL_FreeSurface(loadedImage);
    }
    //Return the optimized image
    return optimizedImage;
}
//Function to apply picture to screen
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;

    //Blit
    SDL_BlitSurface(source, clip, destination, &offset);
}
//Function to start SDL
bool init()
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return false;
    }
    //set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
        return false;
    }

    //Name the window
    SDL_WM_SetCaption( "Block Breaker", NULL );

    //If everything initialized fine
    return true;
}
//Function to load files
bool load_files()
{
    //Load the image
    mainScreen = load_Image( "Menu.bmp" );
    difficultyScreen = load_Image( "Speed Menu.bmp" );
    result = load_Image( "Results.bmp" );
    result2 = load_Image( "Results2.bmp" );

    return true;
}
//function to stop SDL
void clean_up()
{
    SDL_FreeSurface(mainScreen);
    SDL_FreeSurface(difficultyScreen);
    SDL_FreeSurface(screen);
    SDL_FreeSurface(result);
    SDL_FreeSurface(result2);

    //Quit SDL
    SDL_Quit();
}
int main( int argc, char* args[] )
{

    //Variables
    bool running = true;
    bool menu = true;
    bool difficulty = false;
    bool mediumGame = false;
    bool grayGameScreen = false;
    bool hardGame = false;
    bool quit = false;
    bool Result = false;
    bool Result2 = false;

    //Initialize
    if ( init() == false )
    {
        return 1;
    }

    //Quit function
    if (quit == true)
    {
        SDL_Quit();
    }

    //Load the files
    if ( load_files() == false )
    {
        return 1;
    }

    //Load Game
    LoadGame();

    Uint32 starting_tick;
    //while the user hasn't quit
    while (quit == false)
    {
        starting_tick = SDL_GetTicks();
        //Menu screen
        if (menu==true)
        {
            //Apply screen
            apply_surface(0,0,mainScreen,screen);

            //Loop to handle input by user
            while(SDL_PollEvent(&event))
            {
                if (event.type==SDL_MOUSEBUTTONUP)
                {
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {
                        int x = event.button.x;
                        int y = event.button.y;
                        //Button for difficulty screen
                        if ((x>370)&&(x<660)&&(y>265)&&(y<370))
                        {
                            menu = false;
                            difficulty = true;
                            SDL_Flip(screen);
                        }
                        if ((x>374)&&(x<660)&&(y>390)&&(y<500))
                        {
                            menu = false;
                            quit = true;
                            SDL_Flip(screen);
                        }
                    }
                SDL_Flip(screen);
                }
                else if (event.type==SDL_QUIT)
                {
                    quit = true;
                }
            }
            SDL_Flip(screen);
        }

        //Difficulty screen
        else if (difficulty==true)
        {
            //Apply surface
            apply_surface(0,0,difficultyScreen,screen);
            SDL_Flip(screen);

            while (SDL_PollEvent(&event))
            {
                if (event.type==SDL_MOUSEBUTTONUP)
                {
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {
                        int x = event.button.x;
                        int y = event.button.y;
                        //Button for medium game screen
                        if ((x>360)&&(x<660)&&(y>370)&&(y<465))
                        {
                            difficulty = false;
                            mediumGame = true;
                            SDL_Flip(screen);
                        }
                        //Button for hard game screen
                        if ((x>420)&&(x<610)&&(y>490)&&(y<575))
                        {
                            difficulty = false;
                            hardGame = true;
                            SDL_Flip(screen);
                        }
                    }
                SDL_Flip(screen);
                }
                else if (event.type==SDL_QUIT)
                {
                    quit = true;
                }
            }
        }

        //Medium game screen
        else if (mediumGame == true)
        {
            //Fill color
            SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x68, 0x68, 0x68 ));

            //Logic for the game
            Logic();

            //Place Paddle
            SDL_FillRect(screen, &Paddle, white);

            //Place Ball
            SDL_FillRect(screen, &Ball, white);

            //Place Blocks
            SDL_FillRect(screen, &Block1, white);
            SDL_FillRect(screen, &Block2, white);
            SDL_FillRect(screen, &Block3, white);
            SDL_FillRect(screen, &Block4, white);
            SDL_FillRect(screen, &Block5, white);
            SDL_FillRect(screen, &Block6, white);
            SDL_FillRect(screen, &Block7, white);
            SDL_FillRect(screen, &Block8, white);
            SDL_FillRect(screen, &Block9, white);
            SDL_FillRect(screen, &Block10, white);
            SDL_FillRect(screen, &Block11, white);
            SDL_FillRect(screen, &Block12, white);
            SDL_FillRect(screen, &Block13, white);
            SDL_FillRect(screen, &Block14, white);
            SDL_FillRect(screen, &Block15, white);
            SDL_FillRect(screen, &Block16, white);
            SDL_FillRect(screen, &Block17, white);
            SDL_FillRect(screen, &Block18, white);
            SDL_FillRect(screen, &Block19, white);
            SDL_FillRect(screen, &Block20, white);
            SDL_FillRect(screen, &Block21, white);
            SDL_FillRect(screen, &Block22, white);
            SDL_FillRect(screen, &Block23, white);
            SDL_FillRect(screen, &Block24, white);
            SDL_FillRect(screen, &Block25, white);
            SDL_FillRect(screen, &Block26, white);

            //Loser
            if (Ball.y + Ball.h > 719)
            {
                mediumGame = false;
                Result2 = true;
                SDL_Flip(screen);
            }

            //Winner
            if (Block1.x != 58 &&
                Block2.x != 216 &&
                Block3.x != 374 &&
                Block4.x != 533 &&
                Block5.x != 691 &&
                Block6.x != 849 &&
                Block7.x != 84 &&
                Block8.x != 269 &&
                Block9.x != 453 &&
                Block10.x != 638 &&
                Block11.x != 822 &&
                Block12.x != 23 &&
                Block13.x != 146 &&
                Block14.x != 269 &&
                Block15.x != 392 &&
                Block16.x != 516 &&
                Block17.x != 639 &&
                Block18.x != 762 &&
                Block19.x != 885 &&
                Block20.x != 88 &&
                Block21.x != 820 &&
                Block22.x != 138 &&
                Block23.x != 296 &&
                Block24.x != 454 &&
                Block25.x != 612 &&
                Block26.x != 770)
            {
                hardGame = false;
                Result = true;
                SDL_Flip(screen);
            }

            //Flip screen
            SDL_Flip(screen);
        }

        //Hard game screen
        else if (hardGame == true)
        {
            //Fill color
            SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x68, 0x68, 0x68 ));

            //Logic for the game
            Logic();

            //Place Paddle
            SDL_FillRect(screen, &Paddle, white);

            //Place Ball
            SDL_FillRect(screen, &Ball, white);

            //Place Blocks
            SDL_FillRect(screen, &Block1, white);
            SDL_FillRect(screen, &Block2, white);
            SDL_FillRect(screen, &Block3, white);
            SDL_FillRect(screen, &Block4, white);
            SDL_FillRect(screen, &Block5, white);
            SDL_FillRect(screen, &Block6, white);
            SDL_FillRect(screen, &Block7, white);
            SDL_FillRect(screen, &Block8, white);
            SDL_FillRect(screen, &Block9, white);
            SDL_FillRect(screen, &Block10, white);
            SDL_FillRect(screen, &Block11, white);
            SDL_FillRect(screen, &Block12, white);
            SDL_FillRect(screen, &Block13, white);
            SDL_FillRect(screen, &Block14, white);
            SDL_FillRect(screen, &Block15, white);
            SDL_FillRect(screen, &Block16, white);
            SDL_FillRect(screen, &Block17, white);
            SDL_FillRect(screen, &Block18, white);
            SDL_FillRect(screen, &Block19, white);
            SDL_FillRect(screen, &Block20, white);
            SDL_FillRect(screen, &Block21, white);
            SDL_FillRect(screen, &Block22, white);
            SDL_FillRect(screen, &Block23, white);
            SDL_FillRect(screen, &Block24, white);
            SDL_FillRect(screen, &Block25, white);
            SDL_FillRect(screen, &Block26, white);

            //Loser
            if (Ball.y + Ball.h > 720)
            {
                hardGame = false;
                Result2 = true;
                SDL_Flip(screen);
            }

            //Winner
            if (Block1.x != 58 &&
                Block2.x != 216 &&
                Block3.x != 374 &&
                Block4.x != 533 &&
                Block5.x != 691 &&
                Block6.x != 849 &&
                Block7.x != 84 &&
                Block8.x != 269 &&
                Block9.x != 453 &&
                Block10.x != 638 &&
                Block11.x != 822 &&
                Block12.x != 23 &&
                Block13.x != 146 &&
                Block14.x != 269 &&
                Block15.x != 392 &&
                Block16.x != 516 &&
                Block17.x != 639 &&
                Block18.x != 762 &&
                Block19.x != 885 &&
                Block20.x != 88 &&
                Block21.x != 820 &&
                Block22.x != 138 &&
                Block23.x != 296 &&
                Block24.x != 454 &&
                Block25.x != 612 &&
                Block26.x != 770)
            {
                hardGame = false;
                Result = true;
                SDL_Flip(screen);
            }

            //Flip screen
            SDL_Flip(screen);
        }

        //Win menu
        else if (Result == true)
        {
            apply_surface(0,0,result,screen);
            LoadGame();
            SDL_Flip(screen);

            while (SDL_PollEvent(&event))
            {
                if (event.type==SDL_MOUSEBUTTONUP)
                {
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {
                        int x = event.button.x;
                        int y = event.button.y;

                        //Button for medium game screen
                        if ((x>360)&&(x<660)&&(y>370)&&(y<465))
                        {
                            Result = false;
                            difficulty = true;
                            SDL_Flip(screen);
                        }

                        //Button for hard game screen
                        if ((x>420)&&(x<610)&&(y>490)&&(y<575))
                        {
                            Result = false;
                            quit = true;
                            SDL_Flip(screen);
                        }
                    }
                    SDL_Flip(screen);
                }
                else if (event.type==SDL_QUIT)
                {
                    quit = true;
                }
            }
        }

        //Lose menu
        else if (Result2 == true)
        {
            apply_surface(0,0,result2,screen);
            LoadGame();
            SDL_Flip(screen);

            while (SDL_PollEvent(&event))
            {
                if (event.type==SDL_MOUSEBUTTONUP)
                {
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {
                        int x = event.button.x;
                        int y = event.button.y;

                        //Button for medium game screen
                        if ((x>360)&&(x<660)&&(y>370)&&(y<465))
                        {
                            Result = false;
                            difficulty = true;
                            SDL_Flip(screen);
                        }

                        //Button for hard game screen
                        if ((x>420)&&(x<610)&&(y>490)&&(y<575))
                        {
                            Result = false;
                            quit = true;
                            SDL_Flip(screen);
                        }
                    }
                    SDL_Flip(screen);
                }
                else if (event.type==SDL_QUIT)
                {
                    quit = true;
                }
            }
        }

        //Cap fps
        if (( 1000/fps) > SDL_GetTicks() - starting_tick)
        {
            SDL_Delay( 1000/fps - ( SDL_GetTicks() - starting_tick ));
        }
    }

    //Clean up
    clean_up();
    return 0;
}

A: Here's some sample code for displaying an image:
Loading the image:
SDL_Rect image_hitbox;
SDL_Texture* image = IMG_LoadTexture(renderer, filelocation.c_str());

Now, if you want the image to be displayed at a certain size, without consideration of the size of the image itself, just set it like normal:
image_hitbox.x = locationX;
image_hitbox.y = locationY;
image_hitbox.w = width;
image_hitbox.h = height;

If you would like width and height to depend on the picture itself, you can do this:
SDL_QueryTexture(image, nullptr, nullptr, &image_hitbox.w, &image_hitbox.h);

which will get the textures width and height for you.
Then, to simply render the image, you do this:
SDL_RenderCopy(renderer, image, nullptr, &image_hitbox);
SDL_RenderPresent(renderer);

which will render the image (and scale it to the set width and height) at the coordinates in image_hitbox.
I'm not 100% sure this is exactly what you asked for, especially since you seem to be rendering surfaces instead of textures, but I can recommend using textures instead, as they use your GPU instead of your CPU.


text:
Q: Cannot access properties after JSON deserialization into dynamic I'm having some issues accessing dynamic properties after JSON deserialization. Here is the JSON:
{
  "user" : {
       "511221" :{
        "timestamp" : 1403365646384,
        "version" : -81317051,
        "email" : "user@name.com",
        "name" : "My Name",
        "structures" : [ "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r" ]
       }
   },
}

There's actually two problems here. First is that "511221" changes for each user. This is given when authenticating. I can't create a user class and then create another class which name keeps changing.
Also, it's a number. AFAIK, there is no way to have a class name as a number. What are my options here? I cannot control what gets returned by the API.
So instead of deserialization into a predefined class, I have a dynamic, like this:
dynamic jsonObject = JsonConvert.DeserializeObject(response);

I want to be able to do this:
string[] structures = jsonObject.user.(authInfo.userid).structures;

In words, I want (authInfo.userid) to input the user id as a string above, however this does not seem possible. I have also tried reflection:
private static object ReflectOnPath(object o, string path)
{
    object value = o;
    string[] pathComponents = path.Split('.');
    foreach (var component in pathComponents)
    {
        Type type = value.GetType();
        System.Reflection.PropertyInfo pi = type.GetProperty(component);

        //pi is null here, I have no idea why

        value = pi.GetValue(value);
    }
    return value;
}

So it could be called like this to do the same as shown above:
string[] structures = ReflectOnPath(jsonObject, "user." + authInfo.userid + ".structures") as string[];

However, when this is called, GetProperty() on type (JObject) is null. I know the property "user" exists, but why can't I access it?

A: You can deserialize your JSON to JObject instead of dynamic, then you can access the property by property name dynamically, for example :
JObject jObject = JsonConvert.DeserializeObject<JObject>(response);
var user = "511221";
var structures = jObject["user"][user]["structures"][0];

//given JSON input as in this question,
//following line will print "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r"
Console.WriteLine(structures);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ratio and percentage related The ration of boys to girls in a school is 7:6. If the number of boys and girls in the school increases by 10% and 15% respectively in one year, the number of boys will exceed the number of girls by 120. What is the total number of students in the school?

A: Hint: Suppose total number of girls
 after increment is $x$ and total number of boys after increment is $y$ then,
$$x+120=y$$

A: Let us note $b$ the current number of boys and $g$ the current number of girls. What we know is that today $$\frac bg=\frac 76$$ that is to say $$6b=7g$$ Within a year, there will be $1.10 b$ boys and $1.15 g$ girls and you are told that the situation will be such that $$1.10b-1.15g=120$$ So, two equations for two unknowns $b$ and $g$.
I am sure that you can take from here.


text:
Q: Why will thread run faster with thread.Join in Visual Basic .Net I have two windows form to test the performance of using threat
I do a looping of 500
For i As Integer = 1 To 500
    'Form 1 scenario
    Dim Thread1 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread1.Start(RunningID)
    Dim Thread2 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread2.Start(RunningID)
    Dim Thread3 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread3.Start(RunningID)
    Dim Thread4 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread4.Start(RunningID)
Next

Form 2 scenario
For i As Integer = 1 To 500
    'Form 2 scenario
    Dim Thread1 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread1.Start(RunningID)
    Dim Thread2 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread2.Start(RunningID)
    Dim Thread3 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread3.Start(RunningID)
    Dim Thread4 As New System.Threading.Thread(AddressOf InsertRecord1)
    Thread4.Start(RunningID)
    Thread1.Join()
    Thread2.Join()
    Thread3.Join()
    Thread4.Join()
Next

Apparently Scenario 2 is faster than scenario 1. why??
this is the data collected
Scenario 1 take (milliseconds): 2578   3188   3078   2984   3250
Scenario 2 take (milliseconds): 1890   1969   1828   1938   1860

A: I think this just shows that your Inserts do not scale well. Your first scanario launches 2000 threads and waits for them to finish - the second scenario launches 4 threads and waits for them to finish, 500 times.
Using Threads adds an overhead to the execution that itself can slow down your code, if all threads end up into the same database that cannot handle that many connections your execution times get worse. Maybe you could test your Example without multiple threads, put the calls directly into the loop and look at the numbers, possibly this runs even faster.


text:
Q: How to send props to a component while using Route to load? 1) If I am importing a component, I can send props to component like this,
<ImportedComponent props={props} />

Is there any way to send props to a component, If I am using Route?
<Route path={"...somePath"} component= {someComponent} />

2) Also, If I am in the required path already, Is there any difference in using
<Route />

to load a component and directly referring imported component this way,
<ImportedComponent />

A: You can use render
<Route
    path={"...somePath"}
    render={(props) => (<someComponent {...props} otherProps={otherProps} />)}
/>


text:
Q: How to convert numbers to words in odoo? In the invoice, I want to convert total amount to words in Indian numbering system(hundreds, thousands, lakhs, crores). I cant use amount_to_text library module since it has been set in euro currency. So how to write function in python to achieve this? (dont worry abt indendation,its correct in my system) When i tried this code in my custom module, i get this error
TypeError: _int2word() takes exactly 1 argument (7 given)
class account_invoice(models.Model):
_inherit = "account.invoice"
print "hello"

ones = ["", "one ","two ","three ","four ", "five ", "six ","seven ","eight ","nine "]
tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ","fifteen ","sixteen ","seventeen ","eighteen ","nineteen "]
twenties = ["","","twenty ","thirty ","forty ","fifty ","sixty ","seventy ","eighty ","ninety "]
thousands = ["","thousand ","lakh ", "crore "]

def _int2word(amount_total):

    n = amount_total
    n3 = []
    r1 = ""
    ns = str(n)
    for k in range(3, 33, 3):
        r = ns[-k:]
        q = len(ns) - k

        if q < -2:
            break
        else:
            if  q >= 0:
                n3.append(int(r[:3]))
            elif q >= -1:
                n3.append(int(r[:2]))
            elif q >= -2:
                n3.append(int(r[:1]))
        r1 = r

    nw = ""
    for i, x in enumerate(n3):
        b1 = x % 10
        b2 = (x % 100)//10
        b3 = (x % 1000)//100
        #print b1, b2, b3  # test
        if x == 0:
            continue  # skip
        else:
            t = thousands[i]
        if b2 == 0:
            nw = ones[b1] + t + nw
        elif b2 == 1:
            nw = tens[b1] + t + nw
        elif b2 > 1:
            nw = twenties[b2] + ones[b1] + t + nw
        if b3 > 0:
            nw = ones[b3] + "hundred " + nw
    return nw

_columns = {
    'amount_words': fields.function(_int2word, string='In Words', type="char"),
}

A: You could use amount_to_text_en function from openerp.tools this function takes 3 parameters the_value , the_partner.lang and the currency_name then it will be not just Euro it will return any currency you pass to it.


text:
Q: How to determine the limit of a sequence in a metric space If I'm trying to prove that a Metric space $(M,d)$ is not complete I have to find a Cauchy a sequence that doesn't converge in $M$.
Using the following Metric Space as an example:

$M = \{  x \in \mathbb{R}^2 : ||x||<1 \}$
$d(x,y) = 2-||x||-||y||$ if $x \neq y$, and $0$ otherwise

I know that the point $(1,1)$ lies outside this space, as $||(1,1)|| = \sqrt{2}  >1 $
So now I want to see if a sequence exists with this limit point.
I figured, in the usual metric the sequence $(\frac{\sqrt{2}}{2}-\frac{1}{n},\frac{\sqrt{2}}{2}-\frac{1}{n}$ would converge to $(\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2})$
How would I check to see if the limit point is the same given the above metric $d$?
Or even better, how would I determine exactly what the limit of this sequence is given the above metric $d$.

A: Take for example the sequence $x_n = \left (1-\frac{1}{n},0\right )$
this sequence clearly belongs to $M$
Now in order to prove that the sequence is a Cauchy sequence we regard the distance between two terms of the sequence and show that the distance tends to $0$ as $n,m \to \infty$
$$d(x_n,x_m) = 2 - ||x_n|| - ||x_m|| = 2 - \left(1-\frac{1}{n}\right) - \left(1-\frac{1}{m}\right)  = \frac{1}{n} + \frac{1}{m}  \longrightarrow 0 $$
After that, we should prove that the sequence not converges to any point, or more general, prove that there are not convergent sequences (showing  that the space is not complete) , this can be easily done just taking an arbitrary point $x$ and an arbitrary sequence $(x_n)$ and showing that $(x_n)$ can not converge to $x$ (take a look at the distance between $x$ and a general point of the sequence)


text:
Q: Raster copy multiple rasters keeping name but dropping extension I have ~100 rasters I need to clip to an area. All rasters are saved as .bil files, and for use in later processing I was trying to make these have 'no extension for esri grid', but keep the same name.
i.e. depth.bil becomes depth, hazard.bil becomes hazard etc. (There are multiple named files in each folder and in this model build example I am calling via %name% on iteration)
I tried to change this in 'calculate value' to take off the extension of the file:
expression = changeName("%Name%")
code block =  def changeName(name): return str(name[:-4])

This worked once, but when I changed folder it put it out of sync so it was naming files incorrectly to the raster it was clipping.
If I don't remove this it says as a .bil file given it needs no extension in the clip tool.
I can do some python but from what I know I would still be in the same predicament as this in ModelBuilder.

A: AFAIK just removing an extension doesn't make a file a GRID format, what you need is the function Raster To Other Format (multiple)
.
You can use it in model builder. The tool takes all your images in a folder and save them under the same name but with your chosen data format in a folder you specify.


text:
Q: Deploy CNN keras model on Arduino I wrote the below **CNN **Keras model on Google Colaboratory to Classify a set of one dimensional signals to 10 classes and its works well, however when I deploy it on Arduino, it doesn't predict any classes;
model = Sequential()
model.add(tf.keras.layers.Reshape((500, 1), input_shape=(500,),name='reshape'))
model.add(tf.keras.layers.Conv1D(filters=10,kernel_size=5,activation=tf.nn.relu, padding='same'))
model.add(tf.keras.layers.Flatten())
model.add(Dense(10, activation='softmax', name='output'))
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

I wrote another dense model using Keras; That works well on Arduino nano BLE 33 sense, however the above CNN model gets zero as probability of all 10 classes.
Anyone can help me how to deploy a one dimensional CNN?


text:
Q: Change a function's properties each time it's executed in Javascript I'm willing to create a function that changes payhighx() into paylowx() and paylowx() into payhighx() each time one of the two is executed. I thought of an if statement going into the roll() function that'd check whether payhighx()/paylowx() was executed and change their properties if the returned value is True. I tried researching something related to my problem, but couldn't find anything useful in terms of JQuery and Javascript.
var start = 0.01

var $input = $("#oddsInput")
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")
var $pay = $("#oddsPayout.btn.btn-primary.btn-xlg.btn-block")

function paylowx() {
    $pay.click()
    document.getElementById("oddsInput").value = "1.2";
    $odds.click()
}

function payhighx() {
    $pay.click()
    document.getElementById("oddsInput").value = "5.2";
    $odds.click()
}

function roll() {
    $bet.val(start)
    $button.click()
    setTimeout(function() {
        var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
        var cls = tr.getAttribute('class')
        if (cls === 'success'){

        }
        else{
            payhighx()
        }
            $button.click();
        setTimeout(function()
        {
            $button.click();
            },1000);
            },1000);
}

setInterval(roll, 2000)


text:
Q: Scala StringView-like class I want to see a class that represents a part of the existing string. Something that I can use in the following manner:
val theBigString: String = ???;
val pattern: Regex = ???;

val mySubstring = SmthLikeStringView(theBigString, /*start*/ 1000, /*end*/ 1500);
if (pattern.matches(mySubstring)) {???;} else {???;}

Of course I know about the following stuff, but it seems not to fit:

*

*val mySubstring = theBigString.substring(/*start*/ 1000, /*end*/ 1500). The resulting object has nice interface, which I like. But AFAIK, the operation implies literally copying character, which I want to avoid, I'd like to create a "lightweight" object.

*val mySubstring = scala.collection.StringView(theBigString).slice(/*start*/ 1000, /*end*/ 1500). This is really a View (hopefully, lightweight enough), but it has inappropriate interface. Not only it has unexpected method names (e.g. slice instead of substring), but it also doesn't implement CharSequence, so I can't operate on it via Regex and other standard ways.

Is there something that (on the one hand) is lightweight, view-like and (on the other hand) can be used together with Regex?
(AFAIK, no. But then the questions are: (1) WHY??? (2) Are there any bug reports / feature requests for that?)


text:
Q: Consequences of setting `LC_ALL=C.UTF-8` and `LANG=C.UTF-8` In order to fix the bug with packing a Python application as a snap I am ready to add this code:
# I don't know what I am doing
export LC_ALL=C.UTF-8
export LANG=C.UTF-8

There is a lot of text that seems to explain what a LC_ALL=C does (but not LC_ALL=C.UTF-8 or LANG=C.UTF-8) and a big text that explains the bug and the Python behavior. But none of them fits my small head. Usually I enjoy wrapping my head around the gory technical details, but lately a time pressure makes me rather ignorant.
I just want to know what is the meaning of the phrase This system supports the C.UTF-8 locale and what will happen if I set those variables to switch to it? (which I guess is made by setting those environment variables)

A: The "C" locale turns off all internationalization, status/error messages are in English, there is no distinction between characters and bytes, sorting is by raw byte values. The meaning of bytes outside the ASCII range is not defined.
This works mostly ok for a program that works entirely with bytes, it can read those bytes, process them and output them again without caring about what exactly byte values in the range 0x80-0xFF mean.
However it causes big problems for python3's "convert everything to unicode" approach. If you don't know what byte values in the range 0x80-0xFF mean then you can't correctly convert them to Unicode. Python3 decides to raise an error in this case rather than making a potentially-incorrect assumption.
Using language locales in widely distributed scripts is problematic too though. The first problem is you can't be sure the locale for any particular language will be present on every system where you script will run. Secondly language-specific locales may have other settings which the scripter finds undesirable.
C.UTF-8 keeps most of the characteristics of the C locale, but specifies a UTF-8 encoding.


text:
Q: How to add new component parameters in Joomla on the fly? usually its done by setting up the config.xml but what to do when my component needs more parameters at run-time ? There is little or zero information about, just 1-2 tutorials about custom parameters which could be used to archive the same thing but only if you're willing to write lots of bloat code for a very simple thing.
In my case my component is rather a little platform in it self, ie: users can add plugins from us. Of course I'd like to expose some options for such plugins in the component's options.
Is there any shortcut because if you look at the built-in component's code, you really don't want to do the same for each plugin...
well, thanks! any thoughts are welcome!
ps: may be there is something more compact like the Redux-Framework for Wordpress. I'd love to know there is library which can server both CMS systems.
update
'component' = Joomla component and by 'plugin' I mean my and non-Joomla plugin, hosted in a Joomla component. Imagine your Joomla component is just a host for external plugins.

A: You need to create a custom field type, where you'll be able to implement all the logic that's needed.
In case you need to store the values with the component, add a hidden input field, and use javascript to populate the markup on load, and insert the values you want to store on user interaction (you can also store an object encoded in json).  Joomla will take care of saving and retrieving it.
the docs


text:
Q: How to read lambdas in android / R8 stack trace de-obfuscated with retrace.jar? Specifically, lines similar to:

<my-package>.-$$Lambda$<my-class>$TBpBoCodhQrLRrW-jmx762QZ0VY.run(Unknown Source:2)

<my-package> and <my-class> were obviously replaced.
Perhaps there are some options to R8 to preserve pertinent information?

A: The classes with names starting with -$$Lambda$ are generated by R8 (and D8) when desugaring Java lambdas. These are synthetic classes, and they have no corresponding item in the input program. Normally a -$$Lambda$ will not be on the top of stack, as they will always call the lambda$xxx method generated by javac which has references back to the original source.
If you are using retrace.jar from ProGuard, please make sure to use a recent version which supports inline frames in the mapping file. Version 6+ should work.


text:
Q: No Logical Name for Wireless Adapter Ubuntu Server 12.04 I just installed Ubuntu Server 12.04 after formatting my Windows hard drive, because I no longer need the desktop so I will be using it a server.
I cannot connect to the internet via Wireless router, and while following some instructions on a forum, I noticed that when using the command:
    lshw -C network

My wireless adapter is seen, but does not have a logical name. Is there a way to give my wireless adapter a logical name, or a different way to solve the problem? I am not able to run an ethernet wire from my router to my room at the moment so I have to find out a way to connect to the internet with the wireless adapter.

A: Just found the solution on the Ubuntu Forums:
Had to run the following command:
sudo apt-get install firmware-b43-installer


text:
Q: If $n$ is odd and $a_{ij} = -a_{ji}$ for all $i,j\in\{1,...,n\}$, then $A$ is not invertible. Does the statement hold also when $n$ is even? I have no clue how to do that task. We currently are doing Eigenvalue, Eigenvector and diagonaziable matrices. Do you guys have any ideas how to do this task? I am very sorry for the formating, I cannot get the hang of it.
Translation of the question:
$K$ is a field, $n$ a natural number and $A = (a_{ij}), i,j = 1,...,n \in Mat(n \times n, K)$. Prove this statement: If $n$ is odd and $a_{ij} = -a_{ji}$ for all $i,j \in \{1,...,n\}$, then $A$ is not invertible. Does the statement also apply to the case when $n$ is even?

Thanks in Advance!

A: As Jyrki Lahtonen has noted, the simplest counterexample to an even-$n$ attempt to generalize the theorem is $\left(\begin{array}{cc}
0 & -1\\
1 & 0
\end{array}\right)$. The reason the theorem only works for odd $n$ is because $A^T=-A$ implies $\det A=\det A^T=(-1)^n \det A$, which implies $\det A=0$ provided $(-1)^n=-1$.

A: Consider  $$ \begin{pmatrix}0&4\\-4&0\end{pmatrix}$$ which is invertible.


text:
Q: Docker file fails to build I am a software developer by trade. I know little about linux and general networking but I do use docker a lot.
About a month ago I dual booted. I now have Manjaro Linux and Windows 10.
I am working on a pet-project. I have the following Dockerfile. On my Manjaro Linux when I run docker build . --no-cache the dockerfile fails to build. The error I get is this:

When I run the same command on Windows, the dockerfile builds without any problems. Also, someone else running Manjaro linux ran the same command, and for them it built fine too, even on Linux.
This means the issue it local to my machine, something is not right in my Manjaro install. The install is fresh about a month old so I'm not sure what can be wrong.
I ran sudo iptables -nL to see what I have, here is the output:

I read the official docker documentation on iptables, and it tells users not to mess with the docker chains.
I'm now stuck and I'm not sure why my dockerfile is failing.

A: This error is covered in their forums here: https://discourse.elm-lang.org/t/cannot-install-any-elm-packages/3084
Copying answers for archival:
1:

At the end of the error message it says the URL doesn't exist. So this looks like a networking issue. Maybe test if you can reach the same URL from the same box using curl or wget or a browser. Maybe it's behind a firewall or you need to set HTTPS_PROXY in the environment?

2:

https://package.elm-lang.org is not set up for ipv6 (I just tested). So you need to change the protocol to v4.

3:

*

*ping package.elm-lang.org

*Adds the ip into /etc/hosts

The first thing I recommend trying is disabling IPv6 in Manjaro (if you have it enabled).


text:
Q: Tools to operate a mobile using a desktop PC I have used software named my mobiler which displays the screen of any Windows Mobile connected to a desktop PC and allows the user to control the mobile from the desktop.
Are there other similar software available in the market for S60 or Series 40 Nokia mobiles.

A: My Mobiler is very cool - like Remote Desktop but for a phone.
The Nokia PC Connectivity API doesn't quite do the same thing, as it provides a set of APIs to let you control the phone and get data from it. Neither do the Series 40 or Series 60 emulators, as the phone is emulated rather than real.
Given the significant technology differences between S60, S40 and Windows, I'd be surprised to see this change any time soon.
Now, Maemo (as running on the N900) is a different kettle of fish altogether. Quite remarkably someone has ported VNC there which should do the job just nicely.


text:
Q: how can i further understand the compilation process used by gcc? I was trying to reverse engineer some psp programs developed using the free
pspsdk
https://sourceforge.net/projects/minpspw/
I noticed that i created a function to see how MIPS handles more than 4 arguments (a0-a4).
Everyone i know has told me that they get passed onto the stack.
To my surprise, that 5th argument was actually passed to register t0 and to compiler didn't even use the stack!
it also inlined a function without even having used a jal or jump to it. (obvious optimization).
Altough there was indeed a space a memory and you could double check by using print with function pointer argument. That actual code that was executed was automatically inlined without the need of a function call instruction.
^^ but that doesn't really benefit me for a reverse engineer attempt...
there is a man page for this version of gcc. and it takes seconds to install if anyone is able to provide it's man for compilation if there is one.
It's so long i don't even know how to reference information reliably

A: How arguments are passed is specified by the ABI (application binary interface).  So you have to find respective documents.
Moreover, there is more than one such ABI, namely n32 and n64.  In the case of mips-gcc, some of the decisions are commented in the GCC sources like in ./gcc/config/mips/mips.h
/* This structure has to cope with two different argument allocation
   schemes.  Most MIPS ABIs view the arguments as a structure, of which
   the first N words go in registers and the rest go on the stack.  If I
   < N, the Ith word might go in Ith integer argument register or in a
   floating-point register.  For these ABIs, we only need to remember
   the offset of the current argument into the structure.

   The EABI instead allocates the integer and floating-point arguments
   separately.  The first N words of FP arguments go in FP registers,
   the rest go on the stack.  Likewise, the first N words of the other
   arguments go in integer registers, and the rest go on the stack.  We
   need to maintain three counts: the number of integer registers used,
   the number of floating-point registers used, and the number of words
   passed on the stack.

   We could keep separate information for the two ABIs (a word count for
   the standard ABIs, and three separate counts for the EABI).  But it
   seems simpler to view the standard ABIs as forms of EABI that do not
   allocate floating-point registers.

   So for the standard ABIs, the first N words are allocated to integer
   registers, and mips_function_arg decides on an argument-by-argument
   basis whether that argument should really go in an integer register,
   or in a floating-point one.  */

There are more such comments in the mips backend.  Search for "cumulative" or "CUMULATIVE" in mips.c and mips.h.


text:
Q: Send email via python in c++ my question is whether I can send an email via python in a c++ program.
That is my actual python script.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
# From
fromaddr = "...@gmail.com"
# To
toaddr = "..."
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
# subject
msg['Subject'] = "..."
# Text
body = "..."
msg.attach(MIMEText(body, 'plain'))
#smtplib import
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("username", "password")
text = msg.as_string()
#send email
server.sendmail(fromaddr, toaddr, text)

My plan ist it, that I will open python and import the script via the commandline in the programm.
Is there a better way to do it?
The problem is that c++ open via system("python") the commandline, but now I have to write import mail.py in the command line.
Can I do this automaticly with an other order? I will open python, import mail and quit with one order. Is that possible?
Thank You!

A: Here is the program for an email.
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(email, password)
smtpserver.sendmail(email, recipient, text)
print 'Message Sent!'
smtpserver.close()

The variables: email is your email address, password is the password to your email, recipient is the receiver of the email, and text is the text to send.


text:
Q: SIGABRT on cast to UIImage I'm using FastttCamera as a wrapper to AVFoundation for taking, processing and displaying a picture. Here's my code (a FastttCamera delegate method) in which I cast (FastttCapturedImage *) to (UIImage *):
- (void)cameraController:(FastttCamera *)cameraController didFinishScalingCapturedImage:(FastttCapturedImage *)capturedImage
{
    //Use the captured image's data--note that the FastttCapturedImage is cast to a UIImage
    NSData *pngData = UIImagePNGRepresentation((UIImage *)capturedImage);

    //Save the image, and add the path to this transaction's picPath attribute
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory

    int timestamp = [[NSDate date] timeIntervalSince1970];

    NSString *timeTag = [NSString stringWithFormat:@"%d",timestamp];

    NSString *filePath = [documentsPath stringByAppendingString:timeTag]; //Add the file name
    [pngData writeToFile:filePath atomically:YES]; //Write the file

    self.thisTransaction.picPath = filePath;

    [self.viewFinder setImage:(UIImage *)capturedImage];
}

However, I'm getting a SIGABRT at the line:
    NSData *pngData = UIImagePNGRepresentation((UIImage *)capturedImage);

with this console readout:
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[FastttCapturedImage CGImage]: unrecognized selector sent to instance 0x17e2a100'

I'm confused by the reference to CGImage. Is it a problem with my typecast? There was no complaint on build. Can someone please set me straight?

A: Read the docs for FastttCapturedImage. It's not a UIImage so you can't just cast it like that. Use the provided property to get the UIImage.
Change the problematic line to:
NSData *pngData = UIImagePNGRepresentation(capturedImage.fullImage);

You have the same problem later:
[self.viewFinder setImage:capturedImage.fullImage];

BTW - you didn't get a problem while compiling because a cast is a way to tell the compiler "trust me, it's really what I'm telling you it is". The problem here is you were wrong, it's not really what you claimed it was. :)


text:
Q: Directive changes CSS when element is active I'm very new to Angular so I'm sure this isn't correct but I have a set of
 elements which further contain links (individually, they're just navigation buttons for my page). What I'd like is to keep the specific button, say, "Home" highlighted a certain color while the user is on that page. So my html roughly looks like this...

           Home

I literally just wrote my first custom Directive yesterday so here's my second attempt at one...
app.directive( 'changeCss', [ '$location',
    function ( ) {
        return {
            restrict: 'A',
            scope: {
                active: '&'
            },
            link: function( $scope, element, attrs ){
                if( $scope.active ){
                    element.addClass( 'actives');
                }
                else {
                    element.addClass( 'inActives' );
                }
            }

        };
    }
] );

And my isActive() function looks like...
    var active = false;
    $scope.aap.isActive = function( ){
        if ( active ){
            active = false;
            return true;
        } else {
            active = true;
            return false;
        };
    };

Now, when I load up the page all the navigation buttons (Home, Save, etc.) are the color I'd like them to be. Clicking on a button, say, "Home" highlights that button in the color I'd like it to be. But, when I interact with that Home page at all, click an accordion element for instance, the color goes back to the "inactive" color. What am I doing wrong?

A:  I'm not 100% sure for this. but I hope this might help you. If you want to set the active/inactive of your navigation bar base on your page.
I use ng-class for setting active of the navigation bar (see here https://docs.angularjs.org/api/ng/directive/ngClass) by passing the uri to the function getClass().

                Dashboard

                Sessions

at my Controller I check the location path and sends boolean for activating/deactivating the ng-class
.controller('mainCtrl', ['$location','$scope', function ($location, $scope) {

        $scope.getClass = function(path) {
            if ($location.path().substr(0, path.length) == path) {
              return true;
            } else {
              return false;
            }
        }

    }]);


text:
Q: dplyr summarise evaluates custom function twice? I am using dplyr group_by and summarise functions with custom made aggregate function, and have observed a strange behavior. It seems like the aggregate function is evaluate twice for each group.
Here is a minimal example:
aggFun <- function(x) { print("Inside function"); print(rnorm(1)); sum(x)}
df <- data.frame(key = rep("a", 3), val = 1:3)
df %>% group_by(key) %>% summarise(sum = aggFun(val))

The following is output:
[1] "Inside function"
[1] 0.3230769
[1] "Inside function"
[1] -0.3347653
# A tibble: 1 × 2
   key   sum
<fctr> <int>
1      a     6

Since there is only one group, shouldn´t the function only be evaluated once? I am experiencing the same thing in a large application, and worry that this might be bad for performance, or am I missing something?
Solved by upgrading to GitHub version.


text:
Q: CSS layout inside layout I have a layout frame of small widget with top navbar and bottom navbar. Inside that widget i have items and in one of them i have to put another layout(same as parent). This is small example of mine css problem, where footer in child layout is not in the bottom.
.body{
    position: static;
    width: 100%;
    height: 100%;
}
.header{
    position: absolute;
    top: 0px;
}
.footer{
    position: absolute;
    bottom: 0px;
}
.main{
    position: relative;
    width: 100%;
    height: 100%;
    padding-top: 50px;
    padding-bottom: 50px;
}
.item{
    position: relative;
    width: 100%;
}
.view{
    height: 100%;
}

this dont get the height of height in parent widget, how can i fix that?

A: I manage to build the layout i want without any kind of positions, i removed all of them. I use:
display: table;
display: table-row;

for mine layout and it works perfectly. Here is the example of what i did. Below is general css of what i did.
.body{
    height: 100%;
    display: table;
    width: 100%;
    text-align: center;
}
.header{
    display: table-row;
    width: 100%;
    height: 50px;
    background-color: blue;
}
.footer{
    display: table-row;
    bottom: 0px;
    width: 100%;
    height: 50px;
    background-color: grey;
}
.main{
    display: table;
    width: 100%;
    height: 100%;
}
.item{
    display: table-row;
    width: 100%;
}
.fullExtend{
    height: 100%;
}
html, body { height: 100%; }

Class body is container for widget, header and footer is for header and footer for each widget, main is the body of widget, item is part of main which can be widget and fullExtend is item which height get maximum space left in page.

A: Do you want to achieve something like this?
Edit: I refined your structure a bit. You want to achieve this?
HTML :

    Main Header

                Item 1 Header

                    Item 2

                Item 1 Footer

    Main Footer

CSS:
html{
  height: 100%;
}

body{
  margin: 0;
  padding: 0;
  height: 100%;
}
.main-header{
    position: absolute;
    top: 0px;
    background-color: blue;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: white;
    text-align: center;
}

.main-footer{
    position: absolute;
    bottom: 0px;
    background-color: grey;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: white;
    text-align: center;
}
.wrapper{
  position: relative;
  padding: 50px 0;
  box-sizing: border-box;
  height: 100%;
}
.header{
    position: absolute;
    top: 0px;
    width: 100%;
    height: 50px;
    background-color: darkblue;
  color: white;
}
.footer{
    position: absolute;
    bottom: 0px;
    width: 100%;
    height: 50px;
    background-color: darkgrey;
  color: white;
}
.item{
    position: relative;
    width: 100%;
    height: 100%;
}
.item-view{
  height: 100%;
  position: absolute;
  width: 100%;
  padding-top: 50px;
  box-sizing: border-box;
}
.item-content{
  position: relative;
  top: 50px;
}


text:
Q: Node.js - promises and conidtional statements (if, switch, etc) - how to structure? Can you recommend how to correctly deal with a control flow with many if/switch and promises? All the tutorials on the Internet that I've found tend to deal with simple control flow, without many (any?) different processing branches. Any suggested reading or at least search terms?
The way I do it now is to encapsulate if/switch logic in a function that returns a Promise after evaluating the conditions and returns to the main process loop. Any way to do it better, nicer?
Sample code:
// Check if argument is a valid URL
Promise.promisify(checkUrl)().then(() => {
        // Delete all query parameters from URL if present
        return sanitizer.cleanAsync(argv.url)
    }).then(_cleanUrl => {
        cleanUrl = _cleanUrl;
        logger.warn(`URL: ${cleanUrl}`);
        // Validate Google Analytics view id supplied as '--gaId=<id>' command line argument or exit if it is not present
        return Promise.promisify(checkGaId)()
    }).then(() => {
        // Check if DB exists, if not create it
        return db.checkIfDatabaseExistsAsync()
    }).then(() => {
        // Check if all tables exist, if not create them
        return db.checkTablesAsync()
    }).then(() => {
        // Check DB integrity (possiblDelete all query parameters from URL if presente to turn off in the config)
        if (config.database.checkIntegrity) {
            return db.integrityChecksAsync();
        }
    }).then(() => {
        // Check if URL already exists in DB, if not insert it
        return db.getOrCreateEntryUrlIdAsync(cleanUrl)
    }).then(_entryId => {
        entryId = _entryId;
        // Check if any previous executions for the entry point exist and if so whether the last one completed
        return db.getLastExecutionDataAsync(entryId);
    }).then(lastExecution => {
        // If last execution was not completed prompt for user action
        return processLastExecution(entryId, lastExecution)
    }).then(_pages => {
       ... more code follows here...

And psuedo-code for processLasExecution function:
function processLastExecution(entryId, lastExecution) {
return new Promise(
    function (resolve, reject) {

        // No previous executions found or all was okay
        if (lastExecution == null || (lastExecution != null && lastExecution.is_completed == 'Y')) {

            ...resolves with A;

        } else {

            Promise.promisify(selectRunOption)().then(option => {

                switch (option) {

                    case 'resume':

                        ...resolves with B;
                        break;
                    case 'ignore':

                        ...resolves with C;
                        break;
                    case 'delete':

                        ...resolves with D;
                        break;
                    default:
                        ...rejects
                }
            });
        }
    }
)

}
Any way of having the if/switch logic better/more clearly encapsulated or served?
Oh, if anyone wonders this is a command line script, not a web application, and this not exactly what Node.js was intended for.

A: I think it is better to use generator, then you can write sync like codes:
co(function* () {
   // Check if argument is a valid URL
   if (yield checkUrl) {
       var cleanUrl = yield sanitizer.cleanAsync(argv.url);
       ...
   }
   ...
}, ...

co can cooperation with callback and promise, see https://github.com/tj/co


text:
Q: Interface implementation in to my project STARTING QUESTION
My general understanding of Interfaces is fine, I've read hundreds of examples and different articles on this subject but I'm still on a hold, because all this reading still hasn't given me an answer to where to use this tool in my own project.
I'll try to come with a concrete example from my project on where I probably would have benefits from using Interfaces and hopefully someone could give me a concrete answer on how I should implement it.
My purpose with this project was to draw an image in A4 size and preview it in a PictureBox (resized) and then have a GUI to create and move a barcode (with a caption text underneath) on this image in the PictureBox.
Now I want to be able to draw another text object with same functionalities to move it around and show on the preview. But this will be a normal text and therefore it would have a different font and no caption.
This could easily be done with a collection and a loop when drawing.
But what if I want to add more objects to this image, wouldn't it be a lot easier to maintain and extent, if I used Interfaces?
I would also like to elaborate my programming, by learning how to use something a little bit more complex.
CURRENT APPROACH TO A SOLUTION
My main Interface
public interface IElementCreator
{
    int posX { get; set; }
    int posY { get; set; }
    StringFormat format { get; set; }
    string value { get; set; }
    Font font { get; set; }
    bool caption { get; set; }
    Font captionFont { get; set; }
}

My main class for creating an element
public class ElementBase : IElementCreator, IImageUpdater
{
    #region IElementCreator Variables

    private int _posX;
    private int _posY;
    private StringFormat _format;
    private string _value;
    private Font _font;
    private bool _caption;
    private Font _captionFont;

    #endregion

    #region IElementCreator Members

    public int posX
    {
        get { return _posX; }
        set { _posX = value; }
    }

    public int posY
    {
        get { return _posY; }
        set { _posY = value; }
    }

    public StringFormat format
    {
        get { return _format; }
        set { _format = value; }
    }

    public string value
    {
        get { return _value; }
        set { _value = value; }
    }

    public Font font
    {
        get { return _font; }
        set { _font = value; }
    }

    public bool caption
    {
        get { return _caption; }
        set { _caption = value; }
    }

    public Font captionFont
    {
        get { return _captionFont; }
        set { _captionFont = value; }
    }

    #endregion

    #region Constructor

    public ElementBase(int posX, int posY, StringFormat format, string value, Font font, bool caption, Font captionFont)
    {
        this.posX = posX;
        this.posY = posY;
        this.format = format;
        this.value = value;
        this.font = font;
        this.caption = caption;
        this.captionFont = captionFont;
    }

    #endregion

    public Image updatePreview(IElementCreator element, Image img)
    {
    }
}

Interface to update the preview image
public interface IImageUpdater
{
    Image updatePreview(IElementCreator element, Image img);
}

I've not been able to test this yet, I've made the code and I'll start testing later.
What I'm trying to achieve, is to have an interface to handle the creation of a basic text element. With this it should be possible to extent with new classes to handle text elements with different settings.
This is just a starting point and I know some code are missing for everything to make sence, but I just want to share and make sure that i'm not completely of track.

A: What you could do if have a class which is responsible for creating image
public class ImageCreator : IImageCreator
{
    public Image CreatePreviewImg(string value, int fontSize, int x, int y)
    {
        //Your code goes here...
    }
}

then whenever you want to generate an image you could create an instance of image creator
IImageCreator imageCreator = new ImageCreator;
var preview = imageCreator.CreatePreviewImg(...);

thanks to this approach you could have multiple image creators implementing IImageCreator interface and your manager would decide which one to use.
Hope that give you an idea how to use interface in your project.
UPDATE
*LATEST UPDATE AS OF 09/02/2012*
here's how the interface should look like
public interface IImageCreator
{
    public Image CreatePreviewImg(string value, int fontSize, int x, int y);
}

as soon as you implement interface to your class, you will have to write code for that method. so your class would look like :
this is your image item - an object you will pass to image creator (this object contains all values you need to generate an image) and it's interface below
    public class ImageSettings : IImageSettings
    {
        public int posX { get; set; }
        public int posY { get; set; }
        public StringFormat format { get; set; }
        public string value { get; set; }
        public Font font { get; set; }
        public bool caption { get; set; }
        public Font captionFont { get; set; }
    }

    public interface IImageSettings
    {
        int posX { get; set; }
        int posY { get; set; }
        StringFormat format { get; set; }
        string value { get; set; }
        Font font { get; set; }
        bool caption { get; set; }
        Font captionFont { get; set; }
    }

    public class ImageCreator : IImageCreator
    {

THIS IS NEW METHOD WHICH ACCEPTS TYPE OF AN INTERFACE INSTEAD OF PARAMS
        public Image CreatePreviewImg(IImageSettings imageSettings)
        {
            //ALL THE MAGIC HAPPENS HERE
        }

THIS IS THE OLD METHOD - NO LONGER REQUIRED
            public Image CreatePreviewImg(string value, int fontSize, int x, int y)
            {
                // Iniziate barcode font
                PrivateFontCollection private_fonts = new PrivateFontCollection();
                private_fonts.AddFontFile("FREE3OF9.TTF");
            //Image size A4 at 300dpi
            Bitmap bm = new Bitmap(width, height);
            bm.SetResolution(300, 300);

            // Create rectangle for the canvas
            RectangleF rectBg = new RectangleF(0, 0, width, height);

            // Load fonts
            Font bcFont = new Font(private_fonts.Families[0], fontSize, FontStyle.Regular, GraphicsUnit.Point);
            Font valueFont = new Font("Tahoma", 12, FontStyle.Regular, GraphicsUnit.Point);

            // Set StringFormat for the text value
            StringFormat sfValue = new StringFormat();
            sfValue.LineAlignment = StringAlignment.Far;
            sfValue.Alignment = StringAlignment.Center;

            // Set StringFormat for the barcode string
            StringFormat sfBarcode = StringFormat.GenericTypographic;
            sfBarcode.FormatFlags = StringFormatFlags.NoClip;

            using (Graphics g = Graphics.FromImage(bm))
            {
                // Create rectangle to place the barcode and text
                SizeF bcStringSize = g.MeasureString("*" + value + "*", bcFont);
                SizeF valueSize = g.MeasureString(value, valueFont);
                RectangleF recText = new RectangleF(x, y, (float)MeasureDisplayStringWidth(g, "*" + value + "*", bcFont), (float)(bcStringSize.Height + valueSize.Height));

                // Drawing the barcode and text
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                g.FillRectangle(new SolidBrush(Color.White), rectBg);
                g.DrawString("*" + value + "*", bcFont, new SolidBrush(Color.Black), recText, sfBarcode);

                g.DrawString(value, valueFont, new SolidBrush(Color.Black), recText, sfValue);
            }

            return bm;
        }
    }

A:
But what if I want to add more objects to this image, wouldn't it be a
  lot easier to maintain and extent, if I used Interfaces? I would also
  like to elaborate my programming, by learning how to use something a
  little bit more complex.

That entirely depends if you are going to have multiple classes that implement the interface.
I see nothing in your code code that would warrent an interface.  Have you considered reading a book on how to program in C# by chance?  Reading examples is a horrible way of learning how to program, you need to understand the correct way to program, and often time that only comes from books written by people in the industry with decades worth of experience.


text:
Q: Best way to catch a WCF exception in Silverlight? I have a Silverlight 2 application that is consuming a WCF service.  As such, it uses asynchronous callbacks for all the calls to the methods of the service.  If the service is not running, or it crashes, or the network goes down, etc before or during one of these calls, an exception is generated as you would expect.  The problem is, I don't know how to catch this exception.

*

*Because it is an asynchronous call, I can't wrap my begin call with a try/catch block and have it pick up an exception that happens after the program has moved on from that point.

*Because the service proxy is automatically generated, I can't put a try/catch block on each and every generated function that calls EndInvoke (where the exception actually shows up).  These generated functions are also surrounded by External Code in the call stack, so there's nowhere else in the stack to put a try/catch either.

*I can't put the try/catch in my callback functions, because the exception occurs before they would get called.

*There is an Application_UnhandledException function in my App.xaml.cs, which captures all unhandled exceptions.  I could use this, but it seems like a messy way to do it.  I'd rather reserve this function for the truly unexpected errors (aka bugs) and not end up with code in this function for every circumstance I'd like to deal with in a specific way.
Am I missing an obvious solution?  Or am I stuck using Application_UnhandledException?
[Edit]
As mentioned below, the Error property is exactly what I was looking for.  What is throwing me for a loop is that the fact that the exception is thrown and appears to be uncaught, yet execution is able to continue.  It triggers the Application_UnhandledException event and causes VS2008 to break execution, but continuing in the debugger allows execution to continue.  It's not really a problem, it just seems odd.

A: I found a forum thread that was talking about this, and it mentions that the best practice is to use the Error property. Between this thread and my own experiences, this is what I can conclude:

*

*In normal .NET code, the generated proxy class handles the exception properly by putting the exception in the Error property instead of throwing it.

*In Silverlight, the generated proxy class sets the Error property, but does not handle the exception completely.  The exception is picked up by the debugger, which pops up the exception box with the message "ProtocolException was unhandled by user code".  Despite this message, the exception does not seem to actually make it to the Application_UnhandledException function.
I'd expect that this is one of the things they will fix in the final release.
For now, I will use the Error property and just deal with the debugger breaking execution.  If it gets too annoying, I can turn off the break on exception for ProtocolException.

A: I check the Error property of the event args in the service method completed event handler.  I haven't had issues with the event handler not being called.  In the case where the server goes down, the call takes a few seconds then comes back with a ProtocolException in the Error property.
Assuming you have tried this and your callback really never gets called, you might look into customizing the generated proxy class.  See this article.

A: You can forget about Application_UnhandledException on asyn client callbacks, reason why:
Application_UnhandledException only exceptions fired on the UI thread can be caught by Application.UnhandledExceptions
This means... not called at all for a WCF async call :-).
Check detailed response from MSFT
http://silverlight.net/forums/t/21828.aspx
Hello, only exceptions fired on the UI thread can be caught by Application.UnhandledExceptions. It can't catch exceptions from other threads. You can try this to trouble shoot the issue: In Visual Studio, from the Debug menu, choose Exceptions. Then check "Common Language Runtime Exceptions". This will make the debugger stop whenever an exception is thrown. But note this may be quite annoying sometimes since even if an exception is already caught. You can use the CheckBoxes to filter the exceptions you want to catch.
Good news in my case is that handling the error message just in the clietn service call back is enough if you are not debugging.
Thanks
Braulio

A: OOpps....
Sorry wrong answer from my side (well the MSFT guy didn't hit the write answer service callbacks are called on the same UI thread), the thing is
More info:
- In development even detaching from the debugger, this method is never reached.
- On the production environment yes.

My guess something related with Visual Studio options and intercepting exceptions.
More info, in this thread
http://silverlight.net/forums/p/48613/186745.aspx#186745
Quite interesting topic.

A: I'm not a plumber, so I decided to create my own WCF service class that overrides some of the functionality of the class file "reference.cs" that is automatically generated by Visual Studio, I then added my own try/catch blocks to catch communication errors.
The class I created looks something like this:
public class myWCFService : MyWCFServiceClient
{

    protected override MyController.MyService.IMyWCFService CreateChannel()
    {
        return new MyWCFServiceClientChannel(this);
    }

}

private class MyWCFServiceClientChannel : ChannelBase<MyController.MyService.IMyWCFService>, MyController.MyService.IMyWCFService
{
    /// <summary>
    /// Channel Constructor
    /// </summary>
    /// <param name="client"></param>
    public MyWCFServiceClientChannel(System.ServiceModel.ClientBase<MyController.MyService.IMyWCFService> client) :
    base(client)
    {
    }
    /// <summary>
    /// Begin Call To RegisterUser
    /// </summary>
    /// <param name="memberInformation"></param>
    /// <param name="callback"></param>
    /// <param name="asyncState"></param>
    /// <returns></returns>
    public System.IAsyncResult BeginRegisterUser(MyDataEntities.MembershipInformation memberInformation, System.AsyncCallback callback, object asyncState)
    {
        object[] _args = new object[1];
        _args[0] = memberInformation;
        System.IAsyncResult _result = base.BeginInvoke("RegisterUser", _args, callback, asyncState);
        return _result;
    }
    /// <summary>
    /// Result from RegisterUser
    /// </summary>
    /// <param name="result"></param>
    /// <returns></returns>
    public MyDataEntities.MembershipInformation EndRegisterUser(System.IAsyncResult result)
    {
        try
        {
            object[] _args = new object[0];
            MyDataEntities.MembershipInformation _result = ((MyDataEntities.MembershipInformation)(base.EndInvoke("RegisterUser", _args, result)));
            return _result;
        }
         catch (Exception ex)
        {
            MyDataEntities.MembershipInformation _result = new MyDataEntities.MembershipInformation();
            _result.ValidationInformation.HasErrors = true;
            _result.ValidationInformation.Message = ex.Message;
            return _result;
        }
    }
}

A: With Silverlight 3 the the Visual Studio debugger catches these exceptions so that the exception handler - confusingly - is never reached. However, when running without the debugger, the exception handler is called as expected. I guess this is ok as long as one is aware of it. I admit i wasted a few hours trying to figure out how to drill into the inner workings of Silverlight/Wcf/Browser to get to my exception. Don't go there.

A: Using a custom WCF Proxy generator is a good solution to handle asynchronous exceptions in Silver-light.Click here to download source code.

A: With XNA on WP7, I found I had no choice but to manually add try/catch to the various async End*FunctionName*() methods; nothing else I tried would prevent application failure & shutdown when the server was unavailable. It's a real drag having to manually update this code when a service changes.
I am surprised this isn't a bigger issue since there doesn't seem to be any other way to catch these exceptions on WP7 using XNA but I suppose this just says more about how many (==not many) people are trying to do this than anything else. If they would just make slsvcutil.exe generate sync methods we could easily catch these within our own worker thread, but unfortunately the generated code uses thread pool threads with no means to catch the exceptions.

A: To Handle this situation use the TargetInvocationException. This will catch the Exception when the network is down or your service is unavailable.


text:
Q: Why does fgets not work in an "if" statement? So I'm creating a program to read in data and stuck on this part. So if someone choses "1" from the menu section, it should prompt the user to enter "Name of band of Singer", but when I actually run the code, it prints the prompt but also goes back to the menu screen.
I have only copied and pasted the part where I need help in. The stuff inside "fgets" is for a struct.
int main() {
    while (1) {
        printf("The following options are available \n"
            "Read in data [1] \n"
            "Print out catalogue to screen [2] \n"
            "Save data to file [3] \n"
            "Exit Program [4] \n"
            "Enter your choice now ");
        scanf_s("%d", &menu_num);
        if (menu_num == 1) {
            printf("Name of band of Singer: ");
            fgets(hold[0].singer, 20, stdin); }


text:
Q: Syntax for Import Into from Different DBs - MS Access I'm trying to do (basically) an automated row copy from one backend to another as the backend is being used but is not fully developed (some tables are done, others not; adding the completed data into the more advanced db at the end of the day).
I'd like to know what the syntax is for an SQL statement which:
INSERT INTO tblMyBetterTable * IN "C:\\path_to_db\db.accdb"
FROM tblMyTable IN "C:\\path_to_in_use_db\in-use-db.accdb"

The syntax is not correct but I've searched for a while and can't find out how.. I've seen how to import from one table to another etc, but not across backends. If it's not clear, I'd like to basically do a table copy of all rows in in-use-db.accdb from tblMyTable to the latest version of the backend db.accdb's table tblMyBetterTable.

A: I suggest you try DoCmd.TransferDatabase
For a query, you need something on the lines of:
SELECT * INTO NewTable
FROM [;DATABASE=Z:\Docs\Test.accdb].Table1

Or the other way round:
SELECT * INTO [;DATABASE=Z:\Docs\Test.accdb].NewTable
FROM Table1

To insert into an existing table:
INSERT INTO table1
SELECT *
FROM [;DATABASE=Z:\Docs\Test.accdb].Table1


text:
Q: Why does my call stack in VS2005 only show DLL calls and not the originating call? Please forgive my ignorance, but I am not familiar with Visual Studio or Windows DLLs & services. Normally I work in an embedded environment but somehow (just lucky I guess) I got selected to troubleshoot a crash that occurred in one of our Windows services, well actually in MSVCR80.DLL, but which I must presume was caused by our service (Windows event log below)
Faulting application name: MySrvc.exe, version: 0.0.0.0, time stamp: 0x4fee02e5
Faulting module name: MSVCR80.dll, version: 8.0.50727.4940, time stamp: 0x4ca2b271
Exception code: 0xc000000d
Fault offset: 0x00008aa0

The trouble I'm having is that when I attach to the process and then get it to crash, the debugger breaks and then the call stack only has some calls within mscvr80.dll and ntdll.dll and that's it, no calls from our service into those libraries. My guess is that the library is multi-threaded and the stack I'm seeing is just one of it's threads. But when the VS debugger breaks, does it not pause all threads? And is there a way to examine the call stacks of the other threads? Or am I completely off base here?
Again, please forgive my ignorance in this area. Any advice or direction you can offer will be greatly appreciated. Thanks in advance!
-H

A: There are two possibilities:

*

*You're looking at the wrong thread, as you say, in which case you can switch to the right one using the Threads window, via Debug / Windows / Threads.  (But that's unlikely - when a thread crashes, VS will show you that thread.)

*You need to load the symbols for the system DLLs - Visual Studio sometimes can't follow stack traces without the symbols.  Go to Tools / Options / Debugging / Symbols and make sure you're obtaining symbols from Microsoft.


text:
Q: "socket closed" error when I try to send/receive a jxrpc over a socket stream This is my code:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);//suggested by fge

Socket s = new Socket("127.0.0.1",port);
mapper.writeValue(s.getOutputStream(),anObjectRequest);//this works
Aresponse res = mapper.readValue(s.getInputStream(),AresponseClass.class);

I get that the socket is closed.
But, if look into wireshark, I see the server correctly receives the request and correctly sends the answer too!
Where is the problem?

A: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getOutputStream()

Closing the returned OutputStream will close the associated socket

What type is mapper?  Does this method:
mapper.writeValue(s.getOutputStream(),anObjectRequest);//this works

call close on the OutputStream object?
Assuming you are using an ObjectMapper:

Note: method does not close the underlying stream explicitly here; however, JsonFactory this mapper uses may choose to close the stream depending on its settings (by default, it will try to close it when JsonGenerator we construct is closed).

You'll have to pay attention to which JsonFactory you are using.


text:
Q: valueForUndefinedKey:]: this class is not key value coding-compliant for the key imgSelect Swift Receiving error: valueForUndefinedKey:]: this class is not key value coding-compliant for the key imgSelect
I have a tableview with that is editable.. When selecting cell, it takes you to edit information. Everything works great, except the image. User can save image, image is displayed in tableview, but when going back to edit, it crashes. Here is the poorly written code:
without trying to reload the image to edit, everything else works. The image is saved to database and is displayed in tableview..
var existingItem: NSManagedObject!

override func viewDidLoad() {

    super.viewDidLoad()

// Reload data to edit
if existingItem {

    txtPTitle.text = project
    txtPDesc.text = desc
    txtSDate.text = sdate
    txtEDate.text = edate

}

but when I add the following to load image when editing tablecell
// Reload data back into form
if existingItem {

    txtPTitle.text = project
    txtPDesc.text = desc
    txtSDate.text = sdate
    txtEDate.text = edate

    var data: NSManagedObject = NSManagedObject()
    let imageData:NSData = data.valueForKeyPath("projectImage") as NSData
    let projectImage:UIImage = UIImage(data: imageData)
    println("we have an image")

    imgSelect.image = projectImage

}
it crashes with the following error.
'NSUnknownKeyException', reason: '[<_NSZeroData 0x7fe7f1c3b020> valueForUndefinedKey:]: this class is not key value coding-compliant for the key imgSelect.'

A: I would suspect that you haven't actually bound imgSelect in Interface Builder.
Does it actually crash at the imgSelect.image = projectImage line, or perhaps earlier (such as during NIB loading)? Is imgSelect correctly? In either beta 4 or beta 5, they changed the way IBOutlets are defined, and you should make sure you've done a complete clean and rebuild since then (otherwise you could wind up with the wrong object, as you're seeing).


text:
Q: HuggingFace Tokenizer: how to get a token for unicodes strings? The following code does not provide a token for the unicode string '\uf0b7':
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased',
do_lower_case=True)
test_words = ['crazy', 'character', '\uf0b7']
input_ids = tokenizer(test_words,is_split_into_words=True)
print(f'token ids: {input_ids["input_ids"]}')
# token ids: [101, 4689, 2839, 102]  # <- where is the token for the third word?

print(f'word ids:  {input_ids.word_ids()}')
# word ids:  [None, 0, 1, None]   # <- where is the third word (indice 2)?

Is there a way to tell the tokenizer to give a token to the unicode word (e.g. the unknown [UKN]  token or anything else)?
I've tried to add a normalizer, but the output is the same:
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
normalizer = normalizers.Sequence([NFD(), StripAccents()])
tokenizer.normalizer = normalizer
input_ids = tokenizer(test_words,is_split_into_words=True)
print(f'token ids: {input_ids["input_ids"]}')
# token ids: [101, 4689, 2839, 102]

A: Add your desired Unicode as Special Tokens?
    special_tokens_dict = {'additional_special_tokens': ['\uf0b7']}
    num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
    test_words = ['crazy', 'character', '\uf0b7']
    tokenizer(test_words, is_split_into_words=True)

output:
{'input_ids': [101, 4689, 2839, 30522, 102], 'token_type_ids': [0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1]}


text:
Q: Extract an unreferenced assembly from xap file I have a xap file that contains an unreferenced assembly: b.dll.
This assembly was put in the xap file manually (by a post build step, in which I just add the dll to zip(xap) file).
Now at runtime I want to access b.dll and call CreateInstance on it.
This is where I am stuck. How can I get an Assembly instance for b.dll from the xap file?
Thank you!

A: You can initialise a StreamResourceInfo object with a downloaded zip stream (Xap or otherwise).
You can then use Application.GetResourceStream to pull a stream for file from that zip using a Uri.  In this case the dll which can then load with AssemblyPart and then call a CreateInstance on it:-
 WebClient client = new WebClient()
 client.OpenReadCompleted += (s, args) =>
 {
    StreamResourceInfo zip  = new StreamResourceInfo(args.Result, "application/zip");
    StreamResourceInfo dll = Application.GetResourceStream(zip, new Uri("b.dll", UriKind.Relative));
    AssemblyPart assemblyPart = new AssemblyPart();
    Assembly assembly = assemblyPart.Load(dll.Stream);

    _someClassFromB = assembly.CreateInstance("b.SomeClass");
 };
 client.OpenReadAsync(new Uri("your.xap", UriKind.Relative));


text:
Q: Bash : how to pass arguments to a heredoc script Imagine you have a silly script test.sh to which arguments are passed that would look like this:
bash test.sh arg1 arg2 arg3

with test.sh being a silly script that displays its command line:
#!/bin/bash
echo "$0 $*"

I would like to do the same using bash heredoc << to feed the script to bash.
So I tried this :
bash <<'EOF' -- arg1 arg2 arg3
echo "$0 $*"
EOF

But it fails with error
bash: arg1: No such file or directory

Any idea ?

A: The here document is passed to the inner bash on its standard input. You need to instruct bash to read from standard input. With no command line arguments, this happens automatically. If there's at least one non-option argument and no -s or -c option, the first non-option argument is the name of the script file to run. You can pass the -s option to tell bash to read from standard input.
bash <<'EOF' -s -- arg1 arg2 arg3
echo "$0 $*"
EOF

A: Alternatively, on most systems, you can do:
bash /dev/fd/3 3<< 'EOF' arg1 arg2 arg3
echo "$0 $*"
IFS= read -rp "Enter something: "
printf 'You entered: "%s"\n' "$REPLY"
EOF

That way, your here-script can still access stdin.


text:
Q: Not able to redirect from one page to another page I am developing web app using spring..
Exception
The origin server did not find a current representation for the target resource or is not willing to disclose  that one exists.
Controller
@RequestMapping(value="/details/{id}")
public String productDtails(@PathVariable int id)
{
ModelAndView model=new ModelAndView("Detail");
model.addObject("prdt",pd.getById(id));
return "redirect:/detail/{id}";
}

Jsp
<c:url var="url" value="/details/${x.id }"></c:url>

${x.product_Name}

A: To redirect anywhere to our project we can use contextPath
Solved Code
<input type= "button" Value="Buy Now" class="button"/>


text:
Q: EF Core Fluent Api chaining configuration How can I chain this in EF Core Fluent API, instead of repeating line by line for each property of table:
        builder.Entity<FoodWeight>().HasIndex(x => x.NutrientDatabankNumber);
        builder.Entity<FoodWeight>().Property(x => x.NutrientDatabankNumber).HasColumnName("NDB_No");
        builder.Entity<FoodWeight>().Property(x => x.SequenceNumber).HasColumnName("Seq");
        builder.Entity<FoodWeight>().Property(x => x.Amount).HasColumnName("Amount");
        builder.Entity<FoodWeight>().Property(x => x.Description).HasColumnName("Msre_Desc");
        builder.Entity<FoodWeight>().Property(x => x.GramWeight).HasColumnName("Gm_Wgt");
        builder.Entity<FoodWeight>().Property(x => x.GramWeight).HasColumnName("Gm_Wgt");
        builder.Entity<FoodWeight>().Property(x => x.NumberOfDataPoints).HasColumnName("Num_Data_Pts");
        builder.Entity<FoodWeight>().Property(x => x.StandardDeviation).HasColumnName("Std_Dev");

A: You can always add an extension method to EntityTypeBuilder, but this doesn't reduce the verbosity greatly:

modelBuilder
    .Entity<FoodWeight>()
    .Configure(
        entity => entity.HasIndex(x => x.NutrientDatabankNumber),
        entity => entity.Property(x => x.NutrientDatabankNumber).HasColumnName("NDB_No"),
        entity => entity.Property(x => x.SequenceNumber).HasColumnName("Seq")
    );

And the extension method:
public static class EntityTypeBuilderExtensions
{
    public static void Configure<T>(this EntityTypeBuilder<T> modelBuilder, params Action<EntityTypeBuilder<T>>[] builders) where T : class
    {
        builders
            .ToList()
            .ForEach(builder => builder(modelBuilder));
    }
}