text:
Q: Taking a picture via camera and sending it to server in bytearray I am working on an Andorid application in which I would like the user to take a picture and then to save it I am sending it over to the server. Now, I am sending the picture as a byte-array to the server. When I try to save the byte-array to a file as a PNG file, and then try to open the file, the image-viewer complains that the PNG has errors and cannot be displayed. The PNG file size was 122Kb.
When I tried to use Scalr library to resize the image, it says the image source cannot be null. Directly saving the byte-array is causing a corrupt PNG. How should I convert and send the file properly to server, so there are no errors.
Here is the code for camera which I am using and sending it over.
public class AddPhotoForUser extends DrawerLoader {

    private static final int CAMERA_PIC_REQUEST = 22;
    Button BtnSelectImage;
    private ImageView ImgPhoto;
    private static volatile Bitmap photo;
    private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();

    final PersonServiceImpl personService = new PersonServiceImpl();

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

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

        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        set(navMenuTitles, navMenuIcons);

        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
        uploadImageButton.setVisibility(View.INVISIBLE);

        ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });

        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {
                    uploadImage();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
                    startActivity(intent);
                    finish();

                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(AddPhotoForUser.this, Login.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case CAMERA_PIC_REQUEST:
                    if (resultCode == RESULT_OK) {
                        try {
                            photo = (Bitmap) data.getExtras().get("data");
                            if (!(photo == null)) {
                                ImgPhoto.setImageBitmap(photo);
                                Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                                uploadImageButton.setVisibility(View.VISIBLE);

                            }
                        } catch (Exception e) {
                            Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void uploadImage() {

        if (!(photo == null)) {
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            personService.addUserProfilePhoto(byteArray);
        }

    }
}

Here is the server side code to save the image to disk :
 @Override
    public Boolean updateProfilePhoto(byte[] photo) {
        Person person = getCurrentlyAuthenticatedPerson();
        try{
           InputStream in = new ByteArrayInputStream(photo);
            BufferedImage image = ImageIO.read(in);
            image = Scalr.resize(image, Scalr.Method.QUALITY, 100, 100);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            File file = new File(userImagePath);
            if (file.exists() && file.isDirectory()) {
                OutputStream outputStream = new FileOutputStream(new File(userImagePath + person.getUserId()+".png"));
                outputStream.write(baos.toByteArray());
                outputStream.close();
            } else {
                File file1 = new File(userImagePath+person.getUserId()+".png");
                if (file1.exists()) {
                    try {
                        OutputStream outputStream = new FileOutputStream(file1);
                        outputStream.write(baos.toByteArray());
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                } else {
                   boolean result = file1.createNewFile();
                    System.out.println("Result of file1 creation is "+result);
                    OutputStream outputStream = new FileOutputStream(file1);
                    outputStream.write(baos.toByteArray());
                    outputStream.close();
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

If I don't use the Scalr library, there are no errors, but its a corrupt file. Here is the Scalr error log :
java.lang.IllegalArgumentException: src cannot be null
    at org.imgscalr.Scalr.resize(Scalr.java:1564)
    at org.imgscalr.Scalr.resize(Scalr.java:1415)
    at com.journaldev.spring.service.PersonServiceImpl.updateProfilePhoto(PersonServiceImpl.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy51.updateProfilePhoto(Unknown Source)
    at com.journaldev.spring.Controller.PersonController.addProfilePhotoForUser(PersonController.java:100)

Any help would be nice. Thanks a lot. :-)
Updated code
public class AddPhotoForUser extends DrawerLoader {

    Button BtnSelectImage;
    private ImageView ImgPhoto;

    private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();

    final PersonServiceImpl personService = new PersonServiceImpl();

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private static final int CAMERA_PHOTO = 111;
    private Uri imageToUploadUri;

    Bitmap reducedSizeBitmap;

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

        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        set(navMenuTitles, navMenuIcons);

        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
        uploadImageButton.setVisibility(View.INVISIBLE);

        ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                    captureCameraImage();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });

        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {
                    uploadImage();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
                    startActivity(intent);
                    finish();

                }
            }
        });

    }

    private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 12000000; // 12MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();

            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;
                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

    private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(AddPhotoForUser.this, Login.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
            if(imageToUploadUri != null){
                Uri selectedImage = imageToUploadUri;
                getContentResolver().notifyChange(selectedImage, null);
                reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                if(reducedSizeBitmap != null){
                    ImgPhoto.setImageBitmap(reducedSizeBitmap);
                    Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                    uploadImageButton.setVisibility(View.VISIBLE);
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            }else{
                Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
            }
        }

    }

    private void uploadImage() {
        if(!(reducedSizeBitmap == null)){
            reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            this.personService.addUserProfilePhoto(byteArray);
        }
    }
}

A: If you use Bundle extras = data.getExtras(); in your onActivityResult() then it will return thumbnail image not actual image.
Here is code I have used for Capturing and Saving Camera Image then display it to ImageView. You can use according to your need.
You have to save Camera image to specific location then fetch from that location then convert it to byte-array.
Here is method for opening capturing camera image activity.
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

then your onActivityResult() method should be like this.
@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            }
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.
private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();

            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

EDIT:
Here is method for uploading image to server.
/**
 * Upload Image to server
 *
 * @param file              image to be saved
 * @param compressorQuality quality of image
 * @return path of uploaded image in server
 */
private String uploadImage(Bitmap file, int compressorQuality) {
    String final_upload_filename = "demo_image.png";
    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";
        URL url = new URL("image_upload_url");
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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("uploaded_file", final_upload_filename);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);
        file.compress(CompressFormat.PNG, compressorQuality, dos);
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        dos.close();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();
        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response;
}

You need to make upload script in backend server to store image data in particular folder.
I hope it helps!

A: At first you need to create a file and save image on it and here's a code.
//method to save image in internal or external storage
private void storeImage(Bitmap image,String imageName) {
    File pictureFile = getOutputMediaFile(imageName);
    if (pictureFile == null) {
        Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    }
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }
}

//method to create file to save image on it
private  File getOutputMediaFile(String imageName){
    //create folder with name FoursquareAPI
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/FoursquareAPI");

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }
    File mediaFile;
        String mImageName= imageName +".png";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
    return mediaFile;
}


