How do I get the image that I took and submit it to my server

Question: Currently I am able to upload an existed image in the sdcard to my server.  I'm a total newbie in Android programming world and I was wondering how do I dynamically grab the newly taken image and submit it to the server?
This is what I have so far for my onClick event
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            camera.takePicture(myShutterCallback,
                    myPictureCallback_RAW, myPictureCallback_JPG);

            new Thread(new Runnable() {
                public void run() {

                    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
                    //hard code
                    String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";

                    int response= uploadFile(path);
                    System.out.println("RES : " + response);
                }
              }).start();

        }});

This is the codes for my camera functions
    ShutterCallback myShutterCallback = new ShutterCallback(){

    @Override
    public void onShutter() {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_RAW = new PictureCallback(){

    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_JPG = new PictureCallback(){

    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub

        FileOutputStream outStream = null;

        try
        {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");

            if (!mediaStorageDir.exists())
            {
                if (!mediaStorageDir.mkdirs())
                {
                    Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
                }
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";

            outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
            outStream.write(arg0);
            outStream.close();

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
            //VuzixCamera.super.onBackPressed();
        }

        camera.startPreview();
    }};

Comment: I would first store the image in a folder, then read it to send to your server using an Http post request.
Comment: have u knowledge of php?if yes i can provide u a sample program
Comment: Yes, I have knowledge of php.  What's this has anything to do with php?  I've already used php to handle incoming data and submit it to my server and it's in working condition.  I just want `"IMG_20000106_124322.jpg"` to be dynamic
Answer: Hope this answer will help you.
Take A new Picture Code:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class CameraUtil  extends Activity {

    private final static int REQUEST_TAKE_PHOTO=200;
    private final String TAG = "Camera";

    String mCurrentPhotoPath;
    String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(! isDeviceSupportCamera()){
            Log.e(TAG,"Camera Not Supported");
            Intent returnFromCameraIntent = new Intent();
            setResult(RESULT_CANCELED,returnFromCameraIntent);
            finish();
        }
        else{
            dispatchTakePictureIntent();
        }

    }

     private void dispatchTakePictureIntent() {
        Log.i(TAG,"Dispatch Take Picture Intent");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
                File photoFile = null;
                try{
                    photoFile = createImageFile();
                }catch (IOException ex) {
                    // Error occurred while creating the File
                    ex.printStackTrace();
                    Log.i(TAG,"Error occurred while creating the File");
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    //  fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                }
        }
     }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            Log.i(TAG,"On Activity Result");
            File file= new File(path);

            if (requestCode == REQUEST_TAKE_PHOTO  && resultCode == RESULT_OK && path!=null && file.length()>0) {
                        Intent returnFromCameraIntent = new Intent();
                        returnFromCameraIntent.putExtra("picturePath",path);
                        setResult(RESULT_OK,returnFromCameraIntent);
                        finish();
                        Log.i(TAG,"Camera Closed");
                }else{
                    Log.i(TAG,"On Result CANCEL");
                    // cancelled Image capture
                    try{
                    /*delete Temperory created file*/
                        file.delete();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    Intent returnFromCameraIntent = new Intent();
                    setResult(RESULT_CANCELED,returnFromCameraIntent);
                    finish();
                    Log.i(TAG,"Image Capture Cancelled");
           }
           galleryAddPic();
     }

     private File createImageFile() throws IOException {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
            String imageFileName = "CAMERA_" + timeStamp + "_WA0001";

            File root = new File(Environment.getExternalStorageDirectory()
                     + File.separator + "MyApp"+ File.separator);

            if(!root.exists()){
                    root.mkdirs();
            }

           // File storageDir = Environment.getExternalStoragePublicDirectory(
           //         Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                root      /* directory */
            );
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            path=""+image.getAbsolutePath();
            return image;
    }

     private void galleryAddPic() {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File f = new File(mCurrentPhotoPath);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            this.sendBroadcast(mediaScanIntent);
     }

     private boolean isDeviceSupportCamera() {
            if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                // this device has a camera
                return true;
            } else {
                // no camera on this device
                return false;
            }
     }
}

Choose Existing Picture Code:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

public class GalleryUtil extends Activity{
    private final static int RESULT_LOAD_GALLERY=100;
    public static final int MEDIA_TYPE_IMAGE = 1;
    private static final String TAG = "Gallery_Image";

    String mCurrentPhotoPath;
    File photoFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_GALLERY);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         Log.i(TAG,"On Activity Result");
         if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

                Intent returnFromGalleryIntent = new Intent();
                returnFromGalleryIntent.putExtra("picturePath",picturePath);
                setResult(RESULT_OK,returnFromGalleryIntent);
                finish();

           }else{
                Log.i(TAG,"Image Capture Cancelled");
                Intent returnFromGalleryIntent = new Intent();
                setResult(RESULT_CANCELED,returnFromGalleryIntent);
                finish();
           }
    }
}

Convert Image to Base64 String:
public class Base64Utils {

    private static final String TAG = "Base64Utils";
    private String picturePath;
    private String base64;

    public Base64Utils(String picturePath) {
        this.picturePath = picturePath;
    }

    public String getPicturePath() {
        return picturePath;
    }
    public void setPicturePath(String picturePath) {
        this.picturePath = picturePath;
    }

