text:
Q: Error type 3 Error: Activity class {} does not exist I have an IntelliJ Android project, that I successfully imported to Android Studio 0.4.0. It works perfectly if I don't change anything in manifest. However, when I want to change the launcher activity and run, it fails with this error:
Launching application: com.trackingeng/LandingActivity.
DEVICE SHELL COMMAND: am start -D -n "com.trackingeng/LandingActivity"
    -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN
    cat=[android.intent.category.LAUNCHER] cmp=com.trackingeng/LandingActivity }
Error type 3
Error: Activity class {com.trackingeng/LandingActivity} does not exist.

When I click Sync Project with Gradle files, it outputs:
Project Sync
The project 'TrackingEng' is not a Gradle-based project

Run settings:

A: On Android 6, when I uninstalled the app it actually went to disabled instead of being removed from device.
Settings > Apps > click on your app and uninstall

A: When I got this problem I always try this solution and it works.
Instant Run disable

Build -> Clean Project

File -> Invalidate Caches / Restart

But I found an exception this once. This solution doesn't work for me. Then I find out the problem is Emulator cash. I just do Wipe data and Cold boot now and the problem is solved.

A: Some times application install on Guest user on your mobile, So try to switch Guest and uninstall the application.
In addition, try to execute the following command to uninstall application
adb uninstall package "Your package Name"

A: I faced a similar problem after refactoring.
This is what i did to resolve this issue:

*

*Cleaned the Project

*Deleted the Build directory

*Restarted Android Studio

*Rebuild the Project

*Run

*Optionally (Go to the files menu on android, click on "Invalidate Caches / Restart..." uninstall the app on your phone and try again)

And everything worked fine!
I think the key is to restart your IDE.
Edit 1:
If the above steps don't work for you, then deleting Gradle cache seems to be a solution, as pointed out by @Yasitha.
Edit 2
As suggested by a couple of users in the comments below, sometimes the issue can be resolved by completely removing and reinstalling the app from your device.
Simply type adb uninstall <package> in terminal to completely remove app from the device.
Edit 3
As mentioned in Abhishek's Answer, one should also try deleting the app from your device in case multiple users are set up on your device.
Simply go to  Mobile Settings > Apps > [Your App] > More > Uninstall App for All Users
Edit 4
As mentioned by Yassin Ajdi, executing the uninstallAll Gradle task can also fix the issue.
You can go to Gradle > Tasks > Install > uninstallAll to get the job done.
UPDATE for Android Studio 2.1 and up
When running Android Studio 2.1 and up you can also encounter this issue when you have the instant run option enabled in your preferences (is enabled by default).
To disable this option go to the Preferences option in the Android Studio top menu and look for Instant Run so you can uncheck the first checkbox on that screen.

Anyway that fixed it for me. Originally pointed out by user @yusufonder. I discovered this was the issue since gradle install still worked.

A: I had the same issue and this is how I fixed it:
Go to Gradle > Tasks > Install > uninstallAll

A: This happens when you do the following

*

*connect your device/emulator

*run the app from Android Studio (AS)

*use/test the app and uninstall it from the device while it is still
connected to your computer

*try to run the app again from AS

AS thinks you still have the app in your device.
tl;dr - To resolve this, you can simply disconnect your device after uninstalling the app and reconnect it.

A: In my case, it was because the app I was trying to launch was installed for a different user on the device. Go to Settings -> Apps (All apps) and and select the app. Click on the overflow menu and select "Uninstall for all users".

A: Be warned that if you have multiple Profiles set on the device, your app might already exist in one of the other Profiles.
Uninstalling the app from all the Profiles resolved the issue for me.

A: I use Android Studio 3.2 Beta 5, faced with the same issue
Go to
File -> Invalidate Caches / Restart...

Solved problem for me

A: File -> Invalidate Caches / Restart

A: For me it was a very specific problem, I've got a Lg g5 to test my application on, and to reset my apps data I uninstalled it on the phone, but the phone has a "nice" feature to don't uninstall apps immediatly so you might can reinstall them within one day.
So the app was installed but not usable(disabled) after removing the app from the phone completely it worked.

A: Just in case anyone runs into my issue and has no luck with the other solutions...
I was trying to start an activity through adb for FireTV while debugging Amazon launcher integration. However, my project had 60 different build variants (multi-platform, multi-app project) and the ApplicationId didn't match any classpath since the runtime package (and classpaths) were different from the applicationId.
I was trying to run
adb shell am start -n com.myappid.example.packageone.packagetwo/com.myappid.example.packageone.packagetwo.MySplashActivity
(Of course I had tried many combinations with com.runtimepath.example  since I had the added challenge of a different applicationId in my build.gradle and another at runtime)
What finally helped was this post https://stackoverflow.com/a/36255727/5970652
Which revealed a different format!
com.myappid.example/com.runtimepath.example.packageone.packagetwo.MySplashActivity
So if you have a different runtime classpath try specifying with the build.gradle applicationId before the slash and the runtime classpath afterwards.
You can also get these values from BuildConfig.APPLICATION_ID and this.getLocalClassName() respectively if you want to log them in logcat.

A: In my case there was next reason:
I have 2 users: me and Guest.
and app was installed on both of them but deleted only at first.
when I switched to Guest screen and delete app from there, app installed ok.
hope this will help someone :)

A: If you have uninstalled the application manually from the device and you have multi user set up, this error could happen. The application needs to be uninstalled from all the users in the device.

A: I have a Samsung Galaxy. Searching in the settings above didn't work because it didn't show up at all in my Apps settings.
I found the application on my phone by typing the name of the app in the search field. I realized it was in the "Work"(using Mobile@Work) profile and removed it. You can find the settings for the profile by going to Settings->Work profile->Apps
I hope this helps somebody who may not find it the same way that many of the other answers stated it could be found in the settings.

A: Faced this problem in android studio 3.5.1 Took me a day to solve this problem,Tried everything including cleaning cache,restart and renaming package name as well. So if any of above did't work than try this.
Just go to gradle > Tasks > Install > UninstallAll
Here is the link:
Error type 3: Activity Class {...} does not exist

A: Gradle -> Tasks -> Install -> Uninstall All.

A: Try this from terminal
gradlew uninstallAll

This will uninstall all the debug, release, apks of all the versions of your app. And re-install the application

A: The App is already installed for Another user. Please try to uninstall the same app for all the user. Then try.
Or you can try after running adb command.
adb uninstall PACKAGE_NAME

where PACKAGE_NAME is the full name such as com.example.myapp

A: Even I had the same problem but none of the above solutions worked for me.
The problem was that, I had froze the particular app which I was trying to run via Titanium Backup due to which I got the above error. I tried both in Eclipse and Android Studio.
After the realization I just uninstalled the app and then ran it again.

A: I'd like to share the trick that helped in my case. I uninstalled the application from the device and nothing of clean/rebuild/Android Studio restart operations didn't help.
Since Android Studio thinks that the application is still installed on the device and doesn't deploy it, you can force the installation using the ADB:
adb install -r <your_application_from.apk>

where -r means reinstall the app, keeping its data.

A: In my case, I actually change the package name, and it started causing this issue.
I have tried many trick but here I am describing what actually worked for me.

*

*Delete your build folder it also includes the clean(so no need to clean it)

*Try to restart android studio if this doesn't work then invalidate the cache too.

*if it still give you error then try to wipe out the data of your emulator, hopefully this will resolve the issue,

Make sure your activity name is correct also make sure the package name is correct in manifest file.

A: Sometimes this happens once you rename the project's root directory, just delete the .idea folder of your project and reopen it with Android Studio.

A: Refactor the activity launcher and change the class name.

A: Follow the below steps:

*

*Clean your Project

*Delete your build directory

*Restart your Android Studio

*Rebuild the project

A: I also faced the same problem somewhere in the past. Such problems actually occurs when we do some refactoring like - renaming, moving files within the project etc. Renaming and Moving files require changes in the gradle file so whenever you rename or move some file just clean the project:

Build -> Clean Project

Cleaning the project just removes the .class files and recompiles the project. Basically, it forces a project rebuild.
Sometimes such types of errors did not cleaned on cleaning project then try to uninstall the app from the device (either it is emulator or physical one) and run the app again. Hope this will help you, it helps me 50% times.
Note:- Whenever you got any error just don't go to google, Clean the project if this not work do what you want to google.

A: I have LG Stylus and in my test phone, application isn't remove permanently. In Settings -> Application I found debug app (which I try install and debug by AS) with adnotation turn-off. When I remove app from my phone, error disappeard.

A: If your app is not installed at device (tested on Android 9) already:

*

*Build apk

*Move apk to device and install it

*Return to Android Studio and press Run to launch app

A: Sometimes when testing on a device, the app doesn't uninstall properly. To verify and fix this:

*

*Go to Settings.

*Go to Apps.

*Select your app. (here, you can verify that your app is not uninstalled properly).

*Open the overflow menu on the top right and select Uninstall for all users.

*Done. Try to install then launch your app again.

A: I had the same error after renaming/refactoring. What I did was add the applicationId property attribute to my build.gradle file, and set its value to the application package.
In build.gradle:
android {
defaultConfig {
    applicationId "com.example.myapp"
  }
}

A: Remove the app in Android machine.
That works for me.

A: I had been playing with Android Work Profiles by making use of the Shelter App - I had copied my own application into the work profile.
I had to remove my app from both the regular profile as well as the work profile, and then the app would launch properly.  Somehow the existing package inside the work profile was getting in the way of the IDE deploy.

A: I resolve the problem by
Edit Condifiguration -> Deploy-> Select default apk
https://i.stack.imgur.com/8xuLG.png