text:
Q: Windows Store App Access Violation Exception only on Windows 10 I have Windows Store app that is in the Store for 2 years. After Windows 10 release I get a lot of crashes. I can reproduce crash, but only on Windows 10, not 8, or 8.1, also, I`m able to see that this crash happens only on Windows 10, through developer console. There are a lot of such crashes on windows 10 ~ 1000, for month.
The crash sequence: I open the page, app hangs for a second and then it closes without any suggestion for report.
When I debug app with visual studio, app fails with exception:
Access violation reading location 0x00000090 in Windows.Ui.Xaml.dll

Stack trace from dev.windows console:
windows_ui_xaml DirectUI::CCueRenderer::Initialize  0x154
windows_ui_xaml DirectUI::CTimedTextSource::Initialize  0xE0
windows_ui_xaml DirectUI::CTimedTextSource::Create  0x60
windows_ui_xaml DirectUI::MediaElement::EnableTimedText 0x60
windows_ui_xaml DirectUI::MediaElement::HandleMediaOpened   0x21
windows_ui_xaml DirectUI::MediaElement::OnMediaOpened   0x4D
windows_ui_xaml CFxCallbacks::MediaElement_OnMediaOpened    0x20
windows_ui_xaml CMediaElement::OpenMedia    0x156
windows_ui_xaml CMediaElement::HandleSourceReadyEvent   0x12
windows_ui_xaml CMediaElement::HandleMediaEvent 0x90
windows_ui_xaml CMediaQueue::ProcessQueue   0x67
windows_ui_xaml CMediaQueueManager::ProcessQueues   0x90
windows_ui_xaml CCoreServices::Tick 0x246
windows_ui_xaml CCoreServices::NWDrawTree   0x2F1
windows_ui_xaml CCoreServices::NWDrawMainTree   0xB7
windows_ui_xaml CWindowRenderTarget::Draw   0x73
windows_ui_xaml CXcpBrowserHost::OnTick 0x1CB
windows_ui_xaml CXcpDispatcher::Tick    0x88
windows_ui_xaml CXcpDispatcher::OnReentrancyProtectedWindowMessage  0x6F
windows_ui_xaml CXcpDispatcher::WindowProc  0xE0
user32  _InternalCallWinProc    0x2B
user32  UserCallWinProcCheckWow 0x1F0
user32  DispatchMessageWorker   0x231
user32  DispatchMessageW    0x10
windows_ui  Windows::UI::Core::CDispatcher::ProcessMessage  0x356
windows_ui  Windows::UI::Core::CDispatcher::WaitAndProcessMessages  0x129
windows_ui  Windows::UI::Core::CDispatcher::ProcessEvents   0x75
windows_ui_xaml CJupiterWindow::RunCoreWindowMessageLoop    0x55
windows_ui_xaml CJupiterControl::RunMessageLoop 0x25
windows_ui_xaml DirectUI::DXamlCore::RunMessageLoop 0x1E
windows_ui_xaml DirectUI::FrameworkView::Run    0x1A
twinapi_appcore Windows::ApplicationModel::Core::CoreApplicationView::Run   0x3D
twinapi_appcore _lambda_8b2420e462ae079d580fd8e4ff08c89d_::_helper_func_stdcall_    0xAC
shcore  _WrapperThreadProc  0xCA
kernel32    BaseThreadInitThunk 0x24
ntdll   __RtlUserThreadStart    0x2F
ntdll   _RtlUserThreadStart

That is errors description if I download reports:
NULL_CLASS_PTR_READ_c0000005_Windows.UI.Xaml.dll
NULL_POINTER_READ_c0000005_Windows.UI.Xaml.dll

Does anyone has faced the same issue with windows 10 too?
As I understand, there is no managed (my) function calls in stack trace, does it mean that it is Windows 10 bug?

A: As @Pooley mentioned, this code causes error on windows 10 computers:
 var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("msappx:///Resources/Sounds/" + name + ".mp3"));
 var stream = await file.OpenAsync(FileAccessMode.Read);
 var mediaElement = new MediaElement();
 mediaElement.SetSource(stream, file.FileType); mediaElement.Play();

A: I just solved a very similar problem where an universal app would crash with read access violation. The stack trace looked very similar to yours, most of the time it crashed somewhere down the road from CXcpDispatcher::Tick. Although not always, stack trace and also the exception itself would vary sometimes.
The cause was a native c++ class that was dll-imported (p/invoke) by a thin C# wrapper. When the app was holding an instance of that class it would crash every now and then.
That c++ class had one private member of type std::string. After removing that member the universal app stopped crashing. The c++ compiler actually issued a warning C4251 for that member.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using the VSCode Markdown Renderer with Pandoc I am typing up some homework assignments in markdown using both markdown formatting and LaTex for math typesetting in VSCode. I now want to convert the markdown to PDF for review.
VSCode renders markdown perfectly, while pandoc reports many undefined control sequences. How can I get pandoc to use the same renderer that VSCode uses to convert to PDF? After doing some research, it looks like VSCode uses commonmark, but commonmark doesn't seem to render math formulas in pandoc
I've tried this command which avoids the errors but doesn't render the math
pandoc hw1.md -o hw1.pdf -f commonmark --katex


text:
Q: ExtJS 4.2.2: Ext.Direct callback / JSON writer I have connected a grid to Ext.Direct, but I am having problems getting it to work properly.
When I create a new record, the new record's ID (which has been generated in PHP) gets returned with the response, but is not saved in the grid's store. So when I try to update this record, I get an error message as it tries to update the record with ID 0.
I believe that I need to set up a JSON Writer on my store's proxy, but I have not succeeded in doing so yet.
Any help getting it to work properly would be greatly appreciated.
Here's what I've done so far:
The store's model:
Ext.define('Test.model.Post', {
    extend: 'Ext.data.Model',
    alias: 'model.postmodel',

    requires: [
        'Ext.data.Field',
        'Ext.data.proxy.Direct',
        'Ext.data.reader.Json',
        'Ext.data.writer.Json'
    ],

    idProperty: 'idPost',

    fields: [
        {
            name: 'id',
            type: 'int'
        },
        {
            name: 'idPost',
            type: 'int'
        },
        {
            name: 'achns',
            type: 'string'
        },
        {
            name: 'php_poststring',
            type: 'string'
        },
        {
            name: 'postNo1',
            type: 'int'
        },
        {
            name: 'postNo2',
            type: 'int'
        },
        {
            name: 'postNo3',
            type: 'int'
        },
        {
            name: 'postNo4',
            type: 'int'
        },
        {
            name: 'postNo5',
            type: 'int'
        },
        {
            name: 'postNo6',
            type: 'int'
        },
        {
            name: 'postNo7',
            type: 'int'
        },
        {
            name: 'php_name',
            type: 'string'
        },
        {
            name: 'processCode',
            type: 'string'
        },
        {
            name: 'processText',
            type: 'string'
        },
        {
            name: 'processFreetext',
            type: 'string'
        },
        {
            name: 'postUnit',
            type: 'string'
        },
        {
            name: 'postQuantity',
            type: 'string'
        }
    ],

    proxy: {
        type: 'direct',
        api: {
            create: 'Posts.createRecord',
            read: 'Posts.getResults',
            update: 'Posts.updateRecords',
            destroy: 'Posts.destroyRecord'
        },
        extraParams: {
            licence_id: sessionStorage.licenceid,
            username: sessionStorage.username,
            _c: sessionStorage.control,
            project_id: sessionStorage.projectid
        },
        reader: {
            type: 'json',
            root: 'data'
        },
        writer: {
            type: 'json',
            writeRecordId: false
        }
    }
});

JSON Posted (createRecord):
{
    "action": "Posts",
    "method": "createRecord",
    "data": [{
        "id": 0,
        "idPost": 0,
        "achns": "I",
        "php_poststring": "",
        "postNo1": 0,
        "postNo2": 0,
        "postNo3": 0,
        "postNo4": 0,
        "postNo5": 0,
        "postNo6": 0,
        "postNo7": 0,
        "php_name": "",
        "processCode": "",
        "processText": "",
        "processFreetext": "",
        "postUnit": "",
        "postQuantity": ""
    }],
    "type": "rpc",
    "tid": 3
}

JSON Response (createRecord):
{
    "type": "rpc",
    "tid": 3,
    "action": "Posts",
    "method": "createRecord",
    "result": [{
        "success": true,
        "message": "Successfully created post",
        "dataroot": [{
            "idPost": 119, // This ID should be updated in the store
            "fkpdHeader": 4,
            "fkpdObject": null,
            "fkpdElement": null,
            "fkndConstructionPart": null,
            "fkpdFloor": null,
            "fkpdCorrection": null,
            "ACHNS": "I",
            "status": 10,
            "descriptionCode": "",
            "ITTBdescription": "",
            "freeTextDescription": "",
            "quantity": 0,
            "unit": "",
            "postNo1": 0,
            "postNo2": 0,
            "postNo3": 0,
            "postNo4": 0,
            "postNo5": 0,
            "postNo6": 0,
            "postNo7": 0
        }]
    }]
}

Then when I click the record inserted to edit it and commit it, this happens:
JSON Posted (updateRecords):
{
    "action": "Posts",
    "method": "updateRecords",
    "data": [{
        "id": 0,
        "idPost": 0, // Not set from previous return
        "achns": "I",
        "php_poststring": "",
        "postNo1": 0,
        "postNo2": 0,
        "postNo3": 0,
        "postNo4": 0,
        "postNo5": 0,
        "postNo6": 0,
        "postNo7": 0,
        "php_name": "",
        "processCode": "",
        "processText": "",
        "processFreetext": "asdads",
        "postUnit": "",
        "postQuantity": ""
    }],
    "type": "rpc",
    "tid": 15
}

Error response (updateRecords):

PHP Error - Creating default object from empty value

Because idPost is 0 it is not able to select the record from the database to edit.
Edit (2014-01-20):
Added some more code and error information.

A: I think you need to take a look at the idProperty config for your Model. By default, the Model expects the identifier field to be named "id"; change that to "idPost" and the Store record should be updated properly on response.


text:
Q: The Go code does not compile: undefined: revel.EmptyPlugin Me and a few friends are writing a server using golang (revel) and had a database implemented just a few weeks ago. Then suddenly everything just stopped working and the go compiler can't find my import files. That includes EmptyPlugin as well as RegisterPlugin.
We are all pretty new so this is probably a pretty simple fix. I have checked my github.com/robfig/revel folder, and there is no file called EmptyPlugin. But that is probably a misunderstanding from my side :P.
By commenting the lines revel.EmptyPlugin and revel.RegisterPlugin(DbPlugin{}) everything works as it should.
package controllers

import (
    "database/sql"
    "fmt"
    _ "github.com/bmizerany/pq"
    "github.com/robfig/revel"
    "log"
    "time"
    //"strconv"
)

type DbPlugin struct {
    revel.EmptyPlugin
}

func init() {
    revel.RegisterPlugin(DbPlugin{})
}

var db *sql.DB
var err error

A: You appear to compiling using the latest and recently updated version of Revel: https://github.com/robfig/revel.
However, it appears that your code was written for this older version of Revel: https://github.com/robfig/revel/tree/dev.
Update your code to the latest version of Revel.


text:
Q: Extending domain of a meromorphic function from non-compact to compact domain Let $f$ be a meromorphic function with $\text{dom} (f)=\mathcal{M}$, where $\mathcal{M}$ is a non-compact Riemann surface.
If $\mathcal{M}'= \mathcal{M} \cup \{\infty \}$ is the one-point compactification of $\mathcal{M}$, then is $f$ with domain $\mathcal{M}'$ still meromorphic? Does this depend on the compactification method?
Many thanks

A: No.
You can see it with the case $M = \mathbb{C}$, $f=\sin$ (here $f$ is even holomorphic).
sinus is bounded in the direction corresponding to the real line, but tends to infinity along the direction of pure imaginary.
So on the riemann sphere $S^2 = \mathbb{C} \cup \{ \infty \}$, $\sin$ admits no continuous continuation and hence no meromorphic continuation.


text:
Q: authenticate user on server side for Swing clients using kerberos/spnego I am using kerberos protocol to authenticate users for Java Swing applications. I am able to successfully authenticate at the client side, but having problems when getting the user credentials and roles on the server side, I have got ejbs which require certain roles to create those ejbs.
jboss-app.xml looks like
 <jboss-app>
    <security-domain>java:/jaas/spnego-server</security-domain>
    <loader-repository>paymenttracker:loader=paymenttracker.ear</loader-repository>
 </jboss-app>

The client class calling Subject.doAs(s, lv);
lv is a class which extends PrivilegedExceptionAction.
On the server side login-config.xml in jboss server got the following setting
     <application-policy name="spnego-server"><authentication>
    <login-module code="com.sun.security.auth.module.Krb5LoginModule" flag="required" >
<module-option name="storeKey">true</module-option>
<module-option name="debug">true</module-option>
<module-option name="useKeyTab">true</module-option>
<module-option name="keyTab">file://c:/ker/tem.keytab</module-option>
<module-option name="principal">HTTP/ws6421.ebrd.com</module-option>
<module-option name="doNotPrompt">true</module-option>
<module-option name="isInitiator">false</module-option>
</login-module></authentication>
</application-policy>

getting the following error :
16:09:28,990 INFO  [STDOUT] Debug is  true storeKey true useTicketCache false useKeyTab true doNotPrompt true
ticketCache is null isInitiator false KeyTab is file://c:/kerberos/ws6421.keytab refreshKrb5Config is false pr
incipal is HTTP/ws6421.my.com tryFirstPass is false useFirstPass is false storePass is false clearPass is fa
lse
16:09:29,087 INFO  [STDOUT] principal's key obtained from the keytab
16:09:29,087 INFO  [STDOUT] principal is HTTP/ws6421.my.com@MY.COM
16:09:29,088 INFO  [STDOUT] EncryptionKey: keyType=23 keyBytes (hex dump)=0000: A9 DD 6C AB C5 D3 A0 9D   C8 4
4 18 52 78 3E AB 82  ..l......D.Rx>..
16:09:29,094 INFO  [STDOUT] Added server's keyKerberos Principal HTTP/ws6421.ebrd.com@MY.COMKey Version 0key
 EncryptionKey: keyType=23 keyBytes (hex dump)=
0000: A9 DD 6C AB C5 D3 A0 9D   C8 44 18 52 78 3E AB 82  ..l......D.Rx>..
16:09:29,095 INFO  [STDOUT]             [Krb5LoginModule] added Krb5Principal  HTTP/ws6421.my.com@MY.COM t
o Subject
16:09:29,098 INFO  [STDOUT] Commit Succeeded
16:09:29,135 ERROR [SecurityInterceptor] Error in Security Interceptor
java.lang.SecurityException: Denied: caller with subject=Subject:
        Principal: HTTP/ws6421.my.com@MY.COM
        Private Credential: Kerberos Principal HTTP/ws6421.my.com@MY.COMKey Version 0key EncryptionKey: ke
yType=23 keyBytes (hex dump)=
0000: A9 DD 6C AB C5 D3 A0 9D   C8 44 18 52 78 3E AB 82  ..l......D.Rx>..

 and security context post-mapping roles=null: ejbMethod=public abstract services.ejb.login.SBLogin services.e
jb.login.SBLoginHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException
        at org.jboss.ejb.plugins.SecurityInterceptor.checkSecurityContext(SecurityInterceptor.java:368)
        at org.jboss.ejb.plugins.SecurityInterceptor.process(SecurityInterceptor.java:243)


text:
Q: What is $f '(x)$ for $f(x)=(x-3)^3$?
What is $f '(x)$ for $f(x)=(x-3)^3$?

I'm thinking it is $3x^2 - 18x + 27$
but my textbook says it is $3x^2 - 18x - 27$

A: Using the chain rule we have:
$f'(x)=3(x-3)^2\times \frac{d}{dx}(x-3) = 3(x-3)^2$
And $3(x-3)^2 = 3(x^2-6x+9) = 3x^2-18x+27$
You are right. Your textbook is wrong.

A: Note that
$$
f(x)=U^n\\
f^{\prime}(x)=nU^{\prime}U^{n-1}
$$
Then
$$\begin{align}
f^{\prime}(x)&=3(x-3)^{2}\\
&=3(x-3)(x-3)\\
&=3(x(x-3)-3(x-3))\\
&=3(x^2-3x-3x+9)\\
&=3(x^2-6x+9)\\
&=3x^2-18x+27\\
\end{align}$$


text:
Q: Emma code coverage for android JUnit test How to run Eclemma code coverage tool for android Junit test, not for Junit test? Can any one please help.

A: The easiest way would be to add ant build files to both projects (main and test) and then use the specific ant targets to generate the coverage report.
 Then you can import the coverage report to EclEmma.
To add the ant build you first need to disable Project -> Build Automatically in Eclipse to avoid conflicts.
These steps are described in http://dtmilano.blogspot.ca/2011/07/eclipse-android-and-emma-code-coverage.html.


text:
Q: Include third party scripts as type="module" Im trying to figure out if there is a way to configure angular.json to include scripts as type="module" assuming the following script needs to load as
<script src="scripts.js" type="module"></script>

When i try this it does not add type="module". Is there a config to make it do that?
"scripts": [
  "node_modules/third-part/script.js"
]

I checked around in the docs but did not see it https://angular.io/guide/workspace-config#style-script-config
If not is there a best practice to include it?


text:
Q: toggleClass animation not working? or need help toggling animation I am working with this code:
 $('#products h2').click(
        function() {
           $('.well').toggleClass('margin-left260', 100000);
            return false;
        }
    );

What I want to do is slide a div over 260 using a left margin, and then have it slide back on click to 0.  I don't understand why .toggleClass is not animating for me.
I also did well earlier using .animate(margin-left,'260px); but for the life of me could figure out how to use the toggle to have it return to a margin of 0.  What am I missing here?

A: I have added a jsfiddle example here - http://jsfiddle.net/BaXyR/
basically
$('.clickme').click(function(){
if($('#moveme').hasClass('marginleft260')){
      $('#moveme').animate({
        marginLeft: "-=260px",
      }, 5000, function() {
        $(this).removeClass('marginleft260');
      });
}else{
      $('#moveme').animate({
        marginLeft: "+=260px",
      }, 5000, function() {
        $(this).addClass('marginleft260');
      });
}
});

A: toggleClass can be used to add / remove a class / classes on a toggle.  is margin-left260 a class in your css i.e.
.margin-left260 {
    margin-left:260px;
}

also looking at your code, i think you are not implementing toggleClass correctly.  see : http://api.jquery.com/toggleClass/
are you trying to animate the movement?
I think the correct code would be use the animate function - see : http://api.jquery.com/animate/


text:
Q: Android Layout Repeating Pattern I'm setting up an android app that will display data like this:
Line Name        X    GGGGRR
Another Name     Y    GGGRRR
...
Last Name        Z    GGRRRR

where the names and x, y, z numbers are TextViews and the Gs and Rs are ImageViews showing red and green circles.
What's the best way to lay this out? I think putting the list in a vertical LinearLayout makes sense.
I don't want to repeat a bunch of LinearLayouts containing TextViews and ImageViews in the XML, because I might need to adjust the number of entries dynamically. What's the best way to encapsulate these lines? Should I create a custom layout for it? Or would it be better to use a fragment for each line?

A: You sholud use a custom layout with textviews and imageviews as you said and you can use ListView or RecycleView for the list.


text:
Q: Download in android large files When I try this code, it starts download but then stuck with alert "force close"
what should I do? Use some kind of background thread?
try {
    long startTime = System.currentTimeMillis();

    URL u = new URL("http://file.podfm.ru/3/33/332/3322/mp3/24785.mp3");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();

    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    FileOutputStream f = new FileOutputStream(new File("/sdcard/","logo.mp3"));

    InputStream in = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ( (len1 = in.read(buffer)) != -1 ) {
        f.write(buffer,0, len1);
    }
    f.close();

    Log.d("ImageManager", "download ready in" +
        ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
catch (IOException e)
{
    Log.d("ImageManager", "Error" +
        ((System.currentTimeMillis()) / 1000) + e + " sec");
}

A: You should try using an AsyncTask. You are getting the force quit dialog because you are trying to do too much work on the UI thread and Android judges that your application has become unresponsive.
The answers to this question have some good links.
Something like the following would be a good start:
private class DownloadLargeFileTask extends AsyncTask<Void, Void, Void> {
     private final ProgressDialog dialog;

     public DownloadLargeFileTask(ProgressDialog dialog) {
          this.dialog = dialog;
     }

     protected void onPreExecute() {
         dialog.show();
     }

     protected void doInBackground(Void... unused) {
         downloadLargeFile();
     }

     protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

and then execute the task with:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading. Please Wait...");
new DownloadLargeFileTask(dialog).execute();

A: I was dealing with similar problem last week and ended up using AsyncTask with progress bar displayed since it could take some time for the file to be downloaded. One way of doing it is to have below class nested in your Activity and just call it where you need to simply like this:
new DownloadManager().execute("here be URL", "here be filename");

Or if the class is not located within an activity and calling from an activity..
new DownloadManager(this).execute("URL", "filename");

This passes the activity so we have access to method getSystemService();
Here is the actual code doing all the dirty work. You will probably have to modify it for your needs.
private class DownloadManager extends AsyncTask<String, Integer, Drawable>
{

    private Drawable d;
    private HttpURLConnection conn;
    private InputStream stream; //to read
    private ByteArrayOutputStream out; //to write
    private Context mCtx;

    private double fileSize;
    private double downloaded; // number of bytes downloaded
    private int status = DOWNLOADING; //status of current process

    private ProgressDialog progressDialog;

    private static final int MAX_BUFFER_SIZE = 1024; //1kb
    private static final int DOWNLOADING = 0;
    private static final int COMPLETE = 1;

    public DownloadManager(Context ctx)
    {
        d          = null;
        conn       = null;
        fileSize   = 0;
        downloaded = 0;
        status     = DOWNLOADING;
        mCtx       = ctx;
    }

    public boolean isOnline()
    {
        try
        {
            ConnectivityManager cm = (ConnectivityManager)mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting();
        }
        catch (Exception e)
        {
            return false;
        }
    }

    @Override
    protected Drawable doInBackground(String... url)
    {
        try
        {
            String filename = url[1];
            if (isOnline())
            {
                conn     = (HttpURLConnection) new URL(url[0]).openConnection();
                fileSize = conn.getContentLength();
                out      = new ByteArrayOutputStream((int)fileSize);
                conn.connect();

                stream = conn.getInputStream();
                // loop with step
                while (status == DOWNLOADING)
                {
                    byte buffer[];

                    if (fileSize - downloaded > MAX_BUFFER_SIZE)
                    {
                        buffer = new byte[MAX_BUFFER_SIZE];
                    }
                    else
                    {
                        buffer = new byte[(int) (fileSize - downloaded)];
                    }
                    int read = stream.read(buffer);

                    if (read == -1)
                    {
                        publishProgress(100);
                        break;
                    }
                    // writing to buffer
                    out.write(buffer, 0, read);
                    downloaded += read;
                    // update progress bar
                    publishProgress((int) ((downloaded / fileSize) * 100));
                } // end of while

                if (status == DOWNLOADING)
                {
                    status = COMPLETE;
                }
                try
                {
                    FileOutputStream fos = new FileOutputStream(filename);
                    fos.write(out.toByteArray());
                    fos.close();
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    return null;
                }

                d = Drawable.createFromStream((InputStream) new ByteArrayInputStream(out.toByteArray()), "filename");
                return d;
            } // end of if isOnline
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }// end of catch
    } // end of class DownloadManager()

    @Override
    protected void onProgressUpdate(Integer... changed)
    {
        progressDialog.setProgress(changed[0]);
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog = new ProgressDialog(/*ShowContent.this*/); // your activity
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Downloading ...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Drawable result)
    {
        progressDialog.dismiss();
        // do something
    }
}


text:
Q: Format Django DateField as ISO format I'm using Django to serve up some XML. Part of the requirements is that my dates are formatted as follows: 1969-12-31T18:33:28-06:00
How can I output a DateField in Django in that format?

A: If you look under date in the Django documentation you'll see that a variety of formats for the date are supported. Basically in a template you need:
{{ value|date:"some format string" }}

where the format string can be one of the ones defined under date on the page above or one of the custom ones defined under the now function (which includes ISO 8601 format) which is also on the page linked to above. I'm assuming that when you output to xml you do so in a similar way to a template for a normal web page.
Update (August 2014)
As indicated in another answer by Edgar R, as of version 1.2 onwards you can now use a built in switch to output the date in ISO 8601 format using format string: c

A: Introduced in Django 1.2, there is a template tag that will output what you wish:
{{ value|date:"c"}}

From the Django template documentation:

c | ISO 8601 Format | 2008-01-02T10:30:00.000123

Technically, this closer to W3-DTF, but close enough

A: Since Django is written in Python,
http://docs.python.org/library/datetime.html#datetime.datetime.isoformat
datetime(2002, 12, 25, tzinfo=TZ()).isoformat()

A: Check out these docs:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#date
http://docs.djangoproject.com/en/dev/ref/settings/#setting-DATE_FORMAT
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ttag-now
This should be enough for you to format your date any way, you wish.


text:
Q: Bullet: btBvhTriangleMeshShape crash So I have this line of code:
new btBvhTriangleMeshShape(meshInterface, true);

Which crashes my program. Apparently, somewhere inside the function there is an assert(numIndices>0) line, which is causing the crash.
If I add one more false parameter on the end of my line so it looks like:
new btBvhTriangleMeshShape(meshInterface, true, false);

I tell it not to generate the bounding volume data, and it continues fine (no crash). So my question is: Why is it when I clearly have indices in meshInterface, it crashes and says I have no indices.
Additional Info:
meshInterface is created like this:
btTriangleMesh *meshInterface = new btTriangleMesh();
for(uint i = 0; i < terrainMesh.position.size(); i++) {
    //don't remove duplicate vertex because there won't ever be any
    meshInterface->findOrAddVertex(toBt(terrainMesh.position[i]), false);
}
for(uint i = 0; i < terrainMesh.index.size(); i++) {
    meshInterface->addIndex(terrainMesh.index[i]);
}

I already have my data set up in another object, and I just load it into the bullet setup.
And here you can see there is clearly valid data in my meshInterface. The mesh is a flat plane.

A: From btTriangleMesh.h:
// findOrAddVertex is an internal method, use addTriangle instead
int findOrAddVertex(const btVector3& vertex, bool removeDuplicateVertices);

So try using addTriangle instead.
EDIT: It is more efficient to use btTriangleIndexVertexArray instead of btTriangleMesh.


text:
Q: Why don't dynamic objects and extension methods play nice? The causes of the exception:

Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Have been covered in several SO questions (here and here ).But no one has said why the Framework doesn't allow this:

Example
public static class ExampleExtension
{
    public static string HelloWorld(this object o, object o2)
    {
        return "Hello World";
    }

    public static void Test()
    {
        dynamic dynamicObject = new object();

        //Exception
        new object().HelloWorld(dynamicObject);

        //No Exception
        ExampleExtension.HelloWorld(new object(), dynamicObject);
    }
}

new object().HelloWorld(dynamicObject)` is bad