    public String getBase64() {
        FileInputStream fis11=null;
            try {
                fis11 = new FileInputStream(picturePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
            byte[] buf = new byte[8096];
            try {
                for (int readNum; (readNum = fis11.read(buf)) != -1;) {
                    bos11.write(buf, 0, readNum);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        bytes = bos11.toByteArray();
        base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        return base64;
    }

    public void setBase64(String base64) {
        this.base64 = base64;
    }
}

Main Activity Code: Choose or Take Picture, convert it to base64 string and Send Base64 String to Server.
public class CapatureImage extends Activity implements View.OnClickListener {

    private final String TAG = "CapatureImage";
    String picturePath;
    String base64 = null,
    private ImageButton image;
    // for popup
    private PopupWindow pop;

    private final int GALLERY_ACTIVITY_CODE = 200;
    private final int CAMERA_ACTIVITY_CODE = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.CapatureImage);
        configureComponent();
    }

    private void configureComponent() {
        image = (ImageButton) findViewById(R.id.image);
        image.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.image:
            initiatePopupWindow();
            break;
        case R.id.button_camera_dialog:
            Intent camera_Intent = new Intent(this.getApplicationContext(),
                    CameraUtil.class);
            pop.dismiss();
            this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
            break;

        case R.id.button_gallery_dialog:
            Intent gallery_Intent = new Intent(this.getApplicationContext(),
                    GalleryUtil.class);
            pop.dismiss();
            this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
            break;

        case R.id.button_cancel_dialog:
            pop.dismiss();
            break;

        case R.id.button_remove_dialog:
            Log.i(TAG, "Remove Picture");
            image.setImageResource(R.drawable.icon_781q);
            picturePath=null;
            pop.dismiss();
            break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == GALLERY_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
                picturePath = data.getStringExtra("picturePath");
                base64 = new Base64Utils(picturePath).getBase64();
                //send this base64 string to server
            }
            if (resultCode == RESULT_CANCELED) {
                // Write your code if there's no result
            }
        }
        if (requestCode == CAMERA_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
            //  Log.i("Camera_Activity", data.toString());
                picturePath = data.getStringExtra("picturePath");
                base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
            }
            if (resultCode == RESULT_CANCELED) {
                // Write your code if there's no result
            }
        }
    }// onActivityResult

    public void initiatePopupWindow() {
        try {
            // We need to get the instance of the LayoutInflater
            LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.dialoge_choosephoto,
                    (ViewGroup) findViewById(R.id.photo_popup));
            if (picturePath != null && !picturePath.isEmpty()) {
                Log.i(TAG, "Image Exist..Add Remove Button");
                remove = (Button) layout
                        .findViewById(R.id.button_remove_dialog);
                remove.setOnClickListener(this);
                remove.setVisibility(View.VISIBLE);
                pop = new PopupWindow(layout,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
            } else {
                Log.i(TAG, "No Image..remove  Remove Button");
                remove = (Button) layout
                        .findViewById(R.id.button_remove_dialog);
                remove.setOnClickListener(this);
                remove.setVisibility(View.GONE);
                pop = new PopupWindow(layout,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
            }

            // component for popup
            gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
            gallery.setOnClickListener(this);
            camera = (Button) layout.findViewById(R.id.button_camera_dialog);
            camera.setOnClickListener(this);
            cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
            cancel.setOnClickListener(this);
            pop.showAtLocation(layout, Gravity.CENTER, 0, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void displayImage(String path) {
        File imgFile = new File(path);
        if(imgFile.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            image.setImageBitmap(myBitmap);
            image.setScaleType(ScaleType.CENTER_CROP);
        }
   }
}

Comment: Vuzix SmartGlasses does not 'support' ACTION_IMAGE_CAPTURE.  I have to use Surfaceview
Answer: there is two classes upload and main_activity.And i here put it's xml file
public class MainActivity extends Activity {

    final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
    private static final String TAG = "CaptureImage.java";
    public static ImageView showImg = null;
    static String uploadFilePath = " ";
    static String Path;
    static int delete_image_id = 0;
    static TextView imageDetails = null;
    // FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
    static Cursor cursor = null;
    public ProgressDialog dialog_upload = null;
    public String s_name;
    public String s_Adress;
    int serverResponseCode = 0;
    TextView shift_display;
    Uri imageUri = null;
    OnClickListener oclBtnOk = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("VALUES", "It is Working");
            String fileName = "Camera_Example.jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DESCRIPTION,
                "Image capture by camera");

            imageUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

            /*************************** Camera Intent End ************************/

        }
    };
    MainActivity CameraActivity = null;
    Upload upload;
    Button outlet_names_show;
    double latitude;
    double longitude;
    OnClickListener oclBtnOk3 = new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (showImg.getDrawable() == null) {
                Toast.makeText(MainActivity.this, " Picture was not captured ",
                    Toast.LENGTH_SHORT).show();
            } else {
                upload_prescription();
                // CallSummery.flag_bt_merchan=true;

            }

        }
    };
    private Button buttonback;

    /**
     * ********* Convert Image Uri path to physical path *************
     */

    public static String convertImageUriToFile(Uri imageUri, Activity activity) {

        int imageID = 0;

        try {

            /*********** Which columns values want to get *******/
            String[] proj = {MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Thumbnails._ID,
                MediaStore.Images.ImageColumns.ORIENTATION};

            cursor = activity.getContentResolver().query(imageUri, proj, null,
                null, null);

            // Get Query Data

            int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int file_ColumnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            // int orientation_ColumnIndex = cursor.
            // getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);

            int size = cursor.getCount();

            /******* If size is 0, there are no images on the SD Card. *****/

            if (size == 0) {

                // imageDetails.setText("No Image");
            } else {

                if (cursor.moveToFirst()) {

                    imageID = cursor.getInt(columnIndex);
                    delete_image_id = imageID;

                    Path = cursor.getString(file_ColumnIndex);

                }

            }

        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        // Return Captured Image ImageID ( By this ImageID Image will load from
        // sdcard )

        return "" + imageID;
    }

    protected void onCreate(Bundle savedInstanceState) {
        MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CameraActivity = this;
        showImg = (ImageView) findViewById(R.id.showImg);
        upload = new Upload(MainActivity.this);
        final Button photo = (Button) findViewById(R.id.photo);
        final Button upload = (Button) findViewById(R.id.upload);

        photo.setOnClickListener(oclBtnOk);
        upload.setOnClickListener(oclBtnOk3);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (imageUri != null) {
            outState.putString("cameraImageUri", imageUri.toString());
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.containsKey("cameraImageUri")) {
            imageUri = Uri
                .parse(savedInstanceState.getString("cameraImageUri"));
        }
    }

    public void upload_prescription() {
        dialog_upload = ProgressDialog.show(MainActivity.this, "",
            "Uploading file...", true);

        new Thread(new Runnable() {
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {

                    }
                });

                createDirectoryIfNeeded();

                upload.uploadFile(uploadFilePath);

            }
        }).start();

    }

    private void createDirectoryIfNeeded() {
        File direct = new File(Environment.getExternalStorageDirectory()
            + "/Capturetemp");

        if (!direct.exists()) {
            if (direct.mkdir()) {
                // directory is created;
            }

        }

    }

    public void copy(String lo, String lan) throws JSONException {

        String sdCard = Environment.getExternalStorageDirectory().toString();

        Random ran = new Random();

        uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";

        File sourceLocation = new File(Path);
        File targetLocation = new File(uploadFilePath);
        Log.v(TAG, "sourceLocation: " + sourceLocation);
        Log.v(TAG, "targetLocation: " + targetLocation);

        try {

            // 1 = move the file, 2 = copy the file
            int actionChoice = 2;

            // moving the file to another directory
            if (actionChoice == 1) {

                if (sourceLocation.renameTo(targetLocation)) {
                    Log.v(TAG, "Move file successful.");
                } else {
                    Log.v(TAG, "Move file failed.");
                }

            }

            // we will copy the file
            else {

                // make sure the target file exists

                if (sourceLocation.exists()) {

                    InputStream in = new FileInputStream(sourceLocation);
                    OutputStream out = new FileOutputStream(targetLocation);

                    // Copy the bits from instream to outstream
                    byte[] buf = new byte[1024];
                    int len;

                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }

                    in.close();
                    out.close();

                    Log.v(TAG, "Copy file successful.");

                } else {
                    Log.v(TAG, "Copy file failed. Source file missing.");
                }

            }

        } catch (NullPointerException e) {
            // e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (resultCode == RESULT_OK) {

                /*********** Load Captured Image And Data Start ***************/

                String imageId = convertImageUriToFile(imageUri, CameraActivity);

                // Create and excecute AsyncTask to load capture image

                new LoadImagesFromSDCard(MainActivity.this).execute(""
                    + imageId);

                /*********** Load Captured Image And Data End ****************/

            } else if (resultCode == RESULT_CANCELED) {

                Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

            } else {

                Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

            }
        }

    }

    @Override
    public void onBackPressed() {

    }

    public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {

        Context context;
        Bitmap mBitmap;
        private ProgressDialog loadingdailog;

        public LoadImagesFromSDCard(MainActivity context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            loadingdailog = new ProgressDialog(context);
            loadingdailog.setMessage("Loading Image.....");
            loadingdailog.show();

        }

        // Call after onPreExecute method
        @Override
        protected Void doInBackground(String... urls) {

            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;

            try {

                uri = Uri.withAppendedPath(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
                        + urls[0]);

                /************** Decode an input stream into a bitmap. *********/
                bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));

                if (bitmap != null) {

                    /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

                    newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
                        true);
                    // SaveIamge(newBitmap);
                    bitmap.recycle();
                    if (newBitmap != null) {

                        mBitmap = newBitmap;
                    }
                }
            } catch (IOException e) {
                // Error fetching image, try to recover

                /********* Cancel execution of this task. **********/
                cancel(true);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {

            if (loadingdailog.isShowing() && loadingdailog != null) {

                loadingdailog.dismiss();
                loadingdailog = null;
            }

            if (mBitmap != null) {
                showImg.setImageBitmap(mBitmap);

            }
        }
    }

}

upload class
public class Upload {
    protected MainActivity context;
    ProgressDialog dialog = null;
    int serverResponseCode = 0;
    String uploadFilePath = null;
    String uploadFileName = null;
    String msg = null;
    String upLoadServerUri = "http://fileuploadpath";

    public Upload(MainActivity context) {
        this.context = context;

    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            return 0;

        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);

                URL url = new URL(upLoadServerUri);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("photo", fileName);

                //      conn.setRequestProperty("session_id","13");

                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\""
                    + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

                try {

                    readStream(conn.getInputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (serverResponseCode == 200) {

                    context.runOnUiThread(new Runnable() {
                        public void run() {
                            context.dialog_upload.dismiss();
                            Toast.makeText(context, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                        }

                    });

                }
                fileInputStream.close();
            } catch (MalformedURLException ex) {
                // Toast.makeText(context, "File Upload Not Complete.",
                // Toast.LENGTH_SHORT).show();
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                // context.dialog.dismiss();
                e.printStackTrace();
                // Toast.makeText(context, "File Upload Not Complete.",
                // Toast.LENGTH_SHORT).show();
                Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
            }
            // context.dialog.dismiss();
            return serverResponseCode;

        }
    }