A: In my case i uninstalled application from phone it after that the problem began but, the below command worked for me.
Execute below command in terminal/cmd
adb uninstall <package_name>

package_name something like com.example.applicationname
Then, try to reinstall the application. It should work.

A: Try changing the name of the Activity in your AndroidManifest.xml file.
Right now it says:
<activity android:name="LandingActivity" >

Try either adding a period to the beginning of the Activity's name:
<activity android:name=".LandingActivity" >

Or adding the package name to the beginning of the Activity's name:
<activity android:name="com.trackingeng.LandingActivity" >

It also may be a problem that your package name has only two components separated by periods (your package name is "com.trackingeng"; a more standard package name would be "com.trackingeng.app")

A: This happened to me using react-native run-android because my package name did not match my app ID. Just add --appId YOUR_APP_ID.

A: Follow Steps Below
Go to
Mobile setting > Apps > Your App > More > Hit Uninstall app for all users.
Reason : Because you are having multiple users in your phone and you had uninstalled that app for only one.

A: Go to Build > Rebuild Project

A: I had a version of the app on the device that could not be uninstalled as it was corrupt somehow. I had to factory reset the device.

A: I took reference from @jayeffkay's comment:

I had do delete gradle cache as described here Android Studio gets package name wrong when running .apk

It works for me after I deleted the gradle cache files located in:
/your_proj_directory/.gradle/2.10

2.10 is the gradle version used in my case.

A: Disable instant run for Android Studio (tested on version 2.1.1)

A: I had Error type 3. I managed to fix it by adding the following code below in AndroidMainfest.xml.
    <activity android:name=".GameActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

A: I changed a NDK, and problem was solved.

A: If you're not careful and you're trying to disable something in your app manifest make sure you don't disable the app...
<application
android:allowBackup="false"
android:enabled="true"
...

I accidentally set enabled to "false" instead of allowBackup. Wasted 2 hours searching for a solution.

A: My solution is: close the "instant run" of android studio.
"instant run" can be found with the following steps:
Preferences -> Build,Execution,Deployment -> Instant Run
and then uncheck the checkbox "Enable Instant Run to hot swap...."

A: If your app has only two word package name like[com.example] then all your class must be mentioned with full path in manifest like [com.example.SplashActivity] instead of relative path like[.SplashActivity]
change this and delete all your build folder and re-run app.

A: Go to module settings -> Falvors -> Application id ->
(Add your package name)

A: Just doing a clean build did the trick for me.
To do a clean build, do:
Build -> Clean Project

Then do a build or straight run on device.

A: For me, on Android Studio 3.1.2 on Ubuntu 16.04, I met the same issue.
This happens when my colleague changed the package name, and it is okay on his machine.
Neither clean project nor rebuild project work.
I use Sync project with gradle files button on the top pannel of Android Studio and everything works well.

A: Got to android/app/build.gradle and search for
 buildTypes {
     ....
 }

You might have something like
buildTypes {
    debug {
        ...
    }
    release {
        ...
    }
    customBuildType {
        ...
    }
}

Chose the buildType you want to start and then start the App the following
react-native run-android --variant=[buildType] --appIdSuffix '[buildType]'

So,
react-native run-android --variant=debug --appIdSuffix 'debug'

A: Keep package name same in manifest file and in build.gradle(Module:app).it resolved my problem.

A: I tried same app with different device it worked. Finally I noticed that the application is disabled:

*

*Go to setting/apps (on the phone)

*If it is disabled, remove it

A: This happens when the app has not been uninstalled properly.
Use the below plugin of Android Studio to uninstall the app from the device [in case you were unable to find your app inside the settings of the device]
ADBIdea: https://github.com/pbreault/adb-idea
ADBIdea adds the following ADB commands to Android Studio and Intellij:

*

*ADB Uninstall App

*ADB Kill App

*ADB Start App

*ADB Restart App

*ADB Clear App Data

*ADB Clear App Data and Restart

*ADB Revoke Permissions

*ADB Start App With Debugger

*ADB Restart App With Debugger

There are two basic ways to invoke a command:
Through the Tools->Android->ADB Idea menu
By searching for "ADB" in "Find Actions"

*

*Mac OS X: Cmd + Shift + A

*Windows/Linux: Ctrl + Shift + A

A: I face this problem after rename my package...
so simplest one is go to File-> Invalidate caches/Restart ....

A: That might also happen if you have by mistake two launcher Activity in your AndroidManifest.xml like this:
    <activity android:name=".ActivityA">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".ActivityB">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

Just leave the correct one LAUNCHER Activity

A: Besides the cases that the first upvoted comment provided, there is another case can cause this error: the output apk file cannot be replaced by Android Studio, you can manually delete it and build again, it should work.
If you did not change the output path, the default apk output path is {Your Project Path}/app/build/outputs/apk/debug/app-debug.apk

A: In my case, I don't know why, the smartphone was blocking my app. To solve it I went to Configuration --> Application , found my app and pressed "Unistall". I went to configuration becouse my application was not appearing on menu.

A: The problem occurred due to my Emulator. My emulator was running in SafeMood.
Restarting my Emulator without SafeMood worked. First it was started in SafeMood automatically and problem occurred. Then when I disable SafeMood and restart my Emulator it did the trick!

A: This worked on Android Studio version 4.0.1:

*

*Change my git branch to the master branch

*Return to my own branch

A: I think another reason that issue happen is that it is not fully deleted for all users on the device.
Go to Settings -> Apps - > Your Apps -> Click to the 3 dots on the top right -> Uninstall for all users
It works for me. It happen especially you change the icons of the app or messing around with the AndroidManifest.xml file.

A: For me, the problem was that AndroidStudio thought that the app was still on the device.
To fix it:

*

*restart the adb daemon; in a terminal or command prompt, enter:
adb kill-server
adb start-server

*try to launch your app.

*if it still doesn't work, check out this answer.
make sure the platform-tools of the Android SDK is added to your system path variables!

A: I would face this problem when uninstalling the app via the device (i.e. dragging the app to the "Uninstall" option). But here is the proper way to uninstall:
Use the ./gradlew uninstallAll command. This will prevent the Error: Activity class {HomeActivity} does not exist. error.
Update:
If you're lazy you can use the abbreviation for this task:  ./gradlew uA.
Or define aliases for common gradle tasks in your .bash_profile, doing so will save time, typing, and you won't have to remember every command nor worry about typos. I suggest doing this.

A: Below command worked for me. Sometime partial uninstallation of the app also causes this.
Execute below command in terminal/cmd
adb uninstall <package_name>

Then, try to reinstall the application. It should work.

A: As others have noted, this problem can be caused by an attached device/emulator while uninstalling the app and AS connection still exists.  On my end, I just delete all the build folders (under app and project dirs) in the project, and relaunch the application on the device/emulator.

A: Check if you are building hidden version. That's intended behavior for hidden app.
If you want to build regular version, you need to change Build Variant in Android Studio Build > Select Build Variant, change it to regular.

A: If you create a new project from an existing project:
build.gradle
defaultConfig {
        applicationId "xxxxxxxxx" //xxxxxxxxx should be "package name (com.demo.app) from AndroidMenifest.xml"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "3.0.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
}

then click sync in Android Studio

A: I solved it by simply deleting the app -> build  folder and then rebuilding the project. The build folder is automatically recreated after the project is built so there's no risk in deleting it.

A: This fix worked for me:

*

*Remove the installed debug APK from your phone

*In Android Studio, go to Build, choose Build APK(s)

*Put this generated APK on your phone and launch it

*Exit this app and try to debug your app again from Android Studio

A: This usually occurs when you uninstalling the App you are developing. Check whether you have activated the guest account, if so switch the account and uninstall the app, switch back to Admin user (You). and carry on!

A: In my case, I had defined defaultConfig two times.
I don't know why but double check it in case of a mistake.

A: My package name was like "barisciftci.PatternApplier". So changing it to all lowercase solved my problem, so now it looks as "barisciftci.patternapplier".

A: I mistakenly added extra empty <application> tag in AndroidMenifest.xml which was causing this problem.

A: If you are getting this error while developing an instant app then go to Device Settings -> Apps and clear the instant app from device.

A: If you test your app on a smartphone, which has 24 hours secure app remove (like LG G6) you have to uninstall app manually in settings, because it is in bin for 24 hours after uninstalling, so Android Studio thinks that app is installed, but it is in app thrash on your smartphone.

A: Delete the virtual device and re-download it (tested on Android Studio 3.1.3, January 2019).

A: I read all the 'Run' Log and there I saw this line:
"Exception occurred while executing:
android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space"

My problem was, no internal free space to install the app. So, I deleted some files and app get installed successfully.

A: In my case this was being caused by ndk abiFilters when compiling for arm.
To fix it I had to add the following 'splits' section to app/build.gradle's android block:
splits {
    abi {
        enable true //enables the ABIs split mechanism
        reset() //reset the list of ABIs to be included to an empty string
        include "armeabi-v7a", "arm64-v8a", "armv7l"
        universalApk true
    }
}

A: Issue was caused by uninstalling the app while the device was still plugged in.
What happens is the device disables the app rather than removing it.

*

*Go to your app list on your device and uninstall the app from there. You will see that it is currently marked as disabled. This is why you cannot run the app because Android Studio fails to install it as it thinks it already exists.

A: I'm solving simply (don't delete build folder):

*

*deleting all files *.apk in
"\yourapp\app\build\intermediates\split-apk\debug\slices"

*running the app compare a popup message "Application Installation
failed" "Do you want to uninstall the existing application?" click
Ok

*rebuild the project

*run again the project