ExampleExtension.HelloWorld(new object(), dynamicObject)` is good

Why?
If extension methods are essentially just syntactic sugar for calling a static method, wouldn't new object().HelloWolrd() be converted to the compiler to ExampleExtension.HelloWorld(new object()) anyway?  So why can't the DLR handle this?


text:
Q: Why is the chiral condensate a negative quantity? The chiral condensate serves as an order parameter for the chiral phase transition. Thus, it is a finite quantity in one phase and vanishes in the other phase. It is given as a vacuum expectation value of quark fields, e.g.,
$\langle \Omega |\bar\psi \psi | \Omega\rangle$. In QCD sum rules, for example for two quark flavors, it is related to the pion decay constant, pion mass, and quark masses (known as Gell-Mann--Oakes--Renner relation) via
$$\langle \Omega |\bar\psi \psi | \Omega\rangle = - \frac{\displaystyle f^2_\pi m^2_\pi}{\displaystyle 2(m_u + m_d)}$$
which are all positive quantities on the right-hand side such that the condensate must be negative.
Let me add the definition to be more precise:
The condensate is given as trace over the quark propagator ${\rm S}_q(x,y)= -i \langle \Omega |{\rm T} \{ \psi(x) \bar\psi(y) \}| \Omega\rangle$ such that
$$\langle \Omega |\bar\psi(x) \psi(0) | \Omega\rangle := -i \rm{Tr} \lim\limits_{x\to 0} S_q(x,0)\ .$$

How can a vacuum expectation value become a negative quantity?


text:
Q: spy on Observable.filter I have a Jasmin test in which I wish to check if the filter function on an Observable has been called
It looks something like this:
const spy = spyOn(component.myObservable,'filter');

mySubject.next(data);

expect(spy).toHaveBeenCalledTimes(1);

and the implementation :
this.myObservable
 .filter(data => data.....)
 .subscribe(date => data....)

I know that is't been called, but still I can't get the check to work.
Update
By using do i can see that the Observable catches the event. This tells me that the code works and that it is a matter of testing it right
this.myObservable
 .do(data => console.log(data) // log: 3
 .filter(data => data.....)
 .subscribe(date => data....)


text:
Q: Reasons rails is not stopping at debugger In our application in Ruby on Rails (4.0.2) we've always had this problem. I never understood quite well why the application doesn't stop at the debugger statement sometimes.
In some cases, we discovered some constant behavior such as: in a test, it never stops if the statement's placed at the end of the test block like this:
  describe '#some_method' do
    it 'should do something as in the requirements etc' do
      model_x = FactoryGirl.create(:model_x)
      model_x.should be_valid

      # ...more code

      model_x.should be_valid

      debugger
    end
  end

To make debugger stop at the statement, we have to add a  p "foo"
 after it.
In some other misterious cases it doesn't stop, but if you add prints before and after, it does.
When debugging a delayed job, you may have to require the debugger and add some prints for it to stop.
I can't find a deterministic reason why the debugger skips the debugger statement sometimes.
Can someone list the reasons for this behavior?

Obs: I'm using byebug right now, but I know that the plain debugger has this behavior too.
Obs2: From my Gemfile.lock:
byebug (2.4.0)
  columnize (~> 0.3.6)
  debugger-linecache (~> 1.2.0)
...
debugger (1.6.3)
  columnize (>= 0.3.1)
  debugger-linecache (~> 1.2.0)
  debugger-ruby_core_source (~> 1.2.4)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.2.4)

A: This is a known issue in the debugger gem, see here (bullet point number three).
It seems that you are interested in why it doesn't work. The following is the explanation:

*

*What debugger does is watching some events provided by ruby that tell the debugger when to stop. In this case, the debugger tracks what we call a line event that is triggered once per line executed, so in the case of the last line of a method, the debugger will stop in the next line event, which actually happens outside the method that is being debugged.

*In byebug, however, I also track what we call return events, that are called every time a method finishes. That's why I'm able to stop execution before the method actually finishes.
Hope this helps.


text:
Q: Calculus Apostol, 1.26 exercise 21 b I don't know how to solve this with the absolute value.
Find the value of c:
\[ \int_{0}^{c} |x(1-x)|dx=0 \]
Please, if possible, make a solution step-by-step. Thank you and sorry for the poor english.

A: HINT:
If $c\le 1$, then $\frac{c^2}{2}-\frac{c^3}{3}=0$.
If $c>1$, then $\frac{1}{2}-\frac{1}{3}+\frac{c^3}{3}-\frac{c^2}{2}-\frac{1}{3}+\frac{1}{2}=0 \Rightarrow \frac{c^2}{2}-\frac{c^3}{3}=\frac{1}{3}$.
Now try it out.


text:
Q: Azure SQLMI with AAD - Universal with MFA - sign in logs We are authenticating SQL MI users with AAD - Universal with MFA and would like to see a log of all sign ins.
Would this be under the AAD/Users/Audit Logs/Sign ins?
We'd like to see a few months worth of data.
Thanks

A:
In Azure Ad only 30 days of Sign in logs for user, Managed identities or even Service principals are available. After 30 days all  the logs whether audit, Activity or Sign-In are flushed out on Azure's  end, unless you store the logs every month or every seven days in an  Azure storage account or send it to Log analytics workspace.

For Azure AD Free Edition Sign in logs are retained only for 7 days. If you upgrade to Azure AD
Premium P1 or Azure AD Premium P2 then the sign in logs of past 30 days are available.

I created one SQL Server and enabled Azure AD User and tried Signing in with Azure AD Universal MFA via SSMS and managed Identity like below :-

Assigned VMs managed identity access to SQL server:-

SignInLogs of SQL server:-

For managed Identity logs, you can visit here :-

After clicking on try it out, New SignIn logs page will appear and you can select managed identity to verify if your managed identity is successfully logged into an Azure SQL server :-

As, Sign in logs are only available for 30 days in Azure AD, You can save the logs in the storage account every month by following the steps below :-
Click on Export Data settings above SignIn Logs page or Diagnostics Settings> Add diagnostics Settings > Select the required logs > Archive to Storage account > Select your storage account from Azure AD page like below :-

OR

Now, all your sign in and managed identity logs will be stored and populate in your storage account like below:-

Reference :-
How long does Azure AD store reporting data? - Microsoft Entra | Microsoft Learn


text:
Q: Laravel Sanctum Vue I have some problems authenticating an user with Laravel Sanctum.
I have installed everything as needed, with Vite and Vue 3 as a frontend.
So here is the problem... when I login with laravel default auth everything is fine, and when I create request from Vue frontend like:
const AxiosInstance = axios.create({
            headers: {
                Accept: "application/json",
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json",
                "X-Requested-With": "XMLHttpRequest",
            },
            baseURL: "http://127.0.0.1:8000/",
            withCredentials: true,
        });

The real problem is, when I try to get the user, it will always return Unauthenticated:
const user = async() => {
            await AxiosInstance.get('api/user')
        }

So User will be unauthenticated even if it's created directly from axios. I'm checking when user is logged in, and laravel will recognize something like:
        @guest

Welcome guest

        @else

Welcome user

        @endauth

But why api/user is not authenticated?

A: It because laravel scantum use Bearer token
Just change you axios instance like This
import axios from "axios";

const token = localStorage.getItem('auth_token')
 const api = axios.create({
    baseURL: 'http://127.0.0.1:8000/api/v1/',
    timeout: 1000,
    headers: {
        'Accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
  });

  export default api

I hope its helps you


text:
Q: Is it possible to retain ViewBag value from one to another page in MVC? I want to pass ViewBag value from one page to another. Currently, When I move to another page, the value is getting lost. Can anyone please suggest me how to retain the value after page reloads.
This piece of code is inside Home Controller and also added into its Index Page. But when I move to another page, the value is getting lost.
 ViewBag.CounryName = "USA";

A: you can refer following post.
TempData keep() vs peek().
If you still have problem then you can use Session instead of viewbag.


text:
Q: MongoDB C# 2.0 - LINQ query alternative to AsQueryable Here's what my model looks like
public class Bios
{
    [BsonId]
    public ObjectId Id { get; set; }
    [BsonElement("init")]
    public string Init { get; set; }
    [BsonElement("name")]
    public string Name { get; set; }
}

With MongoDB C# driver 1.10, I'm able to do the following and get the right results.  I get a string list of initials.
private static IEnumerable<string> InitList(MongoCollection mongoCollection)
{
    return mongoCollection.AsQueryable<Bios>().Select(b => b.ResAnInit);
}

However, I upgraded the driver to 2.0.1 and tried to get the same results.  With the help of Resharper, I modified the method to this:
private static async Task<IEnumerable<string>> InitList(IMongoCollection<Bios> mongoCollection)
{
    return await mongoCollection.Find(x => x.Init != null)
        .Project(Builders<Bios>.Projection.Include(y => y.Init).Exclude("_id"))
        .ToListAsync();
}

I get errors now.  How can I fix this to do what I did with C# driver 1.10?


text:
Q: Finding DataGridColumn from Header Template How can I find the DataGridTextColumn from the HeaderTemplate template? Is there a way to perform this using only XAML? I have tried FindAncestor of type DataGridTextColumn but it is not found.
I know DataGridTextColumn is not part of the visual tree. Is there any workaround for this?

A: Do you really need the whole column object? The DataContext will be whatever you pass in as header, e.g.
<DataGridTextColumn Header="Name" Binding="{Binding Name}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" Foreground="Red" />
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

This will cause a red header with the text "Name".
If you actually need the column you could use an ElementName binding:
<DataGrid ItemsSource="{Binding Data}">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="nameColumn" Header="Name" Binding="{Binding Name}">
            <DataGridTextColumn.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Foreground="Red">
                        <Run Text="{Binding Mode=OneWay}" />
                        <Run Text=" - " />
                        <Run Text="{Binding ActualWidth, ElementName=nameColumn, Mode=OneWay}" />
                    </TextBlock>
                </DataTemplate>
            </DataGridTextColumn.HeaderTemplate>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

This shows "Name" and the column width in the header.

A: Accessing the column by index in the datagrid using find ancestor works.
<DataGrid ItemsSource="{Binding Data}">
<DataGrid.Columns>
    <DataGridTextColumn x:Name="nameColumn" Header="Name" Binding="{Binding Name}">
        <DataGridTextColumn.HeaderTemplate>
            <DataTemplate>
                <TextBlock Foreground="Red">
                    <Run Text="{Binding Mode=OneWay}" />
                    <Run Text=" - " />
                    <Run Text="{Binding Columns[0].ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Mode=OneWay}" />
                </TextBlock>
            </DataTemplate>
        </DataGridTextColumn.HeaderTemplate>
    </DataGridTextColumn>
</DataGrid.Columns>


text:
Q: How does session data get passed from page to page? For example, I start a session on index.php which has my form. In my form I have a name input and a submit button. I create this code:
$_SESSION['name'] = $_POST['name'];
header('Location: page.php');

On page.php I start the session and display the message

Thank you <?php echo $_SESSION['name'];?>, for signing up.

How is that posted name data passed to page.php?

A: In the context of http, sessions are a way of passing data between pages/requests as http is stateless.
How does the page know of the values in your example? Because they are stored in session variables and available through the request.
For background see:
https://www.w3schools.com/php/php_sessions.asp
What is session and session variables?
http://php.net/manual/en/reserved.variables.session.php
https://en.m.wikipedia.org/wiki/Session_(computer_science)#Web_server_session_management


text:
Q: App crashes while entering background mode in iOS 7.1 Today, I upgrade my Xcode to the latest version(Version 5.1 (5B130a)) to support iOS 7.1. After doing this, I run my project in Xcode as usually. Then app crashes while entering background mdoe. I didn't change any code before upgrading iOS SDK. The code is running perfectly in iOS 5.x, 6.x, 7.0.x.
When app is entering background mode, it doesn't do anything as the following code:
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // do nothing
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

After tracing the crash log, I found the crash point is on the highlighted line in the following screenshot:

any idea?
BTW, the project is using non-ARC mechanism. And view controllers are initialized by storyboard.

A: Looks like you are accessing something that has been released (guess based on your crash).
Enable zombies and this will tell you if you are and what the offending object is.
Product > Scheme > Edit Scheme
Then click on 'Run YOURPROJECT > Diagnostic > enable zombie objects
Then re-run and close it, see if the crash in the debuggers changes ...

A: *

*Go to the "Break point Navigator"

*left click on "Add a new Break point" at the bottom of the project navigator (left bottom)

*Click on "Add Exception Break point"

Now Run the project , you will get the exact point where you are getting the crash.

A: finally, I know what happenes.
I get a table view controller like this:
@interface UserMenuViewController : UITableViewController<UITableViewDataSource, UITableViewDelegate> {
    ....
}

in the following method, I create an UIButton component in the table view cell by using [UIButton buttonWithType:] methods. After inserting the button to cell, I release it. But I shouldn't do this, because it's a mistake. So, the UIButton object seems become chaos while app is going to enter background mode. After I marked the release code, it works fine now. ^^
But I still don't know why it is okay while running in iOS 5.x, 6.x and 7.0.x. It should crash too in those environments.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
if( row == 5 ) {
    BOOL bDidLogin = NO;
    NSString *fileName = bDidLogin? @"btn_logout.png":@"btn_login.png";
    SEL callback = bDidLogin? @selector(doLogout:):@selector(doLogin:);
    UIImage *img = [UIImage imageNamed:fileName];
    UIButton *btn = [Utils generateImgButton:img withHandler:self withCallback:callback withBgColor:[UIColor clearColor]];
    float x = cellWidth - btn.frame.size.width - padding*2;
    float y = cellHeight - btn.frame.size.height - padding*2;
    [Utils moveView:btn toX:x toY:y];
    [cell.contentView addSubview:btn];
    [btn release]; // should not do this!!!!!!!!!!!!!
}
....
}

in Utils.m:
+ (UIButton *) generateImgButton:(UIImage *)img withHandler:(id)handler withCallback:(SEL)callback
                 withBgColor:(UIColor *)bgColor {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:bgColor];
[button setImage:img forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, img.size.width, img.size.height);
[button addTarget:handler action:callback forControlEvents:UIControlEventTouchUpInside];
return button;
 }


text:
Q: Use 'add_theme_support' instead of 'add_custom_image_header' In WordPress 3.4 I am debugging my theme using Debug Bar plugin, which is showing me this error (among a few others):

Notice: add_custom_image_header is deprecated since version 3.4! Use add_theme_support( 'custom-header', $args ) instead.

Okay, clearly, it says I need to use this instead of this. The question is, add_custom_image_header has three parameters, namely:

*

*$header_callback

*$admin_header_callback

*$admin_image_div_callback

How do I represent them in add_theme_support function? Like this?
$aahan_custom_header_args = array(
    'wp-head-callback'       => '',
    'admin-head-callback'    => '',
    'admin-preview-callback' => '',
);
add_theme_support( 'custom-header', $aahan_custom_header_args );

Also, are wp-head-callback, admin-head-callback, and admin-preview-callback, the exact replacements for $header_callback, $admin_header_callback, and $admin_image_div_callback respectively?

A: Please read Updating Custom Backgrounds and Custom Headers for WordPress 3.4.
Custom Headers
Old method:

// Define default header image constant
define( 'HEADER_IMAGE', get_template_directory_uri() . '/images/headers/default.jpg' );
// Define header image width constant
define( 'HEADER_IMAGE_WIDTH', 1000 );
// Define header image height constant
define( 'HEADER_IMAGE_HEIGHT', 198 );
// Define header text constant
define( 'NO_HEADER_TEXT', false );
// Define header text color constant
define( 'HEADER_TEXTCOLOR', '000' );
// Turn on random header image rotation by default.
// Requires HEADER_IMAGE to be null
add_theme_support( 'custom-header', array( 'random-default' => true ) );

// Add Theme support
add_custom_image_header( $wphead_cb, $adminhead_cb, $adminpreview_cb );

New method:

add_theme_support( 'custom-header', array(
    // Header image default
    'default-image'         => get_template_directory_uri() . '/images/headers/default.jpg',
    // Header text display default
    'header-text'           => false,
    // Header text color default
    'default-text-color'        => '000',
    // Header image width (in pixels)
    'width'             => 1000,
    // Header image height (in pixels)
    'height'            => 198,
    // Header image random rotation default
    'random-default'        => false,
    // Template header style callback
    'wp-head-callback'      => $wphead_cb,
    // Admin header style callback
    'admin-head-callback'       => $adminhead_cb,
    // Admin preview style callback
    'admin-preview-callback'    => $adminpreview_cb
) );

Again: that was easy, wasn't it?
Just to clarify, here are the old-constant/new-array-key equivalents:

HEADER_IMAGE       => 'default-image'
HEADER_IMAGE_WIDTH  => 'width'
HEADER_IMAGE_HEIGHT => 'height'
NO_HEADER_TEXT      => 'header-text'
HEADER_TEXTCOLOR    => 'default-text-color'

All of the same callbacks are supported, exactly as before.
For reference, here is the complete defaults array:

$defaults = array(
    'default-image' => '',
    'random-default' => false,
    'width' => 0,
    'height' => 0,
    'flex-height' => false,
    'flex-width' => false,
    'default-text-color' => '',
    'header-text' => true,
    'uploads' => true,
    'wp-head-callback' => '',
    'admin-head-callback' => '',
    'admin-preview-callback' => '',
);


text:
Q: Why do I lose formatting after running javascript? This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

Title

    <input type="text" id="userInput"></input>
    <button onclick="test()">Submit</button>

A: If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;

For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.

A: Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
    {
        var nam= document.getElementById("userInput").value;
        var l = nam.length;
        var pocz = nam.slice(0,1);
        var kon = nam.slice(-1);
        document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
            var one = nam.slice(-1);
            if (document.getElementsByClassName("spantext").length===0)
            {
            var text=document.createElement("span");
    text.setAttribute("class","spantext");
            document.getElementsByTagName("body")[0].appendChild(text);
            }
            else {
            var text=document.getElementsByClassName("spantext")[0];
            }

            if (one == "a") {
               text.innerHTML=nam.slice(0,-1) + "bbb";
            } else {
               text.innerHTML=nam + "ccc";
            }

    }

fiddle


text:
Q: Implemented AbstractUser: adminsite page can not grant permission to user My model (MyUser) implements AbstractUser.
This is my model.py file:
class MyUser(AbstractUser):
   degree = models.IntegerField(verbose_name=u'degree',default=1)
   country=models.CharField(max_length=15,verbose_name=u'country')
   addr=models.CharField(max_length=30,verbose_name=u'address of user')

but, the adminsite page does not give permission to user. What is the issue here?
Find attached figure here.


text:
Q: How to extend multiple mixins in the same Polymer element? I am updating my Polymer App to 2.0, while trying to get familiar with the new concepts.
I would like to extend two mixins: DatastoreBehaviors and FacebookBehaviors in my Polymer element, but I can't figure out how to proceed:
element:
  class AppFeed extends DatastoreBehavior(Polymer.Element) {

      static get is() { return 'app-feed'; }

      ...

}

mixins 1:
const DatastoreBehaviors = (superClass) => class extends superClass {

    ...
}

mixins 2:
  const FacebookBehaviors = (superClass) => class extends superClass {

    ...
}

A: Multiple inheritance can be achieved in Polymer in following way
class AppFeed extends DatastoreBehavior(FacebookBehaviors(Polymer.Element)) { … }

which will create inheritance hierarchy like
AppFeed <= DatastoreBehavior(FacebookBehaviors(Polymer.Element)) <=
FacebookBehaviors(Polymer.Element) <= Polymer.Element

You can also refer documentation.


text:
Q: How can I debug this webclient exception? I am trying to pull a simple RSS feed for an Android App with this code:
public async Task<IList<Episode>> PullEpisodesAsync(int page)
    {
        string xmlFeed = "";

        try
        {
            using (WebClient wc = new WebClient())
            {
                var uri = new Uri(Const.FeedEndpoint);  // http://spotlightenglish.com/feeds/appfeed/
                xmlFeed = await wc.UploadStringTaskAsync(uri, "GET", "");
            }

        }
        catch (System.Net.WebException wex)
        {
            Console.WriteLine("WebExceptionStatus: {0}", wex.StackTrace);
        }

        IList<Episode> episodes = ParseFeed(xmlFeed);

        return episodes;
    }

I get a runtime exception that doesn't give me much to go on:

WebExceptionStatus:   at
  System.Net.WebClient+c_async15.MoveNext ()
  [0x00000] in :0     --- End of stack trace from
  previous location where exception was thrown ---   at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()
  [0x00000] in :0    at
  System.Runtime.CompilerServices.TaskAwaiter`1[System.String].GetResult
  () [0x00000] in :0    at
  Spotlight.EpisodePoller+c_async1.MoveNext ()
  [0x000e2] in
  /Users/Jannie/Workshop/SpotlightEnglish/Elements/EpisodePoller.cs:52
  [spotlight] Web exception: An error occurred performing a WebClient
  request.