    private void readStream(InputStream in) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                Log.e("tag", line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="10dp"
    android:weightSum="1" >

    <ImageView
        android:id="@+id/showImg"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:contentDescription="bla bla" />

    <Button
        android:id="@+id/photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"

        android:text="Capture Image"
        android:textSize="26sp" />

    <Button
        android:id="@+id/upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"

        android:text="Upload Photo"
        android:textSize="26sp" />

</LinearLayout>

for image uri you should paste your file upload path
Comment: Is there any way to combine the 2 button into one?


Econometric models?

Question: I'm confused about econometrics models. Let's  say I used a daily stock market index  for 5 years, and I want to see how oil price affect the stock markets return , let's assume ( as a fact ) that oil price affect ALL the period negatively, and I use

VAR

ARIMA

ARDL, and

GARCH
for the same data.

What will each model tell me?
Will all of them reach a similar conclusion like oil price affect stock market return negatively?
How would the interpretation be different between each model?
Answer: You represent the data with a model to fulfill a certain task, e.g. to describe the data or to forecast or predict values which are not in the dataset. For some tasks some models are more appropriate than other. Therefore you should think of the problem you have and then you should look for a model/way/method to solve this problem. Generally if all of you models tell you the same, e.g. the oil price affects the stock market negatively, than you can be relatively sure that this is really the case.
If the models tell you different inferences you should think about the models:

Does on models detect for autocorrelation?
What about unit roots, structural changes and stationarity?
Are there unobserved effects or is there endogeneity?
etc.

Your models are always only a representation of your data. Some models are more appropriate for some data and some models are more appropriate for other data.

 - VAR
is a model for multiple time-series. If you only have a univariate time series VAR is not appropriate.

ARIMA

ARIMA and its variante seasonal ARIMA usually perform suboptimal when you data has multiple seasonalities or complex seasonality patterns, e.g. daily seasonalities with 365 periods a year.

ARDL

Might be a reasonable choice. You can use it even when your data is non-stationary.

GARCH

Might also be a reasonable choice- especially when there is volatility clustering.
Answer: I don't think that "econometric models" is anyhow a closed, or clearly defined set of models. Econometrics is basically a statistics applied to economy (plus some confusing mathematical notation), and there's lots of models used for such problems.
The answer is: yes and no. Yes, because given you have sufficient data and used your models correctly, then they all should be able to approximate the modeled  "truth". No, because the reason for having different models for modelling similar problems, is that they all focus on slightly different things, optimize different stuff, so won't give you exactly the same answers. Moreover, in many cases you simply can use all those models for same problem, e.g. VAR is multivariate, while ARIMA univariate. However if different models gave you very different answers, then I'd start wondering if there aren't any problems with the data.

Econometric models?


Prove that $1/n+1/(n+1)+\dots+(1/2n)>2/3$

Question:
Prove that $\displaystyle\frac{1}{n} + \frac{1}{n+1} + \dots + \frac{1}{2n}>\frac{2}{3}$

I tried to use mathematical induction, but I'm not able to prove that:
$$
\frac{1}{n+1} + \frac{1}{n+2} + \dots + \frac{1}{2n} + \frac{1}{2n+1} + \frac{1}{2n+2}>\frac{2}{3}.
$$
My method was:
Assumption:
$$\frac{1}{n} + \frac{1}{n+1} + \dots + \frac{1}{2n}>\frac{2}{3}$$
$$\frac{1}{n} + \frac{1}{n+1} + \frac{1}{n+2} + \dots + \frac{1}{2n} + \frac{1}{2n+1} + \frac{1}{2n+2}>\frac{2}{3} + \frac{1}{2n+1} + \frac{1}{2n+2}$$
$$\frac{1}{n+1} + \frac{1}{n+2} + \dots + \frac{1}{2n} + \frac{1}{2n+1} + \frac{1}{2n+2}>\frac{2}{3} + \frac{1}{2n+1} + \frac{1}{2n+2}-\frac{1}{n}$$
Now in order to prove the thesis I have to prove that
$$\frac{2}{3} + \frac{1}{2n+1} + \frac{1}{2n+2}-\frac{1}{n} > \frac{2}{3}$$
But it's a contradiction. Did I make a mistake somewhere? How can I solve this problem? I'd appreciate your help.
Comment: Hint: try to prove a stronger inequality by omitting the first term of the sum. As if by miracle, induction will work then! (note: this inequality will only hold for large $n$)
Comment: Also, to explicitly comment on your approach: there isn't a mistake there. It's just that sometimes naively using induction simply _won't work_. In such cases you either need to somehow strengthen the induction hypothesis (like I did), or take a completely different approach.
Comment: Actually, it should work for every natural n. I will try your idea, thank you a lot!
Answer: HINT
As suggested by Wojowu in the comment, sometimes induction works for a stronger hypothesis, in that case let try with
$$\displaystyle\frac{1}{n} + \frac{1}{n+1} + \dots + \frac{1}{2n}>\frac{2}{3}+\frac1{4n}>\frac23$$
Refer also to the related

Proof by induction, $1/2 + ... + n/2^n < 2$
If $x>0$ real number and $n>1$ integer, then $(1+x)^n>\frac{1}{2}n(n-1)x^2$
Show that $\left(1+\frac{1}{1^3}\right)\left(1+\frac{1}{2^3}\right)\left(1+\frac{1}{3^3}\right)...\left(1+\frac{1}{n^3}\right) < 3$
Answer: There is also a "non-inductive" way to show the inequality.
You may transform the sum into a Riemann-sum and then estimate this sum by an integral:
$$1/n+1/(n+1)+\dots+(1/2n) = \frac{1}{n}\left(\frac{1}{1+\frac{0}{n}} + \frac{1}{1+\frac{1}{n}} + \cdots + \frac{1}{1+\frac{n}{n}} \right) =\boxed{\sum_{k=0}^n \frac{1}{1+\frac{k}{n}} \cdot \frac{1}{n}}$$
Now, note that $f(x) = \frac{1}{1+x}$ is strictly decreasing $[0,1]$. So, you have

$\frac{1}{1+\frac{k}{n}} \cdot \frac{1}{n} = \int_{\frac{k}{n}}^{\frac{k+1}{n}} \frac{1}{1+\frac{k}{n}} \; dx > \int_{\frac{k}{n}}^{\frac{k+1}{n}} \frac{1}{1+x}\; dx$

This gives
$$\boxed{\sum_{k=0}^n \frac{1}{1+\frac{k}{n}} \cdot \frac{1}{n} > \int_0^1 \frac{1}{1+x}\; dx = \ln 2 > \frac{2}{3}}$$


How to add input into a text based program

Question: I created a text based RPG using Python. At the moment when you execute the program it brings you through an introduction and at the end of it i have the user decide to go 1.Left 2. Right 3. Middle. Each place has a unique item needed to complete the game, meaning if you go to the right it will see if you have a specific item appended to your bag. If you do not have it you will return to the main part to decide where to go again. That being said the middle is the main part where i want the user to be able to attack a dragon right away so they can lose, or if prepared with the necessary items appended, win! Now you do not have the option to attack, you just get to the dragon and win, so there is no lose. Any tips of how to incorporate an input throughout the game would be helpful. If more information is needed i can gladly share :).
I tried implementing an input before attacking the dragon but it got caught inside the loop so even when you obtained all the items you would get returned to the main dungeon. Here is a snippet code for the final dungeon for an idea.
def valid_input(prompt, option1, option2):
    while True:
        response = input(prompt).lower()
        if option1 in response:
            print_pause("You use the " + str(Weapon) + " against the dragon")
            print_pause("But it is not strong enough "
                        "to defeat the dragon, he uses Fire Breath"
                        " and, he incinerates you! ")
            print_pause("You lose!")
            play_again()
            break
        elif option2 in response:
            print_pause("Smart Choice! You head back to the main dungeon")
            dungeon_game()
            break
        else:
            print("Sorry, try again")
    return response

def middle_dungeon():
    print_pause("You go to the middle dungeon.")
    print_pause("After a few moments,"
                " you find yourself in front of a " + Dragon + "!")
    print_pause("This is why you need these magical powers.")

    if "MagicRune" in bag:
        print_pause("Luckily the Wizard trained you well, you now obtain "
                    " the power of the " + str(MagicRune) + "!")
        print_pause("You attack the dragon! ")
    if "MagicRune" not in bag:
        print_pause("You do not obtain the necessary magical powers.")
        print_pause("It looks like you need a scroll or more power!.")
        print_pause("You head back to the main dungeon.")
        dungeon_game()

    dragon_health = 100
    count = 0
    while dragon_health > 0:
        damage_by_player = random.randint(0, 60)
        print_pause(f"You hit the dragon and caused {damage_by_player} damage")
        dragon_health = dragon_health - damage_by_player
        print_pause(f"dragon health is now {dragon_health}")
        count = count + 1

    print_pause(f"You successfully defeated the dragon in {count} attempts, you win!")
    play_again()

def dungeon_game():
    passage = ''
    if 'started' not in Dungeon:
        display_intro()
        Dungeon.append('started')
        while passage != '1' and passage != '2' and passage != '3':
            passage = input("1. Left\n"
                            "2. Right\n"
                            "3. Middle\n")
            if passage == '1':
                left_dungeon()
            elif passage == '2':
                right_dungeon()
            elif passage == '3':
                middle_dungeon()
                dungeon_game()

So essentially this output will deny you until you go to the left dungeon and right dungeon, where you see MagicRune in bag: this will let you go to the dragon while loop and win the game.
Comment: What exactly is your question?
Comment: How would you implement an input that does not get caught in a loop? Do i create a function that contains the input and use a function call? i am stuck on being able to add a decision for the user playing.
Comment: You said you tried implementing an input "but it got caught inside the loop". I'm not sure exactly what that means. Can you post the code you tried and explain exactly how it failed?
Comment: yeah let edit the code. Ill show you the function i created and want to use in the existing code above.
Comment: So, the function above i do not actually call it because it wouldnt work, but its an idea of what i want to do. I want to have asked if they want to attack or not after the print statements in middle_dungeon. if they do initially without the appended items it would kill them and ask if they want to play again. Otherwise, when the items are properly appended have them able to use the item  which has a random.choice connected and then move through the rest of the middle_dungeon where they would attack the dragon. Not sure if that is even possible, or if there is an easier way to do so. Thanks!
Answer: You need to rearrange your code a bit. Here's how you could change your input function:
def valid_input(prompt, option1, option2):
    while True:
        response = input(prompt).lower()
        if option1 in response:
            return option1
        elif option2 in response:
            return option2
        else:
            print("Sorry, try again")

Now it returns the option the user chose and lets the calling code determine what to do with that information. This makes it actually reusable. You'd call it like this:
chosen = valid_input("Wanna attack the dragon?", "yes", "no")
if chosen == "yes":
    # do that stuff
else:
    # do other stuff

You also have another problem that you really need to fix: you are treating function calls like goto statements. This will cause you pain when you're trying to debug your code, and also causes hard-to-track bugs.
For example, you should not call play_again() to restart your code. Instead, set up your code structure so that you don't have to do that. E.g.
def dungeon_game():
  while True:
    # set up initial game state here, e.g.
    bag = ["sword", "potion"]
    # call main game logic function
    dungeon()
    # that function returned, so the game is over.
    want_to_play = input("play again?")
    if want_to_play == "no":
      # if we don't break, the While loop will start the game again
      break

def dungeon():
  # blah blah dragon attack
  if (whatever):
    print("You got killed. Game over.")
    return # goes back to dungeon_game()
  else:
    print("You won the fight")
  # code for the next thing that happens...

if __name__ == "__main__":
  dungeon_game()

Comment: Ohhhhhh, this makes much more sense. I really appreciate the input. I will see what i can do to change it around a little. Thank you for taking the time to help out :)
Comment: So i have a left_dungeon() right_dungeon() and middle_dungeon(). I'll share at the bottom my dungeon_game() to show you how i had it , because it goes through all three dungeons in order to append the items. So i am having trouble putting the lists. You're saying i should get rid of this structure all together, correct?
Comment: Your `dungeon_game` looks basically ok, except for that last line where you call `dungeon_game` from inside `dungeon_game`. In general, if you take the list of functions that were called to get to the line of code that's executing (e.g.  `dungeon_game` -> `middle_dungeon`), you should never call a function that's already in that list. If you're in `middle_dungeon` and you want to go back to `dungeon_game`, just `return` from `middle_dungeon`. If you're in `dungeon_game` and want to "start again", set up a loop that will do that. Etc.
Comment: Got it, and i have changed that. Now i just need to figure out how to get the game to reset when i use the `play_again()` function. - again truly appreciate your time and input.


Proof of Nielsen–Schreier Theorem using Covering Spaces

Question: I have two questions about the proof of Theorem VI.34 in these lecture notes. I have typed all that is relevant, below.

Theorem. (Nielsen-Schreier) Any subgroup of a finitely generated free group is
free.