A: I got this error. What I tried to fix the error (didn't work) were:

*

*Clean Project

*Rebuild Project

*Restart Android Studio

Solution was simple , just uninstall the app on your Emulator/Phone and hit "Run" on Android Studio.

A: I face the same issue and I think the solution is very simple than what I think it was
just go to your manifest and change the package name than copy the same package name into your application iD in the Gradle
defaultConfig { applicationId "your package name here" }
that's it, good luck

A: Check the following in android/app/src/main/AndroidManifest.xml
<application
      android:name="[your_package_name].MainApplication"
   ...>
    <activity
        android:name="[your_package_name].MainActivity"
       ...>

A: I had the same error message when I switched to guest profile in my emulator. I switched back to owner profile and it worked.

A: Check Application id in the Gradle file. I had the same issue because I accidentally changes application id while refactoring views name.

A: For me, there was no space left on your device.

A: The file name of the SharedPreferences must be suffixed with the name of the current flavor to prevent the active compilation variant of a product from accessing the preferences of defined users
for another active compilation with the same preference name.
Although each compilation package is different, it may be that when using flavorDimensions, access to user preferences is being crossed and get the Error type 3 while launching MainActivity
app.getSharedPreferences("${BuildConfig.FLAVOR}_shared_pref_3", Context.MODE_PRIVATE)

GL

A: After all these solve suggestions i still had not solved my this problem. And then i remembered my phone has 2 ANDROID User Interface. One of them is using in casual, another is private things of yours. When i download my projects to phone, downloads both of them. I deleted my project in casual one but had not private one. Everything works fine when i delete the private one. So If you have 2 android ui, you should delete all of them and download again.

A: a simple hack is to rename your package : eg MainActivity to ApplicationMainActivity

A: Had the same error, with a much newer version of Android Studio (version 4.1) . A fresh install of Android Studio + a fresh "basic Activity" template would run into error type 3 for hours. I am on win 10 - my problem was how to kill the gradle cache. A good answer above showed a screen snapshot from gradle, but i didn't find it in Android Studio 4.1. Also the env vars for gradle had not been set , and the commandline for gradle didn't work. So .. here is how it worked finally. I went to C:\Users\myusername\ .gradle. This has subdir "caches". I deleted everything inside. Worked !  I did close Android Studio before, restarted and then it worked nicely.  Ah forgot one thing- i run the device emulator (defauöt device), i.e. no physical device yet.

A: Happen to me when changing app name.. Uninstalled app, switched from debug to release version, installed release and then switched back to debug version and working.

A: I found a way to do this - none of the others worked for me. Click Wipe Data as in screenshot below - it's an issue with the emulator.

A: I solved this issue with the new Android Studio electric eel optional flags when invalidate cache and restart
Go to file - invalidate caches...
Check all boxes, android studio will restart

This worked for me.
If still does not work

*

*Check AndroidManifest for the <activity> tag and change its package name to com.yourpackage.YourActivity

*Check applicationId in build gradle to match your same package

*Go to build - clean project - rebuild project


text:
Q: Getting NullPointerException while picking Picture From Gallery HI i am new to Android and i am trying to save a picture onto a server but as soon as i click on my imageview and get into the gallery and select the picture my App gets crashed and it gives me this Error :

java.lang.NullPointerException: Attempt to invoke virtual method
  'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null
  object reference

My Activity Code :
    public class ProfileActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    private static int LOAD_IMAGE = 1;
    public RadioGroup profileRadioGroup;
    String imagePath;
    private EditText profileName, profileDob;
    private CircleImageView profileImageView;
    private Button profileSave;
    private RadioButton genderMale, genderFemale;
    private String profileGender;
    private boolean doubleBackToExitPressedOnce = false;
    private TelephonyManager telephoneManager;
    private NetworkUtil networkUtil;
    private Bitmap bitmap;
    private SharePrefUtil prefUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        getSupportActionBar().hide();
        networkUtil = new NetworkUtil(getApplicationContext());
        telephoneManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        prefUtil = new SharePrefUtil(getApplicationContext());
        initScreen();
        fillLayout();
    }

    private void initScreen() {
        profileImageView = (CircleImageView) findViewById(R.id.displayprofileimage);
        profileImageView.setOnClickListener(new ButtonClick());

        profileName = (EditText) findViewById(R.id.fed_profilename);
        InputFilter[] FilterArray1 = new InputFilter[1];
        FilterArray1[0] = new InputFilter.LengthFilter(30);
        profileName.setFilters(FilterArray1);

        profileDob = (EditText) findViewById(R.id.fed_profileDob);
        profileDob.setFocusable(false);

        profileDob.setOnClickListener(new ButtonClick());

        profileRadioGroup = (RadioGroup) findViewById(R.id.radioSex);
        genderMale = (RadioButton) findViewById(R.id.gender_male);
        genderFemale = (RadioButton) findViewById(R.id.gender_female);

        profileSave = (Button) findViewById(R.id.btn_profilesave);
        profileSave.setOnClickListener(new ButtonClick());
    }

    private void fillLayout(){
        Log.d("jagteraho","profileImage: "+prefUtil.getValueFromSharePref("profileImage"));
        if(!prefUtil.getValueFromSharePref("profileImage").equalsIgnoreCase("")
                &&!prefUtil.getValueFromSharePref("profileImage").equalsIgnoreCase("null"))
        {
            byte[] encodeByte = Base64.decode(prefUtil.getValueFromSharePref("profileImage"), Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            profileImageView.setImageBitmap(bitmap);
        }
        else{
            profileImageView.setImageResource(R.drawable.profile2);
        }
        if (!prefUtil.getValueFromSharePref("profileName").equalsIgnoreCase("null")) {
            profileName.setText(prefUtil.getValueFromSharePref("profileName"));
        }
        if (!prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("null")) {
            if (prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("male"))
                genderMale.setChecked(true);
            else if (prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("female")) {
                genderFemale.setChecked(true);
            }
        }
        if (!prefUtil.getValueFromSharePref("profileDob").equalsIgnoreCase("null")) {
            profileDob.setText(prefUtil.getValueFromSharePref("profileDob"));
        }
    }

    /**
     * used for display profile picture from the gallery.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {

            bitmap = (Bitmap) data.getExtras().get("data"); //I am Getting Error At This LIne
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(filePathColumn[0]);
            imagePath = cursor.getString(index);
            cursor.close();
            profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        }
    }

    /**
     * save the user profile using the active android database library.
     */
    private void saveProfile() {
        prefUtil.setValueInSharePref("profileName",profileName.getText().toString());
        prefUtil.setValueInSharePref("profileDob", profileDob.getText().toString());
        if (genderFemale.isChecked()) {
            prefUtil.setValueInSharePref("profileGender", "Female");
        } else if (genderMale.isChecked()) {
            prefUtil.setValueInSharePref("profileGender", "Male");
        }
        if(imagePath!=null) {
            prefUtil.setValueInSharePref("profileImage", imagePath);
        }
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

        String date = "" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
        profileDob.setText(date);
    }

    /**
     * used to call gallery, onclick to profile imageView.
     */
    class ButtonClick implements View.OnClickListener {
        public void onClick(View v) {
            switch(v.getId())
            {
                case R.id.displayprofileimage:
                    displayProfileImageClicked();
                    break;
                case R.id.btn_profilesave:
                    btnProfileSaveClicked();
                    break;
                case R.id.fed_profileDob:
                    btnProfileDOBClicked();
                    break;
                default:
                    break;
            }
        }
    }

    private void displayProfileImageClicked(){
        Intent a = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(a, LOAD_IMAGE);
    }

    private void btnProfileDOBClicked() {
        Calendar cal = Calendar.getInstance();

        cal.set(2005, 12, 31);
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                ProfileActivity.this,
                2005, 12, 31
        );

        dpd.setMaxDate(cal);
        dpd.show(getFragmentManager(), "Datepickerdialog");
    }

    private void btnProfileSaveClicked(){

        if (validateProfile()) {
            try {
                if(genderFemale.isChecked())
                profileGender = genderFemale.getText().toString();
                else
                profileGender = genderMale.getText().toString();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "Please select a gender", Toast.LENGTH_SHORT).show();
            }
            if (profileGender == null) {
                Toast.makeText(this, "Please select a gender", Toast.LENGTH_SHORT).show();
            } else {
                if (networkUtil.isConnected()) {
                    profileService();
                } else {
                    android.app.AlertDialog.Builder alertbox = new android.app.AlertDialog.Builder(ProfileActivity.this);
                    alertbox.setMessage("No network connection, Please try after some time");
                    alertbox.create();
                    alertbox.setCancelable(false);
                    alertbox.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
                    alertbox.show();
                }
            }
        }

    }

    /**
     * class provide all the information of user to server and
     * getting a authentication key as response.
     */
    private void profileService(){
        OkHttpClient client = new OkHttpClient();
        String requestURL = String.format(getResources().getString(R.string.service_profileCreate));
        String proImg = null;
        if(imagePath!=null) {
            try {

                File f = new File(imagePath);
                FileInputStream fin = new FileInputStream(f);
                byte[] data = new byte[fin.available()];
                fin.read(data);
                fin.close();
                proImg = Base64.encodeToString(data, Base64.NO_WRAP);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonRequest = new JSONObject();
        try {
            jsonRequest.accumulate("empAuthKey", prefUtil.getValueFromSharePref("authKey"));
            jsonRequest.accumulate("profileImg", proImg);
            jsonRequest.accumulate("name", profileName.getText().toString().trim());
            jsonRequest.accumulate("strDOB", profileDob.getText().toString().trim());
            jsonRequest.accumulate("gender", profileGender);
            jsonRequest.accumulate("mobileNo", prefUtil.getValueFromSharePref("mobileno"));
            jsonRequest.accumulate("imei", telephoneManager.getDeviceId());
        }catch(Exception e)
        {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest.toString());
        Request request = new Request.Builder()
                .url(requestURL)
                .post(body).build();

        final SweetAlertDialog pDialog = new SweetAlertDialog(ProfileActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Saving Please wait ...");
        pDialog.setCancelable(false);
        pDialog.show();

        client.newCall(request).enqueue(new Callback() {
            String status, message;
            Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    if (msg.what == 1) {
                        Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
                    } else if (msg.what == 0) {
                        Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
                    } else if (msg.what == -1) {
                        Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
                    } else if (msg.what == 2) {
                        Toast.makeText(ProfileActivity.this, "System Error Please try again...", Toast.LENGTH_LONG).show();
                    }
                    return false;
                }
            });

            @Override
            public void onFailure(Call call, IOException e) {
                if (pDialog.isShowing()) pDialog.dismiss();
                handler.sendEmptyMessage(2);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseString = response.body().string();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseString);
                        status = jsonResponse.getString("status");
                        message = jsonResponse.getString("message");
                        Log.d("jagteraho", "status: " + status + " message: " + message);

                        if (status.equals("success")) {
                            if (pDialog.isShowing()) pDialog.dismiss();
                            saveProfile();
                            handler.sendEmptyMessage(1);
                            Intent login = new Intent(ProfileActivity.this, LoginActivity.class);
                            startActivity(login);
                            finish();

                        } else if (status.equalsIgnoreCase("failure")) {
                            if (pDialog.isShowing()) pDialog.dismiss();
                            handler.sendEmptyMessage(0);
                            Intent profile = new Intent(ProfileActivity.this, ProfileActivity.class);
                            startActivity(profile);
                            finish();

                        } else if (status.equalsIgnoreCase("error")) {
                            if (pDialog.isShowing()) pDialog.dismiss();
                            handler.sendEmptyMessage(-1);
                            Intent alarm = new Intent(ProfileActivity.this, ProfileActivity.class);
                            startActivity(alarm);
                            finish();

                        }
                    } catch (Exception e) {
                        if (pDialog.isShowing()) pDialog.dismiss();
                        handler.sendEmptyMessage(2);
                        e.printStackTrace();
                    }
                }
            }
        });
    }

}