I am not behind a proxy or a firewall, can browse the feed url via the test device and have Internet access specified in my app manifest.
Any pointers on how to start debugging this will be greatly appreciated.

A: The following code with HttpClient works for me:
using (var client = new HttpClient())
{
    var url = "http://spotlightenglish.com/feeds/appfeed/";
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml"));
    var msg = await client.GetAsync(url);
    if (msg.IsSuccessStatusCode)
    {
        var xml = await msg.Content.ReadAsStringAsync();
        // do whatever with xml from here
    }
}

Also your code seems to be a bit wrong. Why are you Uploading something to the server rather than Downloading?


text:
Q: How to create this selector I want create a selector like this on clicking on a div it must show other options like in image and after selecting another option it must show the selected value in div.

this image is from  Google translator

A: You can do something like this:

    From: LANGUAGE

OPTION

OPTION

OPTION

OPTION

OPTION

OPTION

JsFiddle: http://jsfiddle.net/9bzkM/8/
Should work.

A: See this: Sample
$(document).ready(function () {
  $("#lang-from").click(function () {
    $("#lang-content").slideToggle(350);
  });

  $("#lang-content li").click(function (e) {
    e.stopPropagation();
    $("#lang-content").slideUp(350);
    $("#lang-from span").text($(this).text());
  });

});