Proof. Let $F$ be the free group on $n$ generators. Let $X$ be the wedge of $n$ circles, and let $b$ be the central vertex. Then, $\pi_1(X,b) \cong F$. Let $H$ be any subgroup of $F$. Then, by Theorem VI.32, there is a based covering $p: (\tilde X, \tilde b) \to (X,b)$ such that $p_\ast \pi_1(\tilde X, \tilde b) = H$. By Corollary VI.18, $p_\ast$ is injective, and so $\pi_1(\tilde X,\tilde b) \cong H$. Theorem VI.32 states that $\tilde X$ is a simplicial complex, and that $p$ is a simplicial map.  Since $p$ is a local homeomorphism, $\tilde X$ can contain only zero and one-dimensional simplices. Therefore, $\tilde X$ is a graph, and so by Theorem IV.11, its fundamental group is free.

How does $p$ being a local homeomorphism ensure that $\tilde X$ contains only zero and one-dimensional simplices? A rigorous proof would be preferred, but intuition (which can be translated to a proof) is also welcome.

I believe the author meant to write connected graph instead of just graph. We know that the fundamental group of connected graphs is free, I don't think this holds for graphs in general. If I am right, why is this graph connected?

Thank you!
Answer:
This is perhaps somewhat misguidingly put. The claim is true since the dimension of a simplex is a homeomorphism invariant, but this is non-trivial. Instead, I would refer to the proof of Theorem VI.32, where the simplicial structure explicitly constructed on $\tilde{X}$ has faces with at most as many vertices as a face in $X$ has vertices. Therefore, if $X$ has dimension $\le1$, so does $\tilde{X}$.

It is proven as part of Theorem VI.32 that $\tilde{X}$ is path-connected. However, this really does not matter. Fundamental groups only make sense relative to a basepoint and the fundamental group $\pi_1(\tilde{X},\tilde{b})$ only depends on the connected component of $\tilde{X}$ containing $\tilde{b}$, which is a connected graph even a priori. In particular, the fundamental group of any graph relative to any basepoint is free and this statement really has no more content than when you only state it for connected graphs.
Comment: The dimension of a simplicial complex $X$ can be characterized as the largest value of $n$ for which there exists an $x\in X$ such that the local homology group $H_n(X,X\setminus\{x\})$ is non-trivial. This notion is invariant under homeomorphism.
Comment: Why is the dimension of a simplex homeomorphism invariant?


How can i keep the give the subject of the email using postfix in crontab?

Question: Using MAILTO where can i give the subject of the email without using echo Test | mail -s Test firstname.lastname@example.com because if i use like this for sender to a one user it is okay if i want to add multiple user mails then for every script i have to add the mail id's which will be not good when comapare to MAILTO command.
Right now i have the script to send the mail to a user and send the STDOUT AND STDERR to logs.txt.
MAILTO="firstname.lastname@example.com,email@example.com,email@example.com"

25 07 * * * /usr/local/bin/curator --dry-run --config /home/itadmin/.curator/curator.yml /home/itadmin/.curator/snapshot.yml 2>&1 | /usr/bin/tee -a /home/itadmin/.curator/logs.txt