My Logcat are :
E/CustomActivityOnCrash: App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/file/107745/ORIGINAL/NONE/2008282015 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F107745/ORIGINAL/NONE/2008282015} }} to activity {com.aspeage.jagteraho/com.aspeage.jagteraho.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference

at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
at com.aspeage.jagteraho.ProfileActivity.onActivityResult(ProfileActivity.java:143)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: Try this
/*
 * Capturing Camera Image will lauch camera app requrest image capture
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/*
     * Display image from a path to ImageView
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
            videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);

            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();

            // downsizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                    options);

            imgPreview.setImageBitmap(bitmap);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

A: Change this code :
if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {

        bitmap = (Bitmap) data.getExtras().get("data"); //I am Getting Error At This LIne
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(filePathColumn[0]);
        imagePath = cursor.getString(index);
        cursor.close();
        profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
    }

to this
if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(filePathColumn[0]);
        imagePath = cursor.getString(index);
        cursor.close();
        profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        bitmap = BitmapFactory.decodeFile(imagePath);
    }

Add your variable bitmap at last and set value bitmap = BitmapFactory.decodeFile(imagePath); at the end.

A: Even though you are trying to set the bitmap object at that point, you are not anyways using it anywhere. I think you could remove that line. You are using the image path from the content resolver anyways to get the image. If you still want to store to the bitmap member variable, after you have set the imagepath
bitmap = BitmapFactory.decodeFile(imagePath)

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql - move rows from one table to another If i have two tables that are identical in structure, how can i move a set of rows from 1 table to the other?
The set of rows will be determined from a select query.
for example:
customer table

person_id | person_name | person_email
123         tom           tom@example.com

persons table

person_id | person_name  | person_email

a sample select would be:
select * from customer_table where person_name = 'tom';

I want to move the row from customer table to person table
Ideally removing the data from the original table, but this wouldnt be a deal breaker.

A: INSERT INTO Persons_Table (person_id, person_name,person_email)
      SELECT person_id, customer_name, customer_email
      FROM customer_table
      ORDER BY `person_id` DESC LIMIT 0, 15
      WHERE "insert your where clause here";
DELETE FROM customer_table
      WHERE "repeat your where clause here";

You can also use ORDER BY, LIMIT and ASC/DESC to limit and select the specific column that you want to move.

A: BEGIN;
INSERT INTO persons_table select * from customer_table where person_name = 'tom';
DELETE FROM customer_table where person_name = 'tom';
COMMIT;

A:     INSERT INTO Persons_Table (person_id, person_name,person_email)
          SELECT person_id, customer_name, customer_email
          FROM customer_table
          WHERE "insert your where clause here";
    DELETE FROM customer_table
          WHERE "repeat your where clause here";

A: The answer of Fabio is really good but it take a long execution time (as Trilarion already has written)
I have an other solution with faster execution.
START TRANSACTION;
set @N := (now());
INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY);
DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY);
COMMIT;

@N gets the Timestamp at the begin and is used for both commands.
All is in a Transaction to be sure nobody is disturbing

A: A simple INSERT INTO SELECT statement:
INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';

DELETE FROM customer_table WHERE person_name = 'tom';

A: I had to solve the same issue and this is what I used as solution.
To use this solution the source and destination table must be identical, and the must have an id unique and autoincrement in first table (so that the same id is never reused).
Lets say table1 and table2 have this structure
|id|field1|field2

You can make those two query :
INSERT INTO table2 SELECT * FROM table1 WHERE

DELETE FROM table1 WHERE table1.id in (SELECT table2.id FROM table2)

A: To move and delete specific records by selecting using WHERE query,
BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count=""  And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;

A: These two ways are well to move data from one table to another by deleting the data from the first table. But remember in this case the first table's id which is auto_increment will not rearrange the id so in this case might be if your table has billions of data and still increasing then it might be not right for you:
A simple case with providing a range of id from which you want to move your data:
    INSERT INTO old_authors SELECT * FROM authors WHERE id > 1000;
    DELETE FROM authors WHERE id > 1000;

In case if you want to find data with date range then try this one:
INSERT INTO old_authors SELECT * FROM authors WHERE DATE_FORMAT(added, "%Y-%m-%d") > "2022-05-01";
DELETE FROM authors WHERE DATE_FORMAT(added, "%Y-%m-%d") > "2022-05-01";

Also, use Transection and commit to:
START TRANSACTION;
INSERT INTO old_authors SELECT * FROM authors WHERE DATE_FORMAT(added, "%Y-%m-%d") > "2022-04-24";
DELETE FROM authors WHERE DATE_FORMAT(added, "%Y-%m-%d") > "2022-04-24";
COMMIT;


text:
Q: Filter function not retruning anything in react native  comment.dishID === dishID )} />
"list" in the above case is not showing any values although "comments" has an array also "dishID" is getting set propely. Now "comment.dishID" has values corresponding to value in "dishID"
Not sure why filter function is not working properly


text:
Q: error using rename function in PHP I keep getting this error, although the file still gets moved into the correct directory. Anybody know why i'm getting this error?
Warning: rename(../Images/uploaded/1162504_56863010.jpg,../Images/uploaded/Portraits/1162504_56863010.jpg) [function.rename]: No error in D:\Data\Websites\wamp\www\StephsSite\PHP\addImage.php  on line 21

A: According to the User Contributed Notes to rename(), there are issues on Windows systems when the target file already exists.

*

*try unlink() ing the target file first if it exists

*Alternatively, try copy()

A: One possibility is simply to hide the warning:
error_reporting(E_ALL & ~E_WARNING);
rename($old_name, $new_name);
error_reporting(E_ALL & ~E_NOTICE);


text:
Q: Scraped text is connected, how can I separate? I am scraping plain text from websites but I can't seem to separate the text.
Here is what I mean...
var Horseman = require("node-horseman");
var horseman = new Horseman();

horseman
  .open('http://nickoskitchen.com/')
  .text('.rc-headline')
  .then(function(text){
    console.log(text);
    horseman.close();
  });

The result from running this script ...
admin:~/workspace $ node test4.js
Recipes Inspired By New York City Street Foods10 More Unbelievable Red Velvet Desserts10 Twists On The Deviled EggElevate These 10 Dishes With Earthy Artichoke

See? It's being retrieved as one string but when I .count() I end up getting 4 results.
If someone could please help me with this issue I would be greatly appreciative.

A: The text() method just gets the textual content of the matched selector, so any list style (or any html element/style used to separate the values) you see on the page is lost, and you are left with the garbled text.
There is an npm package you may want to look at if what you want to do is scrape the site for some content. It's called cheerio (jQuery for the server). Add it to your code like this
var Horseman = require("node-horseman");
var cheerio = require("cheerio");
var horseman = new Horseman();

horseman
  .open('http://nickoskitchen.com/')
  .html()
  .then(function(html){
      var $ = cheerio.load(html);
      var headlines = $('.rc-headline');
      headlines.each(function(){
          console.log($(this).text());
      });
      horseman.close();
  });

Hope this helps!


text:
Q: Compound Poisson process and central limit theorem If I have a compound Poisson process
$$Y(t) = \sum_{i=1}{N(t)}D_{i}$$
where $ \{\,N(t) : t \geq 0\,\}$ is a Poisson process with rate $\lambda$, and $ \{\,D_i : i \geq 1\,\}$ are i.i.d random variables with distribution function $G$, which are also independent of $ \{\,N(t) : t \geq 0\,\}.\,$
Then Wikipedia informs me that it has the following properties
$$E[Y(t)]=\lambda t E[D]$$
$$Var[Y(t)]=\lambda t E[D^{2}]$$
which can be shown using Wald's equation. As an aside does anyone have a better source that they would refer me to read about this?
Then if I have a compound Poisson process occurring but I chop it up into $N$ segments of length $\bar{t}$ then I think I have a sequence $\{Y_{1}(\bar{t}), Y_{2}(\bar{t}), Y_{3}(\bar{t}), \dots\}$ where each is it's own compound Poisson process.
Then I think $Y_{i}$ are i.i.d, but does this mean I can use the central limit theorem to say that: provided $\lambda$ is sufficiently large the distribution of $Y_{i}$ should be normally distributed. Any comments appreciated.

A: I think the following shows what you're after. Similar problems/exercises can be found in many texts on probability theory (I guess it's more common in textbooks to consider the limit as time grows to infinity).
By the stationary and independent increments of the Poisson process, together with the independence of the $D_i$'s (amongst themselves as well as with $N$), each $Y_i$ is an independent copy of the random variable
$$Z = \sum _{i=1} ^{N(\bar t)} D_i,$$
where $\bar t >0$ is fixed. Wald's equation (rather, the relations in the original post that follow from Wald's eq.) suggests that for a CLT we want to consider
$$ \tilde Z = \frac{Z - \lambda \bar t E[D_1] }{\sqrt{\lambda \bar t E[D_1 ^2]}}. $$
In order to show convergence to the normal distribution we can use MGF's. Note that the MGF of $Z$ is
$$ \Psi _{Z} (\theta) = E [e^{\theta Z}] = e^{\lambda \bar{t} (\Psi _{D}(\theta) -1)}.$$
It follows that
$$ \Psi _{\tilde Z} = \textrm{exp}\left\{ \lambda \bar t (\Psi _D(\theta / \sqrt{\lambda \bar t E[D_1 ^2]}) - 1) - (\lambda \bar t \theta)/ \sqrt{\lambda \bar t E[D_1 ^2]} \right\}.$$
Under the assumption that the distribution $G$ has a nice enough MGF, Taylor expansion as $\lambda \to \infty$ gives (with some simplifications)
$$ \Psi _D(\theta / \sqrt{\lambda \bar t E[D_1 ^2]}) = 1 + \frac{\theta}{\sqrt{\lambda \bar t E[D_1 ^2]}}E[D_1] + \frac{\theta ^2}{2 \lambda \bar t} + o(1/\lambda), \ \textrm{as } \lambda \to \infty. $$
Inserting this into the expression for the MGF for $\tilde Z$,
$$ \Psi _{\tilde Z} (\theta) = \textrm{exp}\left\{ \frac{\theta ^2}{2} + o(1) \right\}, $$
where the $o$-term is with respect to $\lambda \to \infty$. Hence,
$$ \Psi _{\tilde Z} (\theta) \to \textrm{exp}\{\theta^2 / 2\}, \ \lambda \to \infty,$$
and it follows that $\tilde Z$ converges in distribution to a $N(0,1)$-distributed random variable.
Note that this does not use the independence of the $Y_i$'s. Rather, we just consider the compound Poisson process at a fixed time, i.e., you might as well consider $Y(t)$ for a fixed $t$ and send $\lambda$ to infinity. Therefore, I'm not quite sure if this is really what you are after. Still, hopefully it's helpful in some way.


text:
Q: calling child_process.exec in Node as though it was executed in a specific folder I'm using the following to execute a CLI command in nodeJS
var cp = require('child_process');
cp.exec('foocommand', callback);

However, the foocommand is executing in the current folder node is running from. How can I make it execute as though it is being invoked from a different folder?

A: Its in the docs:
var cp = require('child_process');
cp.exec('foocommand', { cwd: 'path/to/dir/' }, callback);

A: Not a total expert but if its a cli then you want to be able to use stdin witch is not available with process.exec. Maybe you want to see if there is a programable interface for the cli?


text:
Q: iAds Throwing Error I am getting the following error:
2010-11-08 19:47:08.190 One2ThreePop[325:207] didFailToReceiveAdWithError
2010-11-08 19:47:10.990 One2ThreePop[325:207] The operation couldn't be completed. Banner view is visible but does not have content
2010-11-08 19:47:10.991 One2ThreePop[325:207] didFailToReceiveAdWithError
2010-11-08 19:47:12.389 One2ThreePop[325:207] The operation couldn't be completed. Ad inventory unavailable
2010-11-08 19:47:12.390 One2ThreePop[325:207] didFailToReceiveAdWithError
2010-11-08 19:47:12.590 One2ThreePop[325:207] The operation couldn't be completed. Ad inventory unavailable
2010-11-08 19:47:12.591 One2ThreePop[325:207] didFailToReceiveAdWithError
2010-11-08 19:47:13.374 One2ThreePop[325:207] The operation couldn't be completed. Ad inventory unavailable
2010-11-08 19:47:13.375 One2ThreePop[325:207] didFailToReceiveAdWithError

As noted above the didFailToReceiveAdWithError is being fired correctly. The iAds are enabled for my application through iTunes connect. I am using xCode 3.2.4 and iOS 4.1.
Here is my complete code for Cocos2d application:
ABCPopAppDelegate.m

- (void) applicationDidFinishLaunching:(UIApplication*)application
{

CC_DIRECTOR_INIT();

NSLog(@"applicationDidFinishLaunching");

MainViewController *controller = [[MainViewController alloc] init];

[window addSubview: controller.view];

}

MainViewController.h

#import <UIKit/UIKit.h>
#import <iAd/iAd.h>
#import "cocos2d.h"
#import "ABCPopGameScene.h"

@interface MainViewController : UIViewController<ADBannerViewDelegate> {

ADBannerView *bannerView;

}

@property (nonatomic,retain) ADBannerView *bannerView;

@end

MainViewController.m:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

[super viewDidLoad];

// Obtain the shared director in order to...
CCDirector *director = [CCDirector sharedDirector];

// Sets landscape mode
[director setDeviceOrientation:kCCDeviceOrientationPortrait];

// Turn on display FPS
[director setDisplayFPS:NO];

// Turn on multiple touches
EAGLView *eaglView = [director openGLView];
[eaglView setMultipleTouchEnabled:YES];

[self.view addSubview:eaglView];

self.bannerView = [[ADBannerView alloc] initWithFrame:CGRectZero];
[self.bannerView setRequiredContentSizeIdentifiers:[NSSet setWithObjects:
ADBannerContentSizeIdentifier320x50,
ADBannerContentSizeIdentifier480x32, nil]];

self.bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;

[self.bannerView setDelegate:self];

[self.view addSubview:self.bannerView];

// [self.view addSubview:eaglView];

// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change anytime.
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];

[[CCDirector sharedDirector] runWithScene: [ABCPopGameScene scene]];

NSLog(@"viewDidLoad fired!");

//[self moveBannerOffScreen];

}

I can see the game running but I do not see any ads displayed. Do I have to somehow position the ads or something?

A: Turned out the error was related to Apple not sending the iAds. I tried it after a while and everything started working fine!


text:
Q: Performance problems with a MySQL query I am trying to retrieve the number of elements which are not null for a column.
For example, if you have something like this:

and you want to retrieve the number of element which are not null for the column_name_1 you should retrieve 1. For the column_name_2 you should retrieve 2, and for the column_name_3 you should retrieve 0.
I am using this query in a MySQL database:
SELECT
  COUNT(*)
FROM
  my_table
WHERE column_name_1 IS NOT NULL
  AND [ others conditions ]

But, you have to run this query for each column, and for a lot elements (not all of them), I have some performance problems. Do you know how I can change this query in order to improve the performance?

A: You can use IF of mysql
SELECT
    SUM(IF(col1 IS NULL,1,0)) as Col1,
    SUM(IF(col2 IS NULL,1,0)) as Col2,
    SUM(IF(col3 IS NULL,1,0)) as Col3
FROM my_table
WHERE [conditions]

This way you shift IS NULL condition from where to selection


text:
Q: Github account keys for multiple local users I created a second user account on my computer, when I was releasing an app under a different developer account, as I understood this was preferable in terms of keys for the certificates.
However, now when I wish to implement source control with Github in my apps on the second account, I'm having difficulty, I suspect because the SSH key was generated with my normal account.
Has anybody else faced this situation, advice? Am I supposed to create another SSH key or something?

A: You should create one ssh key per user per computer. You can easily add multiple keys to your github account.
Just do ssh-keygen, follow the prompts, then cat ~/.ssh/id_rsa.pub and copy the result into github on the account preferences page under SSH keys.
If you don't know the location of the file, enter ~/.ssh/id_rsa for your private key and ~/.ssh/id_rsa.pub for your public key.

A: You can associate more than one key with your Github account, and if I understand your question that's one approach (one key for each user on your computer). You could also share the one private key between both accounts.

A: I believe it's better to copy the original key pair to the second account, if both accounts are intended to be used as a 'single identity'. If you later start using ssh key authentication for other purposes (other hosting, ssh to your other work machines), it's simpler if you don't need to import several different keys to all the machines but just one key.
See Is it possible to use the same ssh private/public key pair on 2 machines to access a git repository?


text:
Q: USB Debugging / System Crash I have written a small program which generates 4 Audio Streams (sine waves) and sends them to 4 sound cards (each one connected to a USB port of the raspberry pi 3).
After a few seconds the pi completely freezes/crashes. I have to reboot the Raspberry Pi.
With just 3 Audio Streams (and 3 USB sound cards), everything works as expected.
The CPU load is actually ok (monitored with htop). The 4 CPUs are at about 30%.
However before crashing I can find the following entries in syslog:
Oct 11 18:48:13 pi kernel: [   51.983775] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=6 fsm=8 on transfer to device 4 ep 0x4
Oct 11 18:48:14 pi kernel: [   52.415833] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=2 fsm=9 on transfer to device 7 ep 0x1
Oct 11 18:48:14 pi kernel: [   52.991916] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=3 fsm=9 on transfer to device 4 ep 0x4
Oct 11 18:48:14 pi kernel: [   53.135930] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=2 fsm=9 on transfer to device 4 ep 0x4
Oct 11 18:48:15 pi kernel: [   53.268195] Transfer to device 4 endpoint 0x4 frame 1995 failed - FIQ reported NYET. Data may have been lost.
Oct 11 18:48:15 pi kernel: [   53.423974] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=3 fsm=9 on transfer to device 7 ep 0x1
Oct 11 18:48:15 pi kernel: [   53.567994] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=3 fsm=9 on transfer to device 4 ep 0x4
Oct 11 18:48:15 pi kernel: [   53.712005] WARN::dwc_otg_hcd_handle_hc_fsm:2619: Unexpected state received on hc=3 fsm=9 on transfer to device 7 ep 0x1

I suspect that there is some problem with the USB.
Are there any tools which could help me to monitor the USB ports? e.g. Buffers, Lost packets,...etc
What's the meaning of the syslog messages?
Any hints appreciated!


text:
Q: How can I style a select element on an Android phone? I am developing a mobile website and testing on both iPhone and android phone.
I changed the appearance of select boxes on the page using CSS.
This displays good in the iPhone browser, but in Android does not apply the styles correctly.
The original dropdown arrow remains present (and is stretched vertically due to the height property).
Is there any way of telling the browser how to style this element on a android device? Or is it not supported?
Here is a sample of my code:
HTML:
<div class="filter-group">
    <select class="bigInput" id="f_eventWho" name="f_eventWho" tabindex="1">
        <option id="f_public" selected="selected">For Everyone</option>
        <option id="f_private">By invitation</option>
        <option id="f_both">All Gatherings</option>
    </select>
</div>

CSS:
.bigInput
{width: 125px;
height: 50px;
background-size: 15px;
background: rgb(159, 209, 225) url(../img/small_down_arrow_20.png) no-repeat right;
border: none;
margin: 5px;
font-size: 14px;
}

A: There is no consistent way to style native selectboxes in browsers, let alone in mobile.
The best workaround I've found is to create an HTML dropdown that emulates the selectbox behavior - I highly recommend SelectBoxIt if you're using JQuery: http://gregfranko.com/jquery.selectBoxIt.js/
All you have to do is call $('select').selectboxit(); and it replaces all select boxes on the page with stylable html elements that behave the exact same way. Best of luck!

A: The best solution is to not try and style select elements, especially not on mobile devices.
Doing so is both damaging to usability and performance, it's raising your middle finger to visitors and letting them know you really don't care about them at all.
Please try and justify the enormous overhead (please look at what a lib like selectBoxIt will do to page-weight) you will be adding against the benefit you will provide to visitors (which is zero, at best).


text:
Q: Javascript alert when new row is added to database I need to give a javascript alert to users browser when a new record is added to database.  So far i have done this:
PHP chatalert.php
require("../system/config.php");
$result = mysql_query("SELECT * FROM chat");
$rows = mysql_num_rows($result);
echo $rows;

Javascript: test.php
<?php
define('BASEPATH', true);
require("../system/config.php");
?>
<script>

var old_count = 0;

setInterval(function(){
    $.ajax({
        type : "POST",
        url : "chatalert.php",
        success : function(data){
            if (data > old_count) {
                alert('new record on i_case');
                old_count = data;
            }
        }
    });
},1000);

</script>

But I always recive an error: "Uncaught ReferenceError: $ is not defined". So I will need some advice on this.
Mairo

A: Have you included jquery? if not try adding this in your head tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

A: also make sure to parse the string to integer/Float for accurate result. The data returned by php can also be in string format:
var old_count = 0;
setInterval(function(){
    $.ajax({
        type : "POST",
        url : "chatalert.php",
        success : function(data){
            if (parseFloat(data) > old_count) {
                alert('new record on i_case');
                old_count = data;
            }
        }
    });
},1000);


text:
Q: iframes como ajustar width y heght No se me ajustan los width y height de iframes y no se si es por ser un iframe de spotify. Aca dejo el codigo. Puse como div principal un iframes y despues coloque las etiquetas iframe

    .iframes{
      position: absolute;
      top:127px;
      display: flex;
      flex-direction:column;
      margin-left:11px;
      }
    iframe{

        width:298px;
        height:225px;
        overflow-x:hidden;
        overflow-y:hidden;

      }````


text:
Q: Is it possible to configure a container from docker-compose or some other way? Is it somehow possible to pass commands for automated container configuration, after the container has been started? For instance, could I pass multiple commands to the container to restart services with systemctl, change network configs, chmod files, etc, from docker-compose?
Thanks.

A: Yes, you can change the startup script to do what you want. Or you could run an init container or possibly in your dockerfile when you make the container.


text:
Q: read operation with two interchanging processes and context switch P1 and P2 are both processes, different from each other.
this is a read operation done on the hard disk:

Given above is a diagram of a read instuction in Linux, Is it true that it's better to avoid using a context switch to better the overall preformance?
(a) true, because it avoids swapping in the TLB.
(b) true.
(c) wrong.
(d) wrong, it's impossible to avoid performing a context switch
Why is the answer simply (c)? I was thinking that the student can't be right because avoiding a context switch doesn't better overall preformance since context switching is used to better preformance.
I was thinking it should be (d) beause when we go from P1 to P2 we need a context switch to go from one process to another.
Can anyone explain?

A: Ok, It seems one ought to choose (c) over (d) simply because (d) is untrue.
When P1 goes after a while into a read stage we're talking about IO, therefore the CPU is busy. It has to first process the IO request and get to that data, so while it's doing exactly that, the scheduler runs another process so that we don't lose time - this however has nothing to do with a context switch.
This is what I think. Does this seems logical?

A: It would be possible to avoid one context switch (the switch from P2 to P1) by not scheduling P2 to run while waiting for the disk operation to complete. Presumably, if you did that then P1 would resume execution slightly sooner, with a warmer TLB.
You can't avoid all context switching because the system call involves a context switch (user to kernel) as does the resumption of P1 after the completion interrupt from the device. But you could avoid two switches of the user context (though only one of the switches affects P1's timing).
So, if your only measurement of performance is how fast P1 executes, then you could extract a tiny bit more by dedicating that CPU to P1 and not allowing any other processes to run. But we know that disk activity is slow compared to context switching, and the question is about overall performance, not about P1 alone. So it makes sense to schedule P2 to run during the wait, even though it will introduce a small delay in resuming P1 later.


text:
Q: Why in assigning a char array elements in c++, the assigned character is destroyed? I wrote a function in C++ which removes two characters from a char array. I think when I assign str[o+2] to str[o], the str[o+2] shoud not be changed. But when I use cout to print it, I see that str[o+2] is altered with null.
#include<iostream>
#include<string.h>
using namespace std;
void shiftLeft(char*,int, int);
int main(){
    char str[100];
    cout<<"enter the string: ";
    cin>>str;
    cout<<"removes the letter with index i and i+1\nenter i:";
    int i;
    cin>>i;
    int n=strlen(str);
    shiftLeft(str,i,n);
    cout<<str;
    return 0;
}
void shiftLeft(char*str,int i, int n){
    for(int o=i-1; o<n; o++){
        str[o]=str[o+2];
    }
}

For example with input "abcdef" and i=3, I expect output "abefef" but I get "abef". where are the last "ef"? Why are they ignored?

A: abcdef0???... <- the contents of array (0 means NUL, ? means indeterminate)
  ef0?        <- what is written to the position (shifted 2 characters)

Assigning str[o+2] to str[o] itself won't changestr[o+2],
but later o will come to o+2 thanks to the for statement and then assigning str[o+2] to str[o] means assigning str[o+4] to str[o+2] with original o value.
Then, terminating null character is written and the string ends.


text:
Q: RPAD not working in SSH Secure Shell When I use this code, I get two different results:
DBMS_OUTPUT.PUT_LINE(RPAD(' ', 30) || 'SPECIALTY IMPORTS' || CHR(13));
In SQL Developer, it formats the title 'SPECIATLY IMPORTS' in the middle, but when I run the sql file on SSH Secure Shell, it just prints it without pushing it to the middle. Also, if I put spaces in the  beginning of the title, it still doesn't push it in SSH. How do I get the title to format to the center of the page in SSH?


text:
Q: ANSI 92 Date Difference not working in MySQL I'm, trying to calculate the number of days between two dates using ANSI SQL standard. But I'm missing something as this statement returns NULL in MySQL.
SELECT EXTRACT(DAY FROM  DATE('2009-01-25')  -  DATE('2009-01-01')) AS day_diff;
I'm aware of the MySQL DATEDIFF function, but I'm curious why this code isn't working.
What am I missing?

A: Is this what you meant to do?
mysql> SELECT EXTRACT(DAY FROM DATE('2009-01-25')) -
         EXTRACT(DAY FROM DATE('2009-01-01')) AS day_diff;
+----------+
| day_diff |
+----------+
|       24 |
+----------+
1 row in set (0.00 sec)

UPDATE:
If you want this to work for dates in different months (or even different years), then you can use the MySQL DATEDIFF() function.
Examples:
mysql> select datediff('2009-04-25','2009-01-01');
+-------------------------------------+
| datediff('2009-04-25','2009-01-01') |
+-------------------------------------+
|                                 114 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> select datediff('2010-04-25','2009-01-01');
+-------------------------------------+
| datediff('2010-04-25','2009-01-01') |
+-------------------------------------+
|                                 479 |
+-------------------------------------+
1 row in set (0.00 sec)


text:
Q: How to handle NSTableView Drag and Drop for multiple rows I'm fairly new to Cocoa dev, but implementing single row drag and drop within my NSTableView was fairly straightforward. However I'm now having a hard time getting it to work right when multiple rows are selected.
It seems to work without fault when all the selected rows are sequential, but it fails when, for example, you select rows 0 and 4 (where 4 is the last row) and drag them to somewhere in between (such as row 1 or 2) — by fail I mean that the wrong row is deleted and so I end up with duplicates.
Here is my acceptDrop code so far:
- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info
        row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation
{
    NSPasteboard* pboard = [info draggingPasteboard];
    NSData* rowData = [pboard dataForType:BasicTableViewDragAndDropDataType];
    NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
    NSInteger dragRow = [rowIndexes firstIndex];
    NSArray *tempArray = [[NSArray alloc] initWithArray:_filePaths copyItems:YES];

    int i = 0;

  if (dragRow < row)
    {
        while (dragRow != NSNotFound)
        {
            int putRow = row + i;
            int deleteRow = dragRow;

            if (putRow > [_filePaths count]) { putRow = [_filePaths count]; }
            if (i >= 1)
            {
                // offset fix for already deleted rows
                deleteRow = deleteRow - i;
            }

            [_filePaths insertObject:[tempArray objectAtIndex:dragRow] atIndex:putRow];
            [_filePaths removeObjectAtIndex:deleteRow];

            dragRow = [rowIndexes indexGreaterThanIndex:dragRow];

            i++;
        }

        [_imagesTableView noteNumberOfRowsChanged];
        [_imagesTableView reloadData];

    return YES;

  }

    NSLog(@"dragging up");

    while (dragRow != NSNotFound)
    {
        int putRow = row + i;
        if (putRow > [_filePaths count]) { putRow = [_filePaths count]; }

        [_filePaths removeObjectAtIndex:dragRow];
        [_filePaths insertObject:[tempArray objectAtIndex:dragRow] atIndex:putRow];

        dragRow = [rowIndexes indexGreaterThanIndex:dragRow];

        i++;
    }

    [_imagesTableView noteNumberOfRowsChanged];
    [_imagesTableView reloadData];

  return YES;
}

A: So after much dragging and dropping (and a few application crashes mixed in there) I started web searching again and found this class on GitHub.
I mimicked the code there and now it's working like a charm.


text:
Q: Expand time series with Pandas I'm starting with the following DataFrame:
import pandas as pd

d = {
    "Id": ["A", "B", "C"],
    "Value1": ["10", "20", "30"],
    "Period1": ["20:00", "20:30", "21:00"],
    "Value2": ["25", "40", "40"],
    "Period2": ["20:45", "00:00", "01:00"],
}
df = pd.DataFrame(data=d)

And given a custom time index:
time_start = "2022-11-16 20:00:00.000000"
time_stop = "2022-11-17 09:00:00.000000"
time_index = pd.date_range(start=time_start, end=time_stop, freq="15Min")

I would like to obtain a dataframe for each Id in df where:

*

*the index is time_index

*the values are Value1 or Value2 depending on the time_index value of the row

For A, I should get:
                              Value
2022-11-16 20:00:00.000000    10
2022-11-16 20:15:00.000000    10
2022-11-16 20:30:00.000000    10
2022-11-16 20:45:00.000000    25
2022-11-16 21:00:00.000000    25
...                           ...

A: Here is one way to do it:
# Setup
df["Period1"] = pd.to_datetime(df["Period1"])
df["Period2"] = pd.to_datetime(df["Period2"])
new_df = pd.DataFrame(time_index).rename(columns={0: "date"})
new_df["time"] = new_df["date"].dt.time

# Add values according to timestamps
for idx in df["Id"]:
    new_df.loc[
        new_df["time"] == df.loc[df["Id"] == idx, "Period1"].dt.time.values[0], idx
    ] = df.loc[df["Id"] == idx, "Value1"].values[0]
    new_df.loc[
        new_df["time"] == df.loc[df["Id"] == idx, "Period2"].dt.time.values[0], idx
    ] = df.loc[df["Id"] == idx, "Value2"].values[0]
    new_df = new_df.fillna(method="ffill")

# Cleanup
new_df = new_df.drop(columns="time").set_index("date").rename_axis(None, axis=0)

Then:
print(pd.DataFrame(new_df.loc[:, "A"]).rename(columns={"A": "Value"}))

# Output
                    Value
2022-11-16 20:00:00    10
2022-11-16 20:15:00    10
2022-11-16 20:30:00    10
2022-11-16 20:45:00    25
2022-11-16 21:00:00    25
...                   ...
2022-11-17 08:00:00    25
2022-11-17 08:15:00    25
2022-11-17 08:30:00    25
2022-11-17 08:45:00    25
2022-11-17 09:00:00    25

[53 rows x 1 columns]

print(pd.DataFrame(new_df.loc[:, "B"]).rename(columns={"B": "Value"}))

# Output
                    Value
2022-11-16 20:00:00   NaN
2022-11-16 20:15:00   NaN
2022-11-16 20:30:00    20
2022-11-16 20:45:00    20
2022-11-16 21:00:00    20
...                   ...
2022-11-17 08:00:00    40
2022-11-17 08:15:00    40
2022-11-17 08:30:00    40
2022-11-17 08:45:00    40
2022-11-17 09:00:00    40

[53 rows x 1 columns]

print(pd.DataFrame(new_df.loc[:, "C"]).rename(columns={"C": "Value"}))

# Output
                    Value
2022-11-16 20:00:00   NaN
2022-11-16 20:15:00   NaN
2022-11-16 20:30:00   NaN
2022-11-16 20:45:00   NaN
2022-11-16 21:00:00    30
...                   ...
2022-11-17 08:00:00    40
2022-11-17 08:15:00    40
2022-11-17 08:30:00    40
2022-11-17 08:45:00    40
2022-11-17 09:00:00    40

[53 rows x 1 columns]


text:
Q: Blazor, how to constantly get currentWindow width? I want to do something like this in a razor page:
@if (currentwidth<x)
{
   le code
}
else
{
    le other code
}

I have added javascript file and connected it to a utility service which works when I get the static width (which I tested).
js:
export function getCurrentWidth() {

    return window.addEventListener("resize", () => {
        window.innerWidth;
    });

}

UtilityService method:
public async Task<double> GetCurrentWidth()
        {
            var m = await GetModule();
            var result = await m.InvokeAsync<double>("getCurrentWidth");
            return result;
        }

Razor file:
double width;

    protected async override Task OnInitializedAsync()
    {
        width = await utilityService.GetCurrentWidth();
    }

Thus the problem is I can't call it from OnInitailzedAsync since this function only fired once, so I need a function that constantly checks the GetCurrentWIdth() method to check for resize.
Is there another way of doing this in blazor or what method could I use/ Thank you in advance.

A: First of all I'd like to point out that you may not have to solve your problem with javascript/C# code. If it's something in the html that you want to manipulate, you may just be better of using css. But I'll leave that up to you.
If however you truly need the window width like you mentioned above, then I would recommend registering a listener to the window (as you've already done) and have that listener call a dotnet function. Doing this with static methods is quite easy, but for instance component this can be a bit trickier as you have to pass an object reference of the current object.
The [JsInvokable] indicates that this method can be called from javascript, which allows communication from the javascript event listener to dotnet.
CSharpFromJs.razor.cs
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Threading.Tasks;

public partial class CSharpFromJS
{
    private DotNetObjectReference<CSharpFromJS> _objectReference;
    public int WindowWidth { get; set; }

    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    protected override void OnInitialized()
    {
        _objectReference = DotNetObjectReference.Create(this);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await InitWindowWidthListener();
        }
    }

    [JSInvokable]
    public void UpdateWindowWidth(int windowWidth)
    {
        WindowWidth = windowWidth;
        StateHasChanged();
    }

    private async Task InitWindowWidthListener()
    {
        await JSRuntime.InvokeVoidAsync("AddWindowWidthListener", _objectReference);
    }

    public async ValueTask DisposeAsync()
    {
        await JSRuntime.InvokeVoidAsync("RemoveWindowWidthListener", _objectReference);
        _objectReference?.Dispose();
    }
}

CSharpFromJs.razor
@implements IAsyncDisposable

Window width: @WindowWidth

Javascript
// Manages the registered event listeners so they can be disposed later
let windowEventListeners = {};

function AddWindowWidthListener(objReference) {
    let eventListener = () => UpdateWindowWidth(objReference);
    window.addEventListener("resize", eventListener);
    windowEventListeners[objReference] = eventListener;
}

function RemoveWindowWidthListener(objReference) {
    window.removeEventListener("resize", windowEventListeners[objReference]);
}

function UpdateWindowWidth(objReference) {
    objReference.invokeMethodAsync("UpdateWindowWidth", window.innerWidth);
}

The only thing you should be careful with is when a component is disposd. You should remove the registered handlers in the DisposeAsync function to ensure that they're not still registered to prevent memory leaks.
This link might provide some better instructions on how to use this, but they don't explain the part about disposing handlers.
Note: This only works in .net5 and later, as IAsyncDisposable was not yet implemented for component before that. If for some reason you're working with an earlier version, you could call it using IDisposable. But this could potentially cause deadlocks, so I would not recommend it.

A: For me works the NuGet package BlazorPro.BlazorSize
Implement the method:
async void WindowResized(object _, BrowserWindowSize window){}
and all necessary Dependencies (see description).


text:
Q: Зачем нужны массивы байтов byte[]? Сабж.
Часто вижу в примерах как используют byte[], например при отправке POST запроса.
Я не понимаю зачем это нужно, это рудимент низкоуровневого программирования?
На сколько я знаю String это массив Char, каждый символ представлен в памяти своим ASCII кодом, что происходит когда эта строка преобразовывается в byte[]?
Вот к примеру это используется в отправке POST запроса, но на той стороне у меня из коробки контроллер принимает модель и сразу создается объект. Майкрософт рекомендует использовать TPL в новых разработках вместо Thread, так как Thread это более низкий уровень.
TPL отдает на откуп работу с потоками в CLI, почему так же не сделать с byte[]?
Вообщем я запутался.
Пример где мне кажется странным использование массива байтов
https://docs.microsoft.com/ru-ru/dotnet/standard/security/encrypting-data
class Class1
{
    static void Main()
    {
        //Initialize the byte arrays to the public key information.
        byte[] modulus =
        {
            214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
            74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,
            207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,
            108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,
            240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,
            168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,
            38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,
            106,99,179,68,175,211,164,116,64,148,226,254,172,147
        };

        byte[] exponent = { 1, 0, 1 };

        //Create values to store encrypted symmetric keys.
        byte[] encryptedSymmetricKey;
        byte[] encryptedSymmetricIV;

        //Create a new instance of the RSA class.
        RSA rsa = RSA.Create();

        //Create a new instance of the RSAParameters structure.
        RSAParameters rsaKeyInfo = new RSAParameters();

        //Set rsaKeyInfo to the public key values.
        rsaKeyInfo.Modulus = modulus;
        rsaKeyInfo.Exponent = exponent;

        //Import key parameters into rsa.
        rsa.ImportParameters(rsaKeyInfo);

        //Create a new instance of the default Aes implementation class.
        Aes aes = Aes.Create();

        //Encrypt the symmetric key and IV.
        encryptedSymmetricKey = rsa.Encrypt(aes.Key, RSAEncryptionPadding.Pkcs1);
        encryptedSymmetricIV = rsa.Encrypt(aes.IV, RSAEncryptionPadding.Pkcs1);
    }
}

Открытый ключ это просто число, зачем оно в байтах?
Вот пример с метанита, отправка POST запроса, зачем я тут перевожу строку в байты? Не ну я понимаю что метод принимает массив байтов, но почему он не может принять просто строку и у себя там сделать с ней все что нужно?
            WebRequest request = WebRequest.Create("https://localhost:44391/api/Order/");
            request.Method = "POST"; // для отправки используется метод Post
                                     // данные для отправки
            string data = _data;
            // преобразуем данные в массив байтов
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data);
            // устанавливаем тип содержимого - параметр ContentType
            request.ContentType = "application/json";
            // Устанавливаем заголовок Content-Length запроса - свойство ContentLength
            request.ContentLength = byteArray.Length;

            //записываем данные в поток запроса
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            WebResponse response = await request.GetResponseAsync();
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    d = reader.ReadToEnd();
                }
            }
            response.Close();

A:
String это массив Char, каждый символ представлен в памяти своим ASCII кодом

Неверно, string хранится в памяти как последовательность двухбайтовых char в кодировке UTF-16, а не ASCII.
Вас никто не заставляет вручную перекодировать в массив байт, особенно если вы используете современные сетевые API. WebRequest устарел, при чем сильно.
private static readonly HttpClient client = new HttpClient();

public async Task<string> PostJsonAsync(string url, string json)
{
    using HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
    using var response = await client.PostAsync(url, content);
    return await response.Content.ReadAsStringAsync();
}

Видите - я ничего не перекодирую. Но это не значит, что перекодировка не происходит. Просто она где-то спрятана внутри кода .NET.
В памяти строка хранится в UTF-16, а отправляется как UTF-8. При чем и хранится в памяти строка как байты, и отправляется как байты. Мы же все знаем, что есть только байты, и ничего кроме байтов в памяти быть не может. Как и по каналу связи ничего кроме байтов отправлено или принято быть не может. Просто .NET удобный, и не требует вручную выполнять перекодировки.
Можно ли string отправить без перекодировок "как есть"? Легко, правда потребуется .NET Core или .NET 5, потому что в старых фреймворках придется поплясать с бубном вокруг небезопасного кода, чтобы получилось.
Можно конечно через Encoding.Unicode.GetBytes(text), но я не буду использовать для наглядности, хотя результат в массиве байт будет идентичен.
string text = "Hello World";
ReadOnlySpan<byte> bytes = MemoryMarshal.Cast<char, byte>(text);
using HttpContent content = new ByteArrayContent(bytes.ToArray());
// и далее то же самое как выше

Если бы конструктор ByteArrayContent принимал в качестве аргумента ReadOnlySpan, можно было бы отправить в сеть прямо содержимое памяти строки, не то что без преобразования - а даже без копирования данных, "как есть". Конечно можно обойти это ограничение через StreamContent, создав собственный Stream, который будет читать непосредственно память из string, но это получится много кода и просто ради того чтобы показать, что это возможно, я не буду его писать.

По поводу, зачем число в байты преобразовывать, оно типа и так байты. Ну вот например, есть Int32 - 4 байта. Так как Socket умеет отправлять только байты, то чтобы отправить это число по сети, надо его в байты и преобразовать. Если особо извратнуться, можно как и со строкой - отправить эти байты читая содержимое ровно той ячейки оперативной памяти, где лежит этот Int32. Правда есть проблема, в определенных ситуациях некая локальная переменная с тем же интом может быть на низком уровне вообще не быть в памяти, а например храниться в регистре процессора, а отправить по сети можно только память, и поэтому в качестве источника данных для отправки по сети и используется массив байт, как самый примитивный указатель на участок памяти с данными в .NET.

Что касается криптографии. Самое длинное целое число в .NET как примитив - Int64 - 8 байт. А 8 байт для представления ключей и прочих криптографических данных - это даже не смешно. Даже древний хэш MD5 - 16 байт. Потом массивы байт можно легко очистить, своевременно избавившись от секретных данных из памяти. Кстати именно потому что строку string нельзя очистить (она не мутабельна) - в ней и не рекомендуется хранить ключ или пароль для шифрования. Поэтому в криптографии везде массивы. Я кстати недавно писал код для алгоритма шифрования пароля Apache MD5, так я замучался, чтобы свести к минимуму копирование байт в памяти туда-сюда, как минимум ради производительности, в этом мне сильно помогли те же спаны Span<T>/ReadOnlySpan<T>.

A: Ваш вопрос распадается на две части.
Во-первых, по поводу криптографии. Здесь представление ключей в виде чисел, хотя и возможно, ничего бы не дало. Для нас, пользователей криптографии, вся работа заключается в преобразовании наборов байт. Мы не пользуемся ни возможностями сложения/умножения, ни десятичным представлением ни ключей шифрования, ни шифруемых сообщений. Фактически криптография работает с наборами байт, и дополнительные операции, которые нам позволяют числа, привели бы лишь к вопросам «а что будет, если сложить два ключа» и. т. п.
Хотя ключи и можно представить числами достаточно большой разрядности, это не несёт смысла точно так же, как не несёт смысла представление файлов в виде чисел.
По поводу второй части, вы правы, API, которое вы приводите в пример, несколько устарело. Сейчас принято писать как-то так:
var client = new HttpClient() { BaseAddress = new Uri("http://httpbin.org") };
var request = new RequestObject(...);
var result = await client.PostAsJsonAsync("/post", request);
var reply = await result.Content.ReadFromJsonAsync<Response>();

Как вы видите, детали наподобие сериализации объектов в JSON, и составление нужного HttpContent'а спрятаны за удобными методами расширения, которые всё сделают за вас.
Впрочем, если вы захотите, низкоуровневые возможности и полный контроль никто у вас не отнимает, и вы можете составить HttpContent сами.

A: Рассмотрим сначала более простой пример. Вы хотите переслать Int32 по сети или записать в файл. Когда вы работаете с абстрактным типом данных, коим является Int32, то вас как программиста, не интересует, как именно он представлен в памяти. Это деталь реализации, которая может отличаться от платформы к платформе. Вам важно какие значения он может принимать и какие операции поддерживает.
Так уж исторически сложилось (об этом чуть позже), что по сети можно пересылать только байты.
Просто скопировав представление Int32 в байтах из памяти и переслав по сети возникнет проблема на принимающей стороне. А что если на принимающей стороне другой способ представления Int32? Там вообще может быть не .NET приложение, а 8-битный микроконтроллер, который умеет работать только с байтами. Это одна из причин почему по сети пересылаются байты - для интероперабельности, т.е. совместимости разных систем. Байты используются как наименьший элемент, который понимают все операционные системы.
То есть проблема в том, что представить 32 разрядный int в виде 4 байт можно не одним способом, а как минимум двумя, которые отличаются порядком байт. И вам нужно задать какой из способов вы хотите выбрать. Тут вы используете кодирование абстрактного типа Int32 в байты. Принимающая и передающая сторона должны договориться, как интерпретировать поток байт, который передается по сети, или хранится в файле.
Со строками точно та же проблема, только еще хуже. Во-первых, строка сама по себе это еще более абстрактная вещь чем число (числа в некотором диапазоне можно хотя бы хранить прямо в памяти). А строка состоит из символов, а символ напрямую в памяти хранить нельзя, можно его закодировать какой-то последовательностью байт. И опять же, способ кодирования - это деталь реализации.
Точно так же как и с Int32 просто послать строку по сети нельзя, можно только послать строку преобразованную в байты используя какой-то способ кодирования. Тут язык программирования и/или библиотеки могут предоставить средства, как указано в других ответах, чтобы упростить жизнь и не делать вручную перекодирование, но указать кодировку (явно или неявно) придется обязательно.