text:
Q: Dango admin throws empty exception when calling __str__ method I'm developping a web app with Django (2.2).
I have the following Profile model extending the built-in User model trough an One-to-one relationship.
class Profile(models.Model):
    class Meta:
        ordering = ['user__last_name']

    txt = models.CharField("TXT", max_length=5, null=True, blank=True, unique=True)
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    colleague = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True)

    def __str__(self):
        """ Display of User with its full name"""
        return "%s %s" % (self.user.last_name.upper(), self.user.first_name.capitalize())

The __str__ method works well in the Admin list display view or in a Django shell.
However, an exception is thrown when I try to access to the admin form, pointing to the __str__ method but without any detail.
When the __str__ method is removed the form is displayed correctly.
Here is the ModelAdmin
class ProfileAdmin(admin.ModelAdmin):
    readonly_fields = ('get_last_name','get_first_name',)

    fieldsets = [
        ('User',
         {'fields': ['get_last_name', 'get_first_name','txt', 'colleague']}),
    ]
    #Sélection des champs à afficher dans la vue liste
    list_display = ('__str__','get_poste','txt', 'colleague ')

    #Champ de recherche
    search_fields = ['user__first_name',
                     'user__last_name',
                     ]

    #calculate fields for list_display
    def get_last_name(self, obj):
        return obj.user.last_name
    def get_first_name(self, obj):
        return obj.user.first_name

    #Define description of fields for list_display
    get_last_name.short_description = 'Name'
    get_first_name.short_description = 'Firstname'

    #Enable sorting on calculated fields
    get_last_name.admin_order_field = 'user__last_name'
    get_first_name.admin_order_field = 'user__first_name'