What i want is that in the MAILTO command is it possible to subject to all the users listed in that command like this MAILTO="email@example.com,email@example.com,firstname.lastname@example.com?subject=Mail Tested"
Thanks
Comment: You have asked a [number](https://serverfault.com/q/849033/37681)  of cron related [questions](https://serverfault.com/q/849282/37681) now and I just want to point out that Cron is only a simple scheduler. If you need more advanced functionality than just *run a specific command at a specific time* usually it is better to instead encode that logic in a script and just let cron call that script. Then you can do useful stuff like for instance catching the exit code of a command and send different messages based on succes or failure, send log files as attachments instead of body text etc.
Answer: MAILTO in crontab is not a command but an environment variable.
For example, in Cron by Paul Vixie, mailto variable is set to NULL if it's empty and to username, if not present. Then, the From:, To: and Subject: are hard-coded to the program in do_command.c:
358     /* if we are supposed to be mailing, MAILTO will
359      * be non-NULL.  only in this case should we set
360      * up the mail command and subjects and stuff...
361      */
362
363     if (mailto) {

375         fprintf(mail, "From: root (Cron Daemon)\n");
376         fprintf(mail, "To: %s\n", mailto);
377         fprintf(mail, "Subject: Cron <%s@%s> %s\n",
378             usernm, first_word(hostname, "."),
379             e->cmd);

Therefore, you can't use MAILTO for changing the Subject. Instead, you could pipe the output to an external command sending mail or use an intermediate file and send its contents.


Clear share intent data while whatsapp sharing in android

Question: I have a Relative layout and Textview on it. Then I convert that relative layout to bitmap image and save in directory.

The problem is when I am sharing the image, in most of app, I found correct image but in case of whatsapp when I am sharing through whatsapp the preview of sharing image is showing me old one until I close the app. Why it's not getting update and when I share the image on whatsapp, preview is old one and the image goes right one. This works fine in FB, Gmail etc...

This is the below code for converting and saving converted bitmap image in file system (directory)
This is for creating Direcory:
File dir = null;
String directorySubPath = "Android/data/com.domainname.appname/sharedResource/";
String imageNameForSave = "/qqq.png";

if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {
            Toast.makeText(this, "Your device doesn't have external storage.", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        {
            Log.d("SD", "YES", null);
            dir = new File(Environment.getExternalStorageDirectory()+File.separator+directorySubPath);
            if (!dir.exists()){
                dir.mkdirs();
            }
            else {
                Log.d("Q-Design:", "Already created", null);
            }
        }

This is for code convert layout to bitmap image & save.
rLayout.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(rLayout.getDrawingCache());
FileOutputStream out = new FileOutputStream(dir+imageNameForSave);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
rLayout.setDrawingCacheEnabled(false);

This is for SHARING that image via Intent:
Uri uri = Uri.parse("file:///" + dir + imageNameForSave);

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test Mail");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Data Shared with you...");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share via:"));

Answer: Use a dynamic name in String imageNameForSave
Ex. String imageNameForSave = "/qqq" + mydate + ext;


How to count the number of line segments in a knotwork?

Question: Question: Given an embedded planar graph $G$, how can you compute the number of segments in the corresponding knotwork? Does the number of segments depend on choice of embedding?
Background
Any embedding of a planar graph corresponds to a particular knotwork like so; each edge corresponds to a crossing of two strands; each strand alternates crossing over and under; alternates which endpoint of the edge it is pivoting around, and alternates pivoting clockwise or anticlockwise:

I have already worked out how to count the number of distinct strands (components $c$) of the knotwork; it's related to the Tutte polynomial of the graph via $|T_G(-1,-1)| = 2^{c-1}$ and is therefore incidentally independent of choice of graph embedding.
I am not sure how to compute the number of segments in a similar way: if we imagine knotworks drawn with unbroken lines, then topologically a knotwork is a collection of some number $k$ of line segments, whose endpoints have been glued together into groups of four ("four-way intersections"). I'm trying to find a formula for computing that number $k$ from the graph.
It seems that in simple cases, this number is equal to twice the number of edges. (four segments meet at each edge in the graph; if these were all distinct, there would be $4|E|$ strands total, but because each segment has two endpoints, we are counting each segment twice when we iterate over all the edges which serve as endpoints for these segments. Therefore there are $2|E|$ strands, as long as all of the endpoints are now distinct.)
But I am not sure whether this holds for even more complicated graphs, or how to show it. For example, graphs with leaf vertices (which cause the knotwork to have line segments whose endpoints are glued to themselves), many parallel edges, or self-loops, or some combination thereof.
Comment: @EtackSxchange It corresponds to the dodecahedral graph! 30 edges * 2 = 60 segments.
Comment: What about the number of line segments in the knotwork of your profile picture?
Answer: Your reasoning works no matter parallel edges and self-loops.
This is generally known in graph theory under the formula:
$$\sum_{v\in V} deg(v) = 2|E|$$
This is because each edge is counted in exactly two degrees (one for each extremity). This formula is correct even when there are parallel edges and self-loops (remember that a self-loops counts for $2$ in the degree of a vertex).
Here, you can apply this argument like this: You have one intersection for each edge, so the graph formed by your segments has $|E|$ vertices, and it is four regular (4 segments are incident at each vertex). So you have $\frac{4|E|}{2} = 2|E|$ segments.
Comment: Ah, I see! because the knotwork is 4-regular, there are 4|E| places in the knotwork where segments end. each segment has two endpoints, which means that no matter how exactly they're hooked up together and arranged, you'll count 2|E| segments in total. This also means that it's independent of how the graph is embedded. Thanks!


Adding CSRF to formtoemailpro.php

Question: Following the post at: https://codeutopia.net/blog/2008/10/16/how-to-csrf-protect-all-your-forms/
I am trying and failing to add the code to formtoemailpro.php https://formtoemail.com/developer_pricing.php
I add the key generator to the form page:
//Generate a key, print a form:
$key = sha1(microtime());
$_SESSION['csrf'] = $key;

And the hidden field:
<input type="hidden" name="csrf" value="<?php echo $key; ?>" />

But I cannot add  the following to formtoemailpro.php and have it work. I have put the top half at the top of the form and the '}' at the bottom as well as adding the 'if(!isset' expession along with the other similar elements of the processing part of the form and I fail.
if($_SERVER['REQUEST_METHOD'] == 'POST')
            //Here we parse the form
if(!isset($_SESSION['csrf']) || $_SESSION['csrf'] !== $_POST['csrf'])
 throw new RuntimeException('CSRF attack');
 //Do the rest of the processing here
}

I am sorry for my ignorance, please can anyone help me?
Thank you.
Comment: display value of `$_POST['csrf']` and value of `$_SESSION['csrf']` before `if` and you understand where is the problem
Answer: If I understated your problem, this is what you need to do:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //Here we parse the form
}

if(!isset($_SESSION['csrf']) || $_SESSION['csrf'] !== $_POST['csrf']){
    throw new RuntimeException('CSRF attack');
 //Do the rest of the processing here
}

Make sure you place the "{", "}", on code blocks.
Also, make sure $_SESSION['csrf'] = $key; is called before any output. (Echo, print, etc...). Look at this Q&A about sessions.
Comment: Thank you. My problem is adding the code to the form processor. I canot really post the script here as it is a paid for thing and I don't want to make it available for free, however, it strats with:  Sorry - I guess that is not much help
Comment: @user2135841 Try and change "error_reporting(E_ALL ^ E_NOTICE);" to error_reporting(false); as you will see in the link, you should add session_start(); and all of the $_session[] calls must be before any file output. (btw - Please don't forget to upvote and select the answer as selected if all goes well :)
Comment: Thank you. I am afraid I am not technicaly up to this.
Comment: Happy to help @user2135841, and welcome to Stack Overflow. If this answer solved your issue, please mark it as accepted and upvote. Thanks and good luck!

Adding CSRF to formtoemailpro.php


Pegar o último registro por data de um historico de lançamentos em mysql

Question: Preciso pegar a última situação de uma doação em determinado período.
Preciso agrupar por doação e por situação.
Somar por situação e ordenar doações por situação, pegando apenas a última.
<code>Tabela LoteRetornoDoacao
Campos: id,dtBaixa,situacaoDoacao,vrTotalLote,num

Tablela Doacao
Campos: id, situacaoDoacao(atual),vrDoacao,idOperadorResponsavel

Tabela Operador
Campos:id, nome,codigo

Tabela DoacaoLoteRetorno
Campos:id, idDoacao,idLoteRetorno

Tabela LoteDoacao
Campos:id, idPartDoador

 Tabela Participante(doador)
 Campos:id,nome,cod
</code>
Preciso pegar a última situação da doação em um determinado período.
Já tentei isso e não funcionou, pega o valor máximo da data, mas mistura os outros campos:
<code>    SELECT DISTINCT
(CASE
WHEN lrd.situacaoDoacao=0 THEN "Aberto"
WHEN lrd.situacaoDoacao=1 THEN "Recebido"
WHEN lrd.situacaoDoacao=2 THEN "Devolvido"
WHEN lrd.situacaoDoacao=3 THEN "Cancelado"
WHEN lrd.situacaoDoacao=4 THEN "Confirmado"
WHEN lrd.situacaoDoacao=5 THEN "Coleta"
ELSE "n" END)AS situacaoLoteRetorno,
lrd.situacaoDoacao,lrd.id,d.situacaoDoacao AS situacaoAtual,d.vr,partDoador.nome,d.codbarras
FROM Doacao d
LEFT JOIN DoacaoLoteRetorno dlr ON dlr.idDoacao=d.id
LEFT JOIN LoteRectoDoacao lrd ON lrd.id=dlr.idLoteRetornoDoacao
LEFT JOIN LoteDoacao ld ON d.idLoteDoacao=ld.id
LEFT JOIN Participante partDoador ON partDoador.id=ld.idPartDoador
GROUP BY dlr.idDoacao HAVING MAX(lrd.dtbaixa) ORDER BY lrd.dtBaixa DESC;
</code>
Segue modelo dos relatórios que preciso fazer.

Nem essa simples consulta retorno correto.
<code>   SELECT  DISTINCT lrd.dtBaixa,dlr.idDoacao FROM LoteRetornoDoacao lrd
LEFT JOIN DoacaoLoteRetorno dlr ON lrd.id=dlr.idLoteRetornoDoacao
GROUP BY idDoacao ORDER BY lrd.dtBaixa DESC;
</code>
O que tem de errado? Acho que é a mania de achar que será filtrado como no excel.... srsr
Answer: Galera vou deixar aqui para documentar o fórum.
Não vou deixar a consulta inteira,porque o objetivo é pegar um registro atendendo o quesito de maior data.
Logo a primeira coisa a fazer é uma query ordenando por data DESC.
Depois ao agrupar, o mysql, automaticamente pega o primeiro registro.
Exemplo com a tabela LoteColetaDoacao
<code>   SELECT a.* FROM (SELECT lcd.*,dlc.idDoacao FROM LoteColetaDoacao lcd
LEFT JOIN DoacaoLoteColeta dlc ON dlc.idLoteColetaDoacao=lcd.id
ORDER BY lcd.dtColeta DESC)a
GROUP BY a.idDoacao;
</code>
Espero ter contribuído.


Cauchy sequences of compactly supported functions

Question: We have the three standard norms $\left\Vert\right\Vert_1$, $\left\Vert\right\Vert_2$, $\left\Vert\right\Vert_\infty$ defined on the space of compactly supported functions $C_0(\Bbb N,\Bbb R)$, $f: \Bbb N \rightarrow \Bbb R$.
For each pair of norms, I must to find sequences which are cauchy with respect to one of these norms but not the other. For instance, in considering the $\left\Vert\right\Vert_1$ and $\left\Vert\right\Vert_2$ norms, I must find a sequence of functions that is cauchy for $\left\Vert\right\Vert_1$ but not $\left\Vert\right\Vert_2$, for the $\left\Vert\right\Vert_1$ and $\left\Vert\right\Vert_\infty$ norms I must to find a sequence of functions that is cauchy for $\left\Vert\right\Vert_1$ but not $\left\Vert\right\Vert_\infty$, and for the $\left\Vert\right\Vert_2$ and $\left\Vert\right\Vert_\infty$ norms I must find a sequence of functions that is cauchy for $\left\Vert\right\Vert_2$ but not $\left\Vert\right\Vert_\infty$ or vice versa.
I have attempted many approaches but I am having difficulty building an intuition for the behavior of these norms in the context of sequences of functions. Any guidance would be much appreciated.
Answer: Note that $\Vert \cdot \Vert_\infty \leqslant \Vert \cdot \Vert _1$ and $\Vert \cdot \Vert_\infty \leqslant \sqrt{\Vert \cdot \Vert _2}$ and when $\Vert f \Vert_1 <1$, then $\Vert f \Vert_2 \leqslant \Vert f \Vert_1$. So any Cauchy sequence for $\Vert \cdot \Vert _1$ or for $\Vert \cdot \Vert _2$ will be a Cauchy sequence for $\Vert \cdot \Vert _\infty$, and any Cauchy sequence for $\Vert \cdot \Vert _1$ will be a Cauchy sequence for $\Vert \cdot \Vert _2$
Check the inequalities and this will suppress many cases for which there is a Cauchy sequence for a norm but not for another.
For the other cases, basically use the sequences of sequences $$(f_N)_{N\in \mathbb{N}} \text{ with } f_N=(1,1/2,\cdots,1/N,0,0,0,\cdots)$$ and $$(g_N)_{N\in \mathbb{N}} \text{ with } g_N=(1,1/\sqrt{2},\cdots,1/\sqrt{N},0,0,0,\cdots).$$
Answer: Hint: Let $E_k=\{1,\dots ,k\}$. Then let $f_{k}(n):=\frac{1}{n}1_E(n)$. So for example, $f_1(1)=1$, $f_1(n)=0$ for $n>1$. Then $f_2(1)=1$, $f_2(2)=\frac{1}{2}$, $f_2(n)=0$ for $n>2$. Then $f_3(1)=1$, $f_3(2)=\frac{1}{2}$, $f_3(3)=\frac{1}{3}$, $f_3(n)=0$ for $n>3$. And so on. Now let $f(n):=\frac{1}{n}$. What types of convergences are happening?


How the following Inverse Fourier Transform is obtained.

Question: In one of the numerical, I came across the following power spectral density (PSD):
$S_{Y}(f) = 2; |f| < 2$ and $S_{Y}(f) = 0; \text{otherwise}$.
Its autocorrelation is given as $R_{Y}(\tau) = 8 \text{Sinc}(4\tau)$ ---(1)
I know that autocorrelation is inverse Fourier transform of PSD, but I am not getting how the autocorrelation in equation (1) is obtained.
Any help in this regard will be highly appreciated.
Comment: Did you try computing the integral directly?
Comment: Thank u so much sir for ur reply... I tried upto following step: $R_{Y} (\tau) = \int_{-\infty}^{+\infty}S_{Y}(f) e^{j2\pi f \tau} \text{d}f = \int_{-\infty}^{+\infty}2 e^{j2\pi f \tau} \text{d}f $. I am not getting what limits should I put now in place of $-\infty$ and $+ \infty$.
Comment: I got the answer when I substituted the limits as -2 to +2 . But I am still not getting why the limits should be from -2 to +2. Basically my confusion is due to |f| < 2.
Comment: $\vert f\vert$ is absolute value of $f$ , e.g. $|-1|=1$,  $|f|<2$ is same as $−2<f<2$
Answer: Because
$$S_{Y}(f) =\begin{cases}
    2&|f|<2\\
    0&f\le -2 \:or\: f \ge 2
\end{cases}$$
we have
$$R_{Y} (\tau) = \int_{-\infty}^{+\infty}S_{Y}(f) e^{j2\pi f \tau} \text{d}f = \int_{-2}^{2}2 e^{j2\pi f \tau} \text{d}f=\left[\frac{e^{j2\pi f \tau}}{j\pi\tau}\right]^2_{-2}\\=\frac{e^{j4\pi\tau}-e^{-j4\pi\tau}}{j\pi\tau}=\frac{2\sin4\pi\tau}{\pi\tau}=\frac{8\sin4\pi\tau}{4\pi\tau}=8\;\text{sinc}\:(4\tau)$$
Comment: Thanks a lot sir.... I had also got the answer, but not getting why we substitute the limit -2 to +2, basically getting doubt because of |f| < 2.
Comment: Because $S_{Y}(f)$ is nonzero only when $-2<f<2$, so the integral outside this region is always zero...
Comment: Yes ... That I also know...My basic doubt is how we are considering $|f| <2$ as $-2 < f < 2$....
Comment: What is your doubt? Isn't $|f|<2$ the same as $-2<f<2$, or are you thinking of $f$ as a complex number?
Comment: No ...I am not considering $f$ as complex. But I am not getting how $|f|<2$ is same as $-2 < f < 2$. Any way will ask new question regarding this doubt...


Como Abrir outro Form dando double click na celula

Question: Tenho uma tabela chamada torneios que mostra o tipo de jogo, o nome do torneio e a data.
Eu quero que ao fazer double click na célula do tipo de jogo abrisse as equipas desse tipo de jogo.
private void Dgv1_CellMouseDoubleClick(Object sender, DataGridViewCellMouseEventArgs e)
{
    EquipasLOL Tela = new EquipasLOL();
    Tela.Show();
    this.Hide();
}

Comment: Olá @Jose. Edita a sua questão e coloque o seu código, caso contrário será difícil ajudar sem termos uma base!
Answer: Utilize o evento MouseDoubleClick. Verifique se é a coluna do "Tipo de Jogo" utilizando o If. Passe como parâmetro o Id do "Tipo de Jogo" e utilize-o na tela EquipasLOL.
private void Dgv1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if(Dgv1.CurrentCell.ColumnIndex == Dgv1.Columns["NomeDaColunaDoTipoDeJogo"].Index)
    {
        EquipasLOL Tela = new EquipasLOL(Dgv1.SelectedRows[0].Cells["ColunaComOIdDoTipoDeJogo"].Value);
        Tela.Show();
        this.Hide();
    }
}

Comment: Obrigado, consegui resolver o meu problema!


Value of type List(Of Long) cannot be converted to List(Of ListItem)

Question: I am filling data from removeActiveService (list of listItem) into a new list listRemove. However listRemove is turning into a list of Long.
Dim listRemove = removeActiveService.Select(Function(item) item.Text.Replace(serviceRemove, "") And item.Text.Split("-"c)(0).Trim And item.Value.Split("-"c)(1).Trim).ToList()

If I change it to Dim listRemove As List(Of ListItem), it results in the error

Value of type List(Of Long) cannot be converted to List(Of ListItem)

I need to perform replace and split on the text and value (see my code). What is the correct syntax here so that it can be a List(Of ListItem)?

EDIT

Starting with checkboxlist items in removeActiveService

Copy that into a brand new list of items called listRemove.

I need to perform these on the TEXT of the list items in listRemove

item.Text.Replace(serviceRemove, "")
item.Text.Split("-"c)(0).Trim

And I need to perform this on the VALUE of the list items in listRemove

item.Value.Split("-"c)(1).Trim
Comment: Why would you be using `And` there? That is a Boolean or bitwise operator. Do you want to perform a Boolean or bitwise operation there? I think not. Please explain in detail what it is that you want to do with an item, including an example or two of potential inputs and expected outputs.
Comment: @user18387401 For each item, I need to replace the text, split the text and grab the left half, and split the value and grab the right half. (See code). I was using And to combine these functions. How can I do it instead of And?
Comment: Telling us to "see code" isn't helpful when the code makes no sense. No one should have to read the comments to understand the question. Edit your question and provide the FULL and CLEAR explanation that you should have in the first place, including the examples I asked for. I can see that you want to perform three separate operations but there's little indication of what you want to do with those three results, because using `And` makes no sense.
Answer: If you expect to output a List(Of ListItem) then you need to create ListItem objects somewhere, which you're not doing now. You're performing operations on the input data but you're not doing anything useful with the results. And doesn't do anything that could be considered useful there. If you expect to output a list of ListItem objects containing the results of those operations then you actually have to create ListItem objects containing the result of those operations. As far as I can tell, this would be the way to go:
Dim listRemove = removeActiveService.Select(Function(item) New ListItem With
                                                           {
                                                               .Text = item.Text.Replace(serviceRemove, "").Split("-"c)(0).Trim(),
                                                               .Value = item.Value.Split("-"c)(1).Trim()
                                                           }).
                                     ToList()


How to convert an array of decimal values in Matlab?

Question: I want to change [1,2,3,4] into [1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1]  in matlab, what is a way to achieve this?
Given:
<code>[1,2,3,4]
</code>
I need:
<code>[1 0 0 0;0 1 0 0;0 0 1 0;0 0 0 1]
</code>
Comment: This is a bit ambiguous. The easy answer is [`eye(4)`](https://www.mathworks.com/help/matlab/ref/eye.html). You need to fill in more detail about what you're looking for and what you've tried so far.
Comment: @BenD it's not really binary, it look like one-hot encoding.
Comment: @ w404336713 craigim is right that you'll need more detail. For example, should each result have a digit count equal to the length of the original array or equal to the size of the largest entry?

i.e. given [1,5] can we assume you want [ 10000, 00001 ] ?
Comment: See https://stackoverflow.com/questions/23078287/create-a-zero-filled-2d-array-with-ones-at-positions-indexed-by-a-vector and https://stackoverflow.com/questions/38947948/how-can-i-hot-one-encode-in-matlab
Comment: @BenD how's this related to binary? I'd agree with you on the `1` and `2`, but `3` is definitely `1100`, not `0010`
Comment: Those aren't binary values...
Comment: Ah, you're right I spoke to soon.
Comment: I'm sorry  what if a =[1,2,4,4,2,4,5,7.....] how to change it
Answer: <code>out=zeros(size(input,1),max(input));
for i=1:size(input,1)
  out(i,input(i))=1;
end
</code>
Use this with the assumption that input is a column vector.


In Pascal's triangle without the $1$s, what is the sum of squares of reciprocals?

Question: Consider Pascal's triangle without the $1$s.

Let $S$ be the sum of squares of reciprocals.
$$S=\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{3^2}+\frac{1}{4^2}+\frac{1}{6^2}+\frac{1}{4^2}+\frac{1}{5^2}+\cdots$$

Does $S$ have a closed form?

Wolfram does not evaluate $S$.
Significance of $S$
$S$ is a single non-trivial number representing all of Pascal's triangle without the $1$s. (The sum of unsquared reciprocals diverges because the harmonic series diverges.)
Why I suspect $S$ has a closed form
I suspect $S$ has a closed form, because many other infinite sums of reciprocals in Pascal's triangle have closed forms. Examples:

$\sum\limits_{k=1}^\infty\binom{k+2}{k}^{-2}=\frac43\pi^2-13$ (source)
$\sum\limits_{k=1}^\infty\binom{k+3}{k}^{-2}=9\pi^2-\frac{355}{4}$ (source)
$\sum\limits_{k=0}^\infty\binom{2k}{k}^{-1}=\frac43+\frac{2\pi\sqrt3}{27}$ (source).
In Pascal's triangle without the outer two layers, the sum of (unsquared) reciprocals is $3/2$, as I show below.

Showing that $1<S<2$
Consider the color-coded Pascal's triangle below. (The green and orange numbers extend below the diagram infinitely).

Let $T$ be the sum of reciprocals of the blue and green numbers. I found that $f(n)=\sum\limits_{k=2}^\infty\binom{n+k}{k}^{-1}=\frac{2}{n^2-1}$ for $n>1$ (source). Then $T=\sum\limits_{n=2}^\infty f(n)=\sum\limits_{n=2}^\infty \frac{2}{n^2-1}=\frac32$ by telescoping.
So the sum of reciprocals of the green numbers is $\frac32-\left(\frac16+\frac{2}{10}+\frac{2}{15}+\frac{1}{20}+\frac{2}{21}+\frac{2}{35}\right)=\frac{67}{84}$.
So the sum of squares of reciprocals of the green numbers is between $0$ and $\left(\frac{67}{84}\right)^2\approx 0.6361961451$.
Using the fact that $\sum\limits_{k=2}^\infty\frac{1}{k^2}=\frac{\pi^2}{6}-1$, the sum of squares of reciprocals of the orange and blue numbers is $2\left(\frac{\pi^2}{6}-1\right)-\left(\frac12\right)^2+\left(\frac{1}{6^2}+\frac{2}{10^2}+\frac{2}{15^2}+\frac{1}{20^2}+\frac{2}{21^2}+\frac{2}{35^2}\right)\approx 1.105202601$.
Therefore $1<S<2$.
Edit
In the comments, @Tyma Gaidash shows that $S=\frac23-\frac{2\pi}{9\sqrt3}+\int_0^1\frac{t(t^2-3t+1)\ln(t(1-t))}{(t^2-t+1)^3}dt\approx 1.1146$. I have asked about a closed form for the integral here.
Comment: We use [hypergeometric $_3 F_2$'s integral representation](https://functions.wolfram.com/HypergeometricFunctions/Hypergeometric3F2/07/03/). Summing over the first sum gives $S=\sum\limits_{n=1}^\infty\frac{_3F_2(1,2,2;n+2,n+2;1)}{(n+1)^2}$ and applying the integral representation experimentally gives $S=\frac23-\frac{2\pi}{9\sqrt3}+\int_0^1\frac{t(t^2-3t+1)\ln(t(1-t))}{(t^2-t+1)^3}dt\approx 1.1146$
Comment: Naturally one has to wonder whether the generalized variant also has a closed form:
$$S(n)=\frac{1}{2^n}+\frac{1}{3^n}+\frac{1}{3^n}+\frac{1}{4^n}+\frac{1}{6^n}+\frac{1}{4^n}+\frac{1}{5^n}+\cdots$$
Perhaps if an integral is found then it is easily doable.
Comment: Using the @ТymaGaidash's work alongside [this](https://math.stackexchange.com/a/4828985/515527) result, your sum can be written in terms of the [Clausen function](https://en.wikipedia.org/wiki/Clausen_function) as:

$$S=\frac13+\frac{4}{3\sqrt 3}\operatorname{Cl}_2\left(\frac{\pi}{3}\right)$$
Comment: $S=\sum_{k=1}^\infty\sum_{n>k}{n\choose k}^{-2}$. Perhaps it's possible to find a closed form for the inner sums first? Using partial fraction decomposition they can be written as a $\mathbb{Q}$-linear combination of sums of the form $\sum_{n>k}\frac1{(n-m)(n-j)}$, where $0\le m,j\le k-1$ are integers.
Comment: I have asked about the [general case](https://math.stackexchange.com/q/4829462/398708).
Answer: From the comments:
@Mastrem notes that $S=\sum_{k=1}^\infty\sum_{n>k}{n\choose k}^{-2}$.
@Tyma Gaidash notes that, using hypergeometric ${}_3F_2$'s integral representation, summing over the first sum gives $S=\sum\limits_{n=1}^\infty\frac{_3F_2(1,2,2;n+2,n+2;1)}{(n+1)^2}$. Applying the integral representation experimentally gives $S=\frac23-\frac{2\pi}{9\sqrt3}+\int_0^1\frac{t(t^2-3t+1)\ln(t(1-t))}{(t^2-t+1)^3}\mathrm dt$ (which is supported by numerical evidence using A024746).
@Zacky uses a result to yield $S=\frac13+\frac{4}{3\sqrt 3}\operatorname{Cl}_2\left(\frac{\pi}{3}\right)$ where $\operatorname{Cl}_2(x)$ is the Clausen function.
Edit:
Thanks to @Tyma Gaidash's comment to this answer, we have:
$$S=\frac13+\frac{4}{3\sqrt 3}G\approx 1.11463574623$$
where $G$ is Gieseking's Constant.
Comment: $\text{Cl}_2\left(\frac\pi3\right)=G$ which is [Gieseking's constant](https://mathworld.wolfram.com/GiesekingsConstant.html)


Partial differential equation. 1D wave Initial Boundary Value Problem.

Question: $$u_{tt} - u_{xx} = 0  \text{ for }0 \leq x \leq 1$$
$$u(x,0) = f(x) $$
$$u_t(x,0) = 0$$
$$u_x(0,t) = 0$$
$$u_x(1,t) = 0$$
$$f(x) = 3x \text{ when } 0 \leq x \leq 1/3$$    and
$$ 3/2  (1-x) \text{ when } 1/3 \leq x \leq 1 $$
Find $u(x,t)$.
I found that $u(x,t) = f(x)$ when $x<t$ and $0$ when $x>t$.
I have doubts that it is the correct answer.
Answer: It is not trivial to solve this equation. The easiest way I could think of is to use a series-Ansatz:
$$
u(x,t)=a_0(t)+\sum_{i=1}^\infty\cos(i\pi x)\cdot a_i(t)
$$
Here the cosine functions are chosen because they already fullfill the homogenous Nemann boundary conditions. Plugging it in the differential equation yields:
$$
a_0''(t)=0\\
a_i''(t)+(i\pi)^2a_i(t)=0
$$
Likewise we use the initial conditions
$$
\begin{cases}u(x,0)=a_0(0)+\sum_{i=1}^\infty\cos(i\pi x)\cdot a_i(0)=f(x)\\
u_t(x,0)=a_0'(0)+\sum_{i=1}^\infty\cos(i\pi x)\cdot a_i'(0)=0\end{cases}\\
\Rightarrow\\
\begin{cases}\int_0^1 \left[a_0(0)+\sum_{i=1}^\infty\cos(i\pi x)\cdot a_i(0)\right]\cdot \cos(j\pi x)dx=\int_0^1f(x)\cdot \cos(j\pi x)dx\quad  \forall j=0,1,2,3\ldots\\
a_j'(0)=0\quad\forall j=0,1,2,3\ldots\end{cases}\\
\Rightarrow\\
\begin{cases}a_0(0)=\int_0^1f(x)dx=\frac{1}{2}\\
\frac{a_j(0)}{2}=\frac{3}{2}\frac{3\cos(\tfrac{j\pi}{3})-2+(-1)^{1+j}}{j^2\pi^2}\quad \forall j=1,2,3\ldots\\
a_j'(0)=0\quad\forall j\in\mathbb{N}\end{cases}\\
$$
Finally we can put it all together and end up with the series represenation of the solution:
$$
u(x,t)=\frac{1}{2}+\sum_{i=1}^\infty3\cdot\frac{3\cos(\tfrac{i\pi}{3})-2+(-1)^{1+i}}{i^2\pi^2}\cos(i\pi x)\cos(i\pi t)
$$
The below plot shows the behaviour of the function and you can see that it bounces back and forth from the walls (as expected) with a periodicity of $2$.


Oracle DB insert query fixing

Question: I have an oracle query that I'm attempting to correct - it is throwing  this error because, I'm guessing, the ids that are referenced in it don't exist in a QA db, but do exist in Production:
Error executing INSERT statement. ORA-02291: integrity constraint (EFAPP.REFMETRIC603) violated - parent key not found

and my broken query is this one:
insert into IDMAPPING (metricid, storeid) values (50441, 18198)
    WHERE EXISTS (SELECT * FROM METRIC WHERE METRICTID = 50441) and WHERE EXISTS (SELECT * FROM STORE WHERE  STOREID = 18198);

Basically, what I'm trying to do is to wrap insert statement into something that would allow for the insert when the ids actually exist.
Would love some help on fixing this query.
Comment: See https://stackoverflow.com/a/41850009/2055998
Comment: @PM77-1 Thanks so much! very much appreciate  the good pointer.
Answer: Use INSERT ... SELECT and CROSS JOIN the tables:
INSERT INTO IDMAPPING (metricid, storeid)
SELECT m.metrictid, s.storeid
FROM   METRIC m
       CROSS JOIN store s
WHERE  m.metrictid = 50441
AND    s.storeid = 18198;

Or just use PL/SQL and catch the error:
DECLARE
  parent_key_not_found EXCEPTION;
  PRAGMA EXCEPTION_INIT(parent_key_not_found, -2291);
BEGIN
  INSERT INTO idmapping (metricid, storeid) VALUES (50441, 18198);
EXCEPTION
  WHEN parent_key_not_found THEN
    -- Ignore the exception
    NULL;
END;
/

db<>fiddle here

Oracle DB insert query fixing


Problem with line-height in Webkit (partially unclickable links)

Question: Here is HTML code:

    A
    B
    C

Here is CSS code:
.row {
    line-height:0;}
.item {
    line-height:1.2;}
.row .under {
    display:inline-block;
    width:100%;}

Here is jsfiddle link with example: http://jsfiddle.net/SRhK9/12/
Problem is that in webkit links are partially unclickable (from the bottom side to the middle of the link).
If I`ll remove span.under problem will dissapear, but I need this element to align blocks with class .item using text-align:justify, like this http://jsfiddle.net/SRhK9/18/
Any ideas on how to workaround this?
Answer: Found an answer. If you will specify position:relative to the .item it will fix the problem. Here is demo: http://jsfiddle.net/SRhK9/68/


How to connect mysql with Java using hibernate? Exception:No Persistence provider for EntityManager named org.hibernate.tutorial_jpa

Question: At the beginning I wanted to write a simple program to connect in Java to MySQL using hibernate. Program don't find a persistence provider for EntityManager. Unfortunately, there are still some exceptions. At this point, they are like this:
Exceptions at this moment:

"C:\Program Files\Java\jdk-17.0.1\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2021.2.2\lib\idea_rt.jar=53702:D:\IntelliJ IDEA Community Edition 2021.2.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\User\.m2\repository\org\hibernate\hibernate-core\5.4.1.Final\hibernate-core-5.4.1.Final.jar;C:\Users\User\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\User\.m2\repository\org\javassist\javassist\3.24.0-GA\javassist-3.24.0-GA.jar;C:\Users\User\.m2\repository\net\bytebuddy\byte-buddy\1.9.5\byte-buddy-1.9.5.jar;C:\Users\User\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\User\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.1.1.Final\jboss-transaction-api_1.2_spec-1.1.1.Final.jar;C:\Users\User\.m2\repository\org\jboss\jandex\2.0.5.Final\jandex-2.0.5.Final.jar;C:\Users\User\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\User\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\User\.m2\repository\org\dom4j\dom4j\2.1.1\dom4j-2.1.1.jar;C:\Users\User\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.0.Final\hibernate-commons-annotations-5.1.0.Final.jar;C:\Users\User\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\User\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.1\jaxb-runtime-2.3.1.jar;C:\Users\User\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\User\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.7\istack-commons-runtime-3.0.7.jar;C:\Users\User\.m2\repository\org\jvnet\staxex\stax-ex\1.8\stax-ex-1.8.jar;C:\Users\User\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.15\FastInfoset-1.2.15.jar;C:\Users\User\.m2\repository\org\hibernate\hibernate-entitymanager\5.4.1.Final\hibernate-entitymanager-5.4.1.Final.jar;C:\Users\User\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-controls\17-ea+11\javafx-controls-17-ea+11.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-graphics\17-ea+11\javafx-graphics-17-ea+11.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-base\17-ea+11\javafx-base-17-ea+11.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-fxml\17-ea+11\javafx-fxml-17-ea+11.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-web\17-ea+11\javafx-web-17-ea+11.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-media\17-ea+11\javafx-media-17-ea+11.jar;C:\Users\User\.m2\repository\org\springframework\spring-beans\3.2.0.RELEASE\spring-beans-3.2.0.RELEASE.jar;C:\Users\User\.m2\repository\org\springframework\spring-core\3.2.0.RELEASE\spring-core-3.2.0.RELEASE.jar;C:\Users\User\.m2\repository\commons-logging\commons-logging\1.1.1\commons-logging-1.1.1.jar -p C:\Users\User\.m2\repository\org\openjfx\javafx-media\17-ea+11\javafx-media-17-ea+11-win.jar;C:\Users\User\.m2\repository\org\kordamp\ikonli\ikonli-core\12.2.0\ikonli-core-12.2.0.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-web\17-ea+11\javafx-web-17-ea+11-win.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-fxml\17-ea+11\javafx-fxml-17-ea+11-win.jar;C:\Users\User\.m2\repository\org\kordamp\ikonli\ikonli-javafx\12.2.0\ikonli-javafx-12.2.0.jar;C:\Users\User\.m2\repository\eu\hansolo\tilesfx\11.48\tilesfx-11.48.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-base\17-ea+11\javafx-base-17-ea+11-win.jar;C:\Users\User\.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-controls\17-ea+11\javafx-controls-17-ea+11-win.jar;C:\Users\User\.m2\repository\net\synedra\validatorfx\0.1.13\validatorfx-0.1.13.jar;C:\Users\User\Desktop\Uczelnia\Java\demo1232\target\classes;C:\Users\User\.m2\repository\org\controlsfx\controlsfx\11.1.0\controlsfx-11.1.0.jar;C:\Users\User\.m2\repository\com\dlsc\formsfx\formsfx-core\11.3.2\formsfx-core-11.3.2.jar;C:\Users\User\.m2\repository\org\kordamp\bootstrapfx\bootstrapfx-core\0.4.0\bootstrapfx-core-0.4.0.jar;C:\Users\User\.m2\repository\org\openjfx\javafx-graphics\17-ea+11\javafx-graphics-17-ea+11-win.jar -m lab2.dziennik/lab2.dziennik.Main
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:467)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:366)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named org.hibernate.tutorial_jpa
    at firstname.lastname@example.com/javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
    at email@example.com/javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at lab2.dziennik/lab2.dziennik.Main.main(Main.java:26)
    ... 11 more
Exception running application lab2.dziennik.Main

Process finished with exit code 1

My code:

peristence.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.0"
             xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="org.hibernate.tutorial.jpa">
        <provider>org.hibernate.ejb.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test"/>
            <property name="hibernate.connection.autocommit" value="false"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="Kacper"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.connection.CharSet" value="utf8"/>
            <property name="hibernate.connection.characterEncoding" value="utf8"/>
            <property name="hibernate.connection.useUnicode" value="true"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

main:

 public static void main(String[] args) {
        EntityManagerFactory e = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
        testBaza1 t = new testBaza1();
        t.setId(2);
        t.setNazwa("bob");

        testBaza t1 = new testBaza();
        t1.setNazwa("xxx");

        EntityManager e1 = e.createEntityManager();
        e1.persist(t);
        e1.persist(t1);
        e1.getTransaction().commit();

        e.close();
    }

testBaza:

package lab2.dziennik;
import javax.persistence.*;

@Entity
@Table(name="TEST")
public class testBaza {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    public Integer getId()
    {
        return id;
    }

    public void setId(int id1){
        id=id1;
    }

    @Column(name="nazwa")
    private String nazwa;

    public String getNazwa()
    {
        return nazwa;
    }

    public void setNazwa(String n){
        nazwa=n;
    }

}

testBaza1

package lab2.dziennik;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TEST1")
public class testBaza1 {
    @Id
    @Column(name="id")
    private Integer id;

    public Integer getId()
    {
        return id;
    }

    public void setId(int id1){
        id=id1;
    }

    @Column(name="nazwa")
    private String nazwa;

    public String getNazwa()
    {
        return nazwa;
    }

    public void setNazwa(String n){
        nazwa=n;
    }
}

maven dependency:

<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.1.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

Please help.
Comment: [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Comment: Instead of image add it as text.
Comment: Okay, I wanted the post to be transparent. I'll take it into account next time.
Comment: Okay, but I have exception: INFO: HHH000318: Could not find any META-INF/persistence.xml file in the classpath and like before.
Comment: Add your exceptions and any other information to your question, not as comments or images.
Comment: I changed this.
Comment: When I did it throws even more exceptions.
Answer: "dirver" class? - I did not go through the complete Stack Trace since it is quite difficult to read :) Could you maybe write it as a code? :)
Try changing "dirver" -> "driver"

Also some drivers need setters and they need to be written correctly:
Comment: Oh, okay, I corrected, but continues to throw exceptions.
Comment: I have updated the exceptions in my post :)
Comment: You could try making the fields public. I do not know why do I have negative ratings - If anyone could explain that.. I am also new here :)


Background desalinhado com a página (excedendo o limite)

Question: Comecei a programar há alguns dias e não sei se o problema é no código ou se é a imagem que é grande demais.
A imagem excede o conteúdo da página e gera uma barra de rolagem na horizontal.
Vejam a CSS:

@charset "UTF-8";

p {
    text-indent: 30px;
    text-align: justify;
    font-family: Tahoma;
}

/*Formatação do menu */

div#cabecalho {
    background-color: white;
}

div#interface {
    background-image: url("_imgs/background.jpg");
    background-repeat: no-repeat;
    background-size: 100%;
    background-size: cover;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    overflow: auto;
    padding: 3em;
}

nav#menu {
    display: block;
    position: relative;
    left: 350px;
}

nav#menu ul {
    list-style: none;
    text-transform: uppercase;
}
nav#menu li {
    background-color: #dddddd;
    display: inline-block;
    padding: 8px;
    margin: 4px;
    transition: 0.7s;
    border-radius: 2px;
    box-shadow: 0.5px 0.5px 1px #202020;

}

nav#menu a {
    text-decoration: none;
    color: black;
}

nav#menu a:hover {
    color: white;
}

nav#menu li:hover {
    background-color: #606060;

}

nav#menu h1 {
    display: none;
}

/* Conteúdo */

div#conteudo {
    background-color: white;
    padding: 10px;
    box-shadow: 0px 0px 10px rgba(0,0,0,0.7);

}

div.rodape a {
    color: #000000;
    text-decoration: none;
}

**

<!DOCTYPE html>

        <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
        <meta charset="utf-8">
        <title>The Rockstar Page</title>

        <hgroup id="">

The Rockstar Games

Fan Page

        </hgroup>

Menu

Rockstar

Galeria de jogos

Vídeos

Download

Uma pequena introdução

A Rockstar Games é uma produtora de jogos eletrônicos fundada em 1998 por dois irmãos britânicos: San Houser e Dan Houser, em NY, nos Estados Unidos. Essa ilustre e maravilhosa produtora ganhou fama por criar a série "Grand Theft Auto" (vulgo "GTA"), tal série que gerou grande polêmica e alvoroço por ser um game em mundo aberto. Sendo assim, era quase que inevitável que o jogo não contesse violência explícita, roubos, assassinatos e qualquer outro tipo de atividade ilegal.

A Rockstar é diferente das outras produtoras de jogos por um simples motivo: ela faz aquilo que nós (jogadores de jogos) queremos jogar. Mas não são só "aqueles joguinhos com história clichê" não. Eles priorisam a experiência e jogabilidade tanto quanto uma empresa por aí (não farei menções, desculpe) priorisa a experiência de um umboxing.

Em Outubro de 2011, Dan Houser disse o seguinte à uma revista japonesa de videogames: "[...]Pode-se dizer que o objetivo da Rockstar é fazer com que os jogadores realmente sintam o que estamos tentando fazer."[...]Eu acho que nós justamente conseguimos porque nos não concentramos no lucro… Se nós fizermos o tipo os jogos que quer jogar, então acreditamos que as pessoas vão comprá-los."

Sucessos e uma breve sinopse

            Jogos

Copyright ©  Rockstar Games

**
Comment: Brendom, bem vindo, acho que um PrintScreen para visualização de pelo menos parte do problema ajudaria muito. Você pode adicionar imagens ao texto, comece pela edição de sua pergunta.
Comment: div#interface {
    background-image: url("_imgs/background.jpg");
    background-repeat: no-repeat;
    background-size: 100%;
    background-size: cover;
    position: absolute;
    width:100%;
    height:100%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    overflow: hidden;
    padding: 0;
}
Answer: Atualização da Resposta:
Visualizando seu código eu consegui identificar o erro, o mesmo se encontrava em nav#menu onde você colocou a propriedade left: 350px; esta linha era a principal causadora do erro, pois estava indicando para ficar 350px a direita da borda esquerda. Leia mais sobre a propriedade aqui.
Para corrigir o erro eu atualizei o seu css que estava assim:
nav#menu {
    display: block;
    position: relative;
    left: 350px;
}

Para isto:
nav#menu {
    display: block;
    position: relative;
    float:right;
}

E criei uma nova classe css:
.posicao-menu{
    float:right;
    width:100%;
    height:auto;
}

No seu html atualizei a linha que estavam assim:

Para estas novas linhas:

E também atualizei a linha que estava assim:

Para estas novas linhas:

Resumindo, criei uma div para colocar seu menu e defini a propriedade float para que ela flutue a direita, da mesma forma defini a propriedade para sua nav que tem o ID menu.
E coloquei em seu html que a nav#menu é filho da div posicao-menu.
Faça os testes!
Comment: Não é no conteúdo que quero mexer e sim no background. O conteúdo será alinhado depois pra inserir mais informações, mas obrigado :D
Comment: Tem como postar seu código completo de como ele está atualmente? Se você estiver declarando a `div conteudo` sem especificar um tamanho para ela, o background da `div interface` vai passar o limite da tela.
Comment: Está igual, não tive tempo de edita-lo ainda. Mas fiz as alterações que foram ditas e o problema não foi resolvido :\
Comment: Você pode postar seu código `html`? Assim consigo te ajudar.
Comment: Código html postado...
Comment: @Brendon Atualizei minha resposta, verifique por favor.
Comment: Era isso!!! Valeu, cara! Agora é só continuar os testes :D
Comment: Sempre que precisar poste seu código que ajudamos no que pudermos.