Any advice to solve this issue would be appreciated

A: It's because the object does not have a first_name and last_name yet, thus you are calling null.upper() and null.capitalize(). Try to handle that inside the __str__ function.

A: I finally got around the problem by adding a field name to the profile model, updating it automatically trough a custom .save() method and returning it with __str__ :
class Profile(models.Model):
    class Meta:
        ordering = ['user__last_name']

    txt = models.CharField("TXT", max_length=5, null=True, blank=True, unique=True)
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    name = models.CharField("Name", max_length=200, null=True, blank=True)
    colleague = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.name = self.user.__str__()
        return super(Profile, self).save(*args, **kwargs)

    def __str__(self):
        """ Display of User with its full name"""
        return self.name

I also customized User str method according to Django: Customize the User model's return field
from django.contrib.auth.models import User

def get_fullname(self):
    return "%s %s" % (self.last_name.upper(), self.first_name.capitalize())

User.add_to_class("__str__", get_fullname)

Thanks for taking the time to respond


text:
Q: scrolling issue with -webkit-overflow-scrolling:touch I am using Phonegap 2.5 for the iPhone application.I am also using query mobile. Its giving scrolling issue when I use -webkit-overflow-scrolling: touch;
Here are the screenshots:

and after scrolling content disappears:

Header and footer are fixed.
this is the code I am using for the div which is scrolling div:

when I remove -webkit-overflow-scrolling: touch; the content doesn't disappear but it doesn't scroll like native.
I can't figure it out what is the problem?
UPDATE: It works fine on ios 6 simulator. screenshots are of iOS 5 device.

A: Couldn't see your html markup though, try to call this script...
Give id to your popup div.
HTML

JQUERY
$(document).ready(function(){
    $('#yourBox').trigger("create");
});


text:
Q: Google Maps Javascript Hyperlink I need to embed a map into an HTML widget and I have got some code which works perfectly. I even understand a little bit of the code as I am a JavaScript newbie.
What I need is to be able to add a hyperlink into the info window for each marker. So if I were to click on say "Australia 1" or "Australia 2" if would open up the appropriate webpage. Just to complicate things I need the equivalent of

The code I am using works well and is below!


text:
Q: Proof that the exponential function is continuous on $\mathbb{R}$ without use of derivatives I am still trying to understand how to prove statements. I want to prove that for $a>0$, $f(x) = a^x$ is continuous on $\mathbb{R}$. The text gives an hint, namely, that it suffices proving continuity at 0.
Now, using the definition of continuity of a function, am I wrong if I write:
IF $|a^x - 0| < \epsilon$,  THEN $|x-0| < \delta$
If I have got something, I have to find an equation which relates epsilon and delta, which satisfies the definition. Actually, I ask this question because I am still not sure if I have understood how to prove using the formal definition of limit and continuity of a function.
PS. I want to prove the statement without making use of derivatives or even more complex arguments.

A: Your definition is wrong.
Note that , for $a >0$, we have $a^0=1$ , so to prove the continuity of the function at $x=0$ you have to show that:

For all $\epsilon >0$ there is a $\delta >0$ such that  $$
 |x-0|<\delta \Rightarrow |a^x-1|<\epsilon$$

Can you do this?

The  point is to show that the solution of the inequality
$(1) \qquad|a^x-1|<\epsilon$
is $|x|<\delta$ for some $\delta >0$.
So we can start solving $(1)$ and this require a bit of attention. The first step is to eliminate the absolute value, so we have to find where $a^x-1>0 \iff a^x>1$. The solution of this inequality is different for $a>1$ or $a<1$ ( the case $a=1$ is trivial). For $a>1$ we find the solution $x>0$, for $a<1$ we find $x<0$.
Consider the case $a>1$. The inequality $(1)$ becomes the two systems
$$
\begin{cases}
x>0\\
a^x<1+\epsilon
\end{cases}
\quad \lor \quad
\begin{cases}
x<0\\
a^x>1-\epsilon
\end{cases}
$$
Now we can solve these systems (using logarithms), and find that the solution is a neighborhood of $0$.
For the first system we have:
$$
a^x<1+\epsilon \iff e^{x\ln a}<e^{\ln(1+\epsilon)} \iff x\ln a<\ln(1+\epsilon) \iff x<\frac{\ln(1+\epsilon)}{\ln a}
$$
( note that $\ln a>0$ since $a>1$), so the solution is:
$$
0<x<\frac{\ln(1+\epsilon)}{\ln a}
$$
In a similar way we solve the second system and we find
$$
\frac{\ln(1-\epsilon)}{\ln a}<x<0
$$
so the solution of $(1)$ for $a>1$ is
$$
\frac{\ln(1-\epsilon)}{\ln a}<x<\frac{\ln(1+\epsilon)}{\ln a}
$$
and we can chose
$$\delta=\mbox{Min}\left(\left|\frac{\ln(1+\epsilon)}{\ln a}\right|,\left|\frac{\ln(1-\epsilon)}{\ln a}\right|\right)$$
Than we have to do the same for the case $a<1$.


text:
Q: how to appending write audio frame use ffmpeg ?
*

*I found that ffmpeg has a concat protocol that can be used to splice/merge multiple audio files, but it has a param ouput file, that is, a new production to a target file; But I want to have a pattern added to the source file, just like the behavior of the fopen when mode = "a": Appends to a file. Writing operations. End of the file.

*Is there a direct way to do this?
FILE *fopen (const char *filename, const char *mode)


text:
Q: Passing parameters to get request in django template I'm trying to create a link to a page in django via a GET request. But, I have to pass the value of a parameter. How do I do so?
urls.py
path('questions/<int:user_id>/', views.recommendationquestions,{'template_name':'questions.html'}, name = 'questions'),

answers.html
Rate more movies

A: You can't nest {% and {{. With {% your variables are available without the need of {{. Your code should be:
Rate more movies

also note the user_id= because your URL parameter is named.


text:
Q: Problems installing imagemagick Im trying to start my first refinery cms project, and am already having trouble. I am trying to get imagemagick going, and am getting errors. I looked on stackoverflow about changing permissions to my profile, or the directories that have problems, also uninstalling and reinstalling, but so far no luck. I was hoping maybe someone could walk me through fixing this. Thanks so much.
 Mac-Pro:local user$ brew install imagemagick
 Error: You must `brew link jpeg' before imagemagick can be installed
 Mac-Pro:local user$ brew link jpeg
 Linking /usr/local/Cellar/jpeg/8d...
 Error: Could not symlink file: /usr/local/Cellar/jpeg/8d/bin/wrjpgcom
 /usr/local/bin is not writable. You should change its permissions.

A: After encouragement, here's my comment to the question as an answer.
The problem is that the directory Homebrew is trying to use isn't writable by the user running brew. To fix this, make the directory writable by that user.
sudo chown -R yourusename:admin /usr/local/bin

This recursively changes the ownership of all objects inside the /usr/local/bin directory to the user called yourusername. It assumes that your user is in the OS X administrator group.
If you're not sure of the username of your user, you can run the command whoami.


text:
Q: Have Bash to parse multiple space-contained words connected by escape char \ How within a string, can we have Bash to parse multiple space-contained words connected by escape char \, by the simplest way (1-2 commands/lines) ?
s="English phrases must be understood are as\ well, even\ if, as\ such"

How to achieve kind of in few variables (or enclosed by quote pair instead of double quote):
a="English"
b="phrases"
c="must"
d="be"
e="understood"
f="are"
g="as well,"
h="even if,"
i="as such"

or as array of s variable itself, etc.  Please guide to the correct path.

A: read -a arr <<< "$s"

read relies on IFS split words. If you have modified that variable,
prepend IFS=' ' to the command above.
$ for i in "${arr[@]}"; do echo "$i"; done
English
phrases
must
be
understood
are
as well,
even if,
as such


text:
Q: XQUERY: reutrn values from different tags using xquery I´m starting using xquery and I want to know how to get the values from 2 different type of tags.
for example:
xml
<elementType>value</elementType>
<otherElementType>value</elementType>
<elementType>value</elementType>
<elementType>value</elementType>

xquery
"for $b in $doc//elementType return stringg($b)"
"for $b in $doc//otherElementType return stringg($b)"

I want this but only using one query, how can that be done?

A: Use what is possibly the shortest expression:
//*[self::elementType or self::otherElementType]/string()


text:
Q: Applepay - canMakePaymentsUsingNetworks returns NO for the first time app runs. [ApplePayManager canMakePaymentsUsingNetworks] returns NO when i try to run the app from xcode on the device with ios 9.0

A: Have updated Xcode to 7.3 and running on device with iOS 9.3. This issue got fixed for me.


text:
Q: Getting AttributeError: module 'mysql' has no attribute 'connector' in python I am on windows 10 and using python3.9.
I installed the pagkage
>python3 -m pip install mysql-connector-python
Now I try to run a simple program
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="pythonDB"
)
mycursor = mydb.cursor()

mycursor.execute("SELECT * FORM customers")

myresult = mycursor.fetchall()

for x in myresult:
    print(x)

I am getting the following error when running
>python3 select.py
Traceback (most recent call last):
File "G:\Python_w3school\mysql\select.py", line 1, in
import mysql.connector
File "C:\Users\pawar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\mysql\connector_init_.py", line 42, in
import dns.resolver
File "C:\Users\pawar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\dns\resolver.py", line 20, in
import socket
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\socket.py", line 54, in
import os, sys, io, selectors
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\selectors.py", line 12, in
import select
File "G:\Python_w3school\mysql\select.py", line 3, in
mydb = mysql.connector.connect(
AttributeError: module 'mysql' has no attribute 'connector'

A: try these:
AttributeError: module 'mysql' has no attribute 'connector'
Attribute error:module 'mysql' has no attribute 'connector'
basically change the import to
from mysql import connector

A: Seems like the Python3 is not taking SQL directly inside the execute function.
Assign the query to a variable and pass it to the execute() function.

It worked for me!!!

sql = "SELECT * FROM customers"
mycursor.execute(sql)

Also try try renaming the file if it is something like select.py to select_customers.py


text:
Q: RLC Circuit and 2nd order linear DE An RLC circuit consists of a voltage source in series with a resistor, a capacitor, and an inductor. An inductor is a coil of wire. When the current passing through the coil changes, a magnetic field is generated that induces a voltage across the inductor. With current $i(t)$, the voltage drop across the inductor is given by $L\frac{di}{dt}$ where $L$ is the inductance of the inductor, measured in henries.
(a) Use Kirchhoff's voltage law to determine the 2nd order differential equation that describes the charge q on the capacitor of the circuit.
(b) Suppose that $R = 50$ ohms, $L = 0.1$ henries, and $C = 5 × 10^{-4}$ farad. At time, $t = 0$, when the charge $q$ and the current $i = \frac{dq}{dt}$ are zero, and a voltage source of $110 V$ is connected. Describe the charge on the capacitor as a function of time.
I never learnt anything about Kirchhoff's law, but could anyone give me any tips on where to start?
Thanks!

A: Are you an engineering student? If so, be sure to check out this video:https://www.youtube.com/watch?v=WBfAEeEzDlg
Applying what is being said in the video we end up with the general solution for the current in the series circuit: $$\frac{V'}{L}\left ( t \right )=i\frac{1}{LC}+i^{'}\frac{R}{L}+i^{''}$$
Important note: The coefficients on the right side of the above equation remain the same no matter what variable you're solving for. However the input signal on the left hand side, in general, will vary. Go try yourself and set up an ode for the voltage drop on the resistor.


text:
Q: copy data from one table to another table with defferent column Hi I create a table but when i try to get data from it I find many probleme so I create another table and i try to cpy the column t1m1 and t1m2 from the first table into column loc_awa from the 2nd table and separate them with a '_' and rt1m1 rt1m2 into score and so on
but when i run the php page i get this error

"Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'match VALUES
  ('1','IRT_MAS','2_0')' at line 1' in C:\wamp\www\fantasy\temp.php on
  line 19"

--Table1--

--Table1--

jawla_id Croissant 	m1t1 	rm1t1 	m1t2 	rm1t2 	m2t1 	rm2t1 	m2t2 	rm2t2 	m3t1 	rm3t1 	m3t2 	rm3t2 	m4t1 	rm4t1 	m4t2 	rm4t2 	m5t1 	rm5t1 	m5t2 	rm5t2 	m6t1 	rm6t1 	m6t2 	rm6t2 	m7t1 	rm7t1 	m7t2 	rm7t2 	m8t1 	rm8t1 	m8t2 	rm8t2

1 	IRT 	2 	MAS 	0 	KAC 	0 	DHJ 	0 	FUS 	2 	RCA 	0 	WAC 	4 	FAR 	2 	RSB 	0 	OCK 	0 	HUSA 	2 	CRA 	1 	KACM 	2 	MCO 	0 	OCS 	1 	MAT 	0

2 	CRA 	1 	IRT 	0 	RCA 	1 	KACM 	1 	MAS 	1 	FUS 	1 	FAR 	1 	OCS 	1 	MCO 	1 	KAC 	0 	DHJ 	0 	RSB 	1 	OCK 	1 	WAC 	3 	MAT 	2 	HUSA 	4

3 	OCS 	0 	OCK 	1 	IRT 	2 	MAT 	2 	KACM 	0 	MAS 	0 	FUS 	1 	CRA 	1 	KAC 	1 	RSB 	2 	MCO 	0 	RCA 	1 	WAC 	2 	DHJ 	1 	HUSA 	1 	FAR 	0

4 	MAT 	0 	FUS 	3 	RCA 	0 	KAC 	1 	CRA 	1 	KACM 	0 	MAS 	1 	MCO 	2 	FAR 	1 	IRT 	2 	DHJ 	0 	OCS 	0 	OCK 	2 	HUSA 	1 	RSB 	0 	WAC 	0

5 	IRT 	2 	OCK 	1 	KACM 	2 	MAT 	1 	FUS 	2 	FAR 	3 	RCA 	3 	MAS 	0 	KAC 	0 	WAC 	1 	HUSA 	1 	DHJ 	1 	MCO 	2 	CRA 	3 	OCS 	1 	RSB 	0

6 	RSB 	1 	HUSA 	1 	FAR 	1 	KACM 	0 	DHJ 	1 	IRT 	1 	OCK 	1 	FUS 	2 	WAC 	2 	OCS 	0 	MAS 	0 	KAC 	0 	CRA 	0 	RCA 	2 	MAT 	1 	MCO 	1

7 	IRT 	1 	RSB 	0 	KACM 	1 	OCK 	0 	FUS 	0 	DHJ 	0 	MCO 	0 	FAR 	0 	KAC 	2 	OCS 	1 	MAS 	1 	CRA 	0 	RCA 	2 	MAT 	3 	HUSA 	0 	WAC 	1

8 	CRA 	1 	KAC 	2 	OCS 	2 	HUSA 	4 	DHJ 	1 	KACM 	0 	WAC 	2 	IRT 	2 	FAR 	1 	RCA 	0 	MAT 	1 	MAS 	0 	OCK 	1 	MCO 	2 	RSB 	0 	FUS 	1

9 	CRA 	1 	MAT 	2 	IRT 	0 	OCS 	1 	KACM 	0 	RSB 	0 	KAC 	3 	HUSA 	1 	FUS 	1 	WAC 	0 	RCA 	1 	OCK 	2 	MAS 	0 	FAR 	1 	MCO 	1 	DHJ 	0

10 	HUSA 	1 	IRT 	3 	FAR 	2 	CRA 	2 	WAC 	2 	KACM 	0 	DHJ 	1 	RCA 	1 	OCK 	0 	MAS 	3 	RSB 	2 	MCO 	1 	MAT 	1 	KAC 	0 	OCS 	0 	FUS 	1

11 	MAS 	0 	DHJ 	0 	MCO 	1 	WAC 	1 	MAT 	1 	FAR 	1 	RCA 	1 	RSB 	0 	CRA 	1 	OCK 	0 	KAC 	0 	IRT 	0 	KACM 	1 	OCS 	2 	FUS 	2 	HUSA 	0

--Table 2--
jawla_id           loc_awa         score
Here's the code that i use :

<?php
try{
        $host="localhost";
        $datab="nmdatab";
        $user="user";
        $pass="password";
        $conect=new PDO("mysql:host=$host;dbname=$datab",$user,$pass);
        $conect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(Exception $e){
        die('Erreur : '.$e->getMessage());
    }
    $matche=$conect->query('SELECT * FROM jawlat ORDER BY jawla_id');
        while ($mt=$matche->fetch()){
            $jawla_id="".$mt["jawla_id"]."";
            $match="".$mt["m1t1"]."_".$mt["m1t2"]."";
            $score="".$mt["rm1t1"]."_".$mt["rm1t2"]."";
            $nt="INSERT INTO match VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m2t1"]."_".$mt["m2t2"]."";
            $score="".$mt["rm2t1"]."_".$mt["rm2t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m3t1"]."_".$mt["m3t2"]."";
            $score="".$mt["rm3t1"]."_".$mt["rm3t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m4t1"]."_".$mt["m4t2"]."";
            $score="".$mt["rm4t1"]."_".$mt["rm4t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m5t1"]."_".$mt["m5t2"]."";
            $score="".$mt["rm5t1"]."_".$mt["rm5t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m5t1"]."_".$mt["m5t2"]."";
            $score="".$mt["rm5t1"]."_".$mt["rm5t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m5t1"]."_".$mt["m5t2"]."";
            $score="".$mt["rm5t1"]."_".$mt["rm5t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            $match="".$mt["m5t1"]."_".$mt["m5t2"]."";
            $score="".$mt["rm5t1"]."_".$mt["rm5t2"]."";
            $nt="INSERT INTO match  VALUES ('$jawla_id','$match','$score')";
            $conect->exec($nt);
            echo "jawla ".$jawla." done";
        }

?>

A: Match is a reserved keyword you need to escape it using back-ticks
INSERT INTO `match`(col1,col2,col3)
         VALUES ('$jawla_id','$match','$score')