问:
Categorical Data mining with python (pandas) (data Cleaning)
Can anyone help me out?

I am new to data mining and have a categorical dataset.
I want to clean the data using PYTHON; I have an issue in the ' Signature' column (Data Cleaning Step). Please see the data sample below for a better understanding. I want to clean the "signature" column to use it later in Machine Learning Model. The output should be numeric.

Please Find the attached screenshot for better understanding>
DataSet

```<code>print(df.sample(2).to_dict("list"))
</code>```
```<code>{'md5': ['da90ea57d95eb78e2caffdd7344a12d8', '7cd341f0d4ab31ecd4e5dec4f24c23ab'], 'version': ['9.20.0', '2.73'], 'min_sdk': ['18', '15'], 'min_screen': ['small', 'small'], 'min_opengl': [2.0, nan], 'supported_cpu': ['arm64-v8a', 'arm64-v8a, armeabi, armeabi-v7a, mips, mips64, x86, x86_64'], 'signature': ['38:91:8A:45:3D:07:19:93:54:F8:B1:9A:F0:5E:C6:56:2C:ED:57:88', '98:24:D8:09:21:56:CE:EC:84:3F:66:04:EF:7D:10:D0:ED:BF:4E:B7'], 'rating_number': [0.0, 4.1], 'rating_count': [0, 125], 'androidpermissionbind_wallpaper': [0, 0], 'androidpermissionforce_back': [0, 0], 'androidpermissionread_calendar': [0, 0], 'androidpermissionbody_sensors': [0, 0], 'androidpermissionread_social_stream': [0, 0], 'androidpermissionread_sync_stats': [0, 0], 'androidpermissioninternet': [1, 1], 'androidpermissionchange_configuration': [0, 0], 'androidpermissionbind_dream_service': [0, 0], 'androidpermissionhardware_test': [0, 0], 'comandroidbrowserpermissionwrite_history_bookmarks': [0, 0], 'comandroidlauncherpermissioninstall_shortcut': [1, 1], 'androidpermissionbind_tv_input': [0, 0], 'androidpermissionbind_vpn_service': [0, 0], 'androidpermissionbluetooth_privileged': [0, 0], 'androidpermissionwrite_call_log': [0, 0], 'androidpermissionchange_wifi_multicast_state': [0, 0], 'androidpermissionbind_input_method': [0, 0], 'androidpermissionset_time_zone': [0, 0], 'androidpermissionwrite_sync_settings': [1, 1], 'androidpermissionwrite_gservices': [0, 0], 'androidpermissionset_orientation': [0, 0], 'androidpermissionbind_device_admin': [0, 0], 'androidpermissionmanage_documents': [0, 0], 'androidpermissionforce_stop_packages': [0, 0], 'androidpermissionwrite_secure_settings': [0, 0], 'androidpermissioncall_privileged': [0, 0], 'androidpermissionmount_format_filesystems': [0, 0], 'androidpermissionsystem_alert_window': [0, 0], 'androidpermissionaccess_location_extra_commands': [0, 0], 'androidpermissionbrick': [0, 0], 'androidpermissiondump': [0, 0], 'androidpermissionchange_wifi_state': [0, 0], 'androidpermissionrecord_audio': [0, 0], 'androidpermissionmodify_phone_state': [0, 0], 'androidpermissionread_profile': [0, 0], 'androidpermissionaccount_manager': [0, 0], 'androidpermissionset_animation_scale': [0, 0], 'androidpermissionset_process_limit': [0, 0], 'androidpermissioncapture_secure_video_output': [0, 0], 'androidpermissionset_preferred_applications': [0, 0], 'androidpermissionaccess_all_downloads': [0, 0], 'androidpermissionset_debug_app': [0, 0], 'androidpermissionstop_app_switches': [0, 0], 'androidpermissionbluetooth': [0, 0], 'androidpermissionaccess_wifi_state': [1, 1], 'androidpermissionset_wallpaper_hints': [0, 0], 'androidpermissionbind_notification_listener_service': [0, 0], 'androidpermissionmms_send_outbox_msg': [0, 0], 'androidpermissioncontrol_location_updates': [0, 0], 'androidpermissionupdate_app_ops_stats': [0, 0], 'androidpermissionreboot': [0, 0], 'androidpermissionbroadcast_wap_push': [0, 0], 'comandroidlauncher3permissionread_settings': [0, 0], 'androidpermissionaccess_network_state': [1, 1], 'androidpermissionstatus_bar': [0, 0], 'androidpermissionwrite_user_dictionary': [0, 0], 'comandroidbrowserpermissionread_history_bookmarks': [0, 0], 'androidpermissionbroadcast_package_removed': [0, 0], 'androidpermissionreceive_sms': [0, 0], 'androidpermissionwrite_contacts': [0, 0], 'androidpermissionread_contacts': [0, 0], 'androidpermissionbind_appwidget': [0, 0], 'androidpermissionsignal_persistent_processes': [0, 0], 'androidpermissioninstall_location_provider': [0, 0], 'androidpermissionaccess_download_manager_advanced': [0, 0], 'androidpermissionwrite_settings': [0, 0], 'androidpermissionmaster_clear': [0, 0], 'androidpermissionread_input_state': [0, 0], 'androidpermissionmanage_app_tokens': [0, 0], 'androidpermissionbind_remoteviews': [0, 0], 'comandroidemailpermissionaccess_provider': [0, 0], 'androidpermissionbind_voice_interaction': [0, 0], 'comandroidlauncherpermissionwrite_settings': [0, 0], 'comandroidgallery3dfiltershowpermissionread': [0, 0], 'androidpermissionbind_print_service': [0, 0], 'androidpermissionmodify_audio_settings': [0, 0], 'androidpermissionuse_sip': [0, 0], 'androidpermissionwrite_apn_settings': [0, 0], 'androidpermissionaccess_surface_flinger': [0, 0], 'androidpermissionfactory_test': [0, 0], 'androidpermissionread_logs': [1, 1], 'androidpermissionprocess_outgoing_calls': [0, 0], 'androidpermissionupdate_device_stats': [0, 0], 'androidpermissionsend_download_completed_intents': [0, 0], 'androidpermissionwrite_calendar': [0, 0], 'androidpermissionnfc': [0, 0], 'androidpermissionmanage_accounts': [1, 1], 'androidpermissionsend_sms': [0, 0], 'androidpermissioninteract_across_users_full': [0, 0], 'androidpermissionaccess_mock_location': [0, 0], 'androidpermissionbind_accessibility_service': [0, 0], 'androidpermissioncapture_audio_output': [0, 0], 'androidpermissionwrite_sms': [0, 0], 'androidpermissionget_tasks': [0, 0], 'androidpermissiondelete_packages': [0, 0], 'androidpermissionaccess_checkin_properties': [0, 0], 'androidpermissionsend_respond_via_message': [0, 0], 'androidpermissionmedia_content_control': [0, 0], 'androidpermissiondownload_without_notification': [0, 0], 'androidpermissionreceive_boot_completed': [0, 0], 'androidpermissionvibrate': [0, 0], 'androidpermissiondiagnostic': [0, 0], 'androidpermissionwrite_profile': [0, 0], 'androidpermissioncall_phone': [0, 0], 'androidpermissionflashlight': [0, 0], 'androidpermissionread_phone_state': [1, 1], 'androidpermissionchange_component_enabled_state': [0, 0], 'androidpermissionclear_app_user_data': [0, 0], 'androidpermissionbroadcast_sms': [0, 0], 'androidpermissionkill_background_processes': [0, 0], 'androidpermissionread_frame_buffer': [0, 0], 'androidpermissionsubscribed_feeds_write': [0, 0], 'androidpermissioncamera': [0, 0], 'androidpermissionreceive_mms': [0, 0], 'androidpermissionwake_lock': [0, 0], 'androidpermissionaccess_download_manager': [0, 0], 'comandroidlauncher3permissionwrite_settings': [0, 0], 'androidpermissiondelete_cache_files': [0, 0], 'androidpermissionrestart_packages': [0, 0], 'androidpermissionget_accounts': [1, 1], 'androidpermissionsubscribed_feeds_read': [0, 0], 'androidpermissionchange_network_state': [0, 0], 'androidpermissionread_sync_settings': [1, 1], 'androidpermissiondisable_keyguard': [0, 0], 'comandroidlauncherpermissionuninstall_shortcut': [1, 1], 'androidpermissionuse_credentials': [1, 1], 'androidpermissionread_user_dictionary': [0, 0], 'androidpermissionwrite_media_storage': [0, 0], 'androidpermissionaccess_coarse_location': [1, 1], 'comandroidemailpermissionread_attachment': [0, 0], 'androidpermissionset_pointer_speed': [0, 0], 'androidpermissionbackup': [0, 0], 'androidpermissionexpand_status_bar': [0, 0], 'androidpermissionbluetooth_admin': [0, 0], 'androidpermissionaccess_fine_location': [0, 0], 'androidpermissionlocation_hardware': [0, 0], 'androidpermissionpersistent_activity': [0, 0], 'androidpermissionreorder_tasks': [0, 0], 'androidpermissionbind_text_service': [0, 0], 'androidpermissiondevice_power': [0, 0], 'androidpermissionset_wallpaper': [0, 0], 'androidpermissionread_call_log': [0, 0], 'androidpermissionwrite_external_storage': [1, 1], 'androidpermissionget_package_size': [0, 0], 'androidpermissionwrite_social_stream': [0, 0], 'androidpermissionread_external_storage': [0, 0], 'androidpermissioninstall_packages': [0, 0], 'androidpermissionauthenticate_accounts': [1, 1], 'comandroidlauncherpermissionread_settings': [0, 0], 'comandroidalarmpermissionset_alarm': [0, 0], 'androidpermissioninternal_system_window': [0, 0], 'androidpermissionclear_app_cache': [0, 0], 'androidpermissioncapture_video_output': [0, 0], 'androidpermissionget_top_activity_info': [0, 0], 'androidpermissioninject_events': [0, 0], 'androidpermissionset_activity_watcher': [0, 0], 'androidpermissionread_sms': [0, 0], 'androidpermissionbattery_stats': [0, 0], 'androidpermissionglobal_search': [0, 0], 'androidpermissionbind_nfc_service': [0, 0], 'androidpermissionpackage_usage_stats': [0, 0], 'androidpermissionset_always_finish': [0, 0], 'androidpermissionaccess_drm': [0, 0], 'androidpermissionbroadcast_sticky': [0, 0], 'androidpermissionmount_unmount_filesystems': [0, 0], 'label': ['malware', 'malware']}
</code>```

Body:
Can anyone help me out?

I am new to data mining and have a categorical dataset.
I want to clean the data using PYTHON; I have an issue in the ' Signature' column (Data Cleaning Step). Please see the data sample below for a better understanding. I want to clean the "signature" column to use it later in Machine Learning Model. The output should be numeric.

Please Find the attached screenshot for better understanding>
DataSet

print(df.sample(2).to_dict("list"))

{'md5': ['da90ea57d95eb78e2caffdd7344a12d8', '7cd341f0d4ab31ecd4e5dec4f24c23ab'], 'version': ['9.20.0', '2.73'], 'min_sdk': ['18', '15'], 'min_screen': ['small', 'small'], 'min_opengl': [2.0, nan], 'supported_cpu': ['arm64-v8a', 'arm64-v8a, armeabi, armeabi-v7a, mips, mips64, x86, x86_64'], 'signature': ['38:91:8A:45:3D:07:19:93:54:F8:B1:9A:F0:5E:C6:56:2C:ED:57:88', '98:24:D8:09:21:56:CE:EC:84:3F:66:04:EF:7D:10:D0:ED:BF:4E:B7'], 'rating_number': [0.0, 4.1], 'rating_count': [0, 125], 'androidpermissionbind_wallpaper': [0, 0], 'androidpermissionforce_back': [0, 0], 'androidpermissionread_calendar': [0, 0], 'androidpermissionbody_sensors': [0, 0], 'androidpermissionread_social_stream': [0, 0], 'androidpermissionread_sync_stats': [0, 0], 'androidpermissioninternet': [1, 1], 'androidpermissionchange_configuration': [0, 0], 'androidpermissionbind_dream_service': [0, 0], 'androidpermissionhardware_test': [0, 0], 'comandroidbrowserpermissionwrite_history_bookmarks': [0, 0], 'comandroidlauncherpermissioninstall_shortcut': [1, 1], 'androidpermissionbind_tv_input': [0, 0], 'androidpermissionbind_vpn_service': [0, 0], 'androidpermissionbluetooth_privileged': [0, 0], 'androidpermissionwrite_call_log': [0, 0], 'androidpermissionchange_wifi_multicast_state': [0, 0], 'androidpermissionbind_input_method': [0, 0], 'androidpermissionset_time_zone': [0, 0], 'androidpermissionwrite_sync_settings': [1, 1], 'androidpermissionwrite_gservices': [0, 0], 'androidpermissionset_orientation': [0, 0], 'androidpermissionbind_device_admin': [0, 0], 'androidpermissionmanage_documents': [0, 0], 'androidpermissionforce_stop_packages': [0, 0], 'androidpermissionwrite_secure_settings': [0, 0], 'androidpermissioncall_privileged': [0, 0], 'androidpermissionmount_format_filesystems': [0, 0], 'androidpermissionsystem_alert_window': [0, 0], 'androidpermissionaccess_location_extra_commands': [0, 0], 'androidpermissionbrick': [0, 0], 'androidpermissiondump': [0, 0], 'androidpermissionchange_wifi_state': [0, 0], 'androidpermissionrecord_audio': [0, 0], 'androidpermissionmodify_phone_state': [0, 0], 'androidpermissionread_profile': [0, 0], 'androidpermissionaccount_manager': [0, 0], 'androidpermissionset_animation_scale': [0, 0], 'androidpermissionset_process_limit': [0, 0], 'androidpermissioncapture_secure_video_output': [0, 0], 'androidpermissionset_preferred_applications': [0, 0], 'androidpermissionaccess_all_downloads': [0, 0], 'androidpermissionset_debug_app': [0, 0], 'androidpermissionstop_app_switches': [0, 0], 'androidpermissionbluetooth': [0, 0], 'androidpermissionaccess_wifi_state': [1, 1], 'androidpermissionset_wallpaper_hints': [0, 0], 'androidpermissionbind_notification_listener_service': [0, 0], 'androidpermissionmms_send_outbox_msg': [0, 0], 'androidpermissioncontrol_location_updates': [0, 0], 'androidpermissionupdate_app_ops_stats': [0, 0], 'androidpermissionreboot': [0, 0], 'androidpermissionbroadcast_wap_push': [0, 0], 'comandroidlauncher3permissionread_settings': [0, 0], 'androidpermissionaccess_network_state': [1, 1], 'androidpermissionstatus_bar': [0, 0], 'androidpermissionwrite_user_dictionary': [0, 0], 'comandroidbrowserpermissionread_history_bookmarks': [0, 0], 'androidpermissionbroadcast_package_removed': [0, 0], 'androidpermissionreceive_sms': [0, 0], 'androidpermissionwrite_contacts': [0, 0], 'androidpermissionread_contacts': [0, 0], 'androidpermissionbind_appwidget': [0, 0], 'androidpermissionsignal_persistent_processes': [0, 0], 'androidpermissioninstall_location_provider': [0, 0], 'androidpermissionaccess_download_manager_advanced': [0, 0], 'androidpermissionwrite_settings': [0, 0], 'androidpermissionmaster_clear': [0, 0], 'androidpermissionread_input_state': [0, 0], 'androidpermissionmanage_app_tokens': [0, 0], 'androidpermissionbind_remoteviews': [0, 0], 'comandroidemailpermissionaccess_provider': [0, 0], 'androidpermissionbind_voice_interaction': [0, 0], 'comandroidlauncherpermissionwrite_settings': [0, 0], 'comandroidgallery3dfiltershowpermissionread': [0, 0], 'androidpermissionbind_print_service': [0, 0], 'androidpermissionmodify_audio_settings': [0, 0], 'androidpermissionuse_sip': [0, 0], 'androidpermissionwrite_apn_settings': [0, 0], 'androidpermissionaccess_surface_flinger': [0, 0], 'androidpermissionfactory_test': [0, 0], 'androidpermissionread_logs': [1, 1], 'androidpermissionprocess_outgoing_calls': [0, 0], 'androidpermissionupdate_device_stats': [0, 0], 'androidpermissionsend_download_completed_intents': [0, 0], 'androidpermissionwrite_calendar': [0, 0], 'androidpermissionnfc': [0, 0], 'androidpermissionmanage_accounts': [1, 1], 'androidpermissionsend_sms': [0, 0], 'androidpermissioninteract_across_users_full': [0, 0], 'androidpermissionaccess_mock_location': [0, 0], 'androidpermissionbind_accessibility_service': [0, 0], 'androidpermissioncapture_audio_output': [0, 0], 'androidpermissionwrite_sms': [0, 0], 'androidpermissionget_tasks': [0, 0], 'androidpermissiondelete_packages': [0, 0], 'androidpermissionaccess_checkin_properties': [0, 0], 'androidpermissionsend_respond_via_message': [0, 0], 'androidpermissionmedia_content_control': [0, 0], 'androidpermissiondownload_without_notification': [0, 0], 'androidpermissionreceive_boot_completed': [0, 0], 'androidpermissionvibrate': [0, 0], 'androidpermissiondiagnostic': [0, 0], 'androidpermissionwrite_profile': [0, 0], 'androidpermissioncall_phone': [0, 0], 'androidpermissionflashlight': [0, 0], 'androidpermissionread_phone_state': [1, 1], 'androidpermissionchange_component_enabled_state': [0, 0], 'androidpermissionclear_app_user_data': [0, 0], 'androidpermissionbroadcast_sms': [0, 0], 'androidpermissionkill_background_processes': [0, 0], 'androidpermissionread_frame_buffer': [0, 0], 'androidpermissionsubscribed_feeds_write': [0, 0], 'androidpermissioncamera': [0, 0], 'androidpermissionreceive_mms': [0, 0], 'androidpermissionwake_lock': [0, 0], 'androidpermissionaccess_download_manager': [0, 0], 'comandroidlauncher3permissionwrite_settings': [0, 0], 'androidpermissiondelete_cache_files': [0, 0], 'androidpermissionrestart_packages': [0, 0], 'androidpermissionget_accounts': [1, 1], 'androidpermissionsubscribed_feeds_read': [0, 0], 'androidpermissionchange_network_state': [0, 0], 'androidpermissionread_sync_settings': [1, 1], 'androidpermissiondisable_keyguard': [0, 0], 'comandroidlauncherpermissionuninstall_shortcut': [1, 1], 'androidpermissionuse_credentials': [1, 1], 'androidpermissionread_user_dictionary': [0, 0], 'androidpermissionwrite_media_storage': [0, 0], 'androidpermissionaccess_coarse_location': [1, 1], 'comandroidemailpermissionread_attachment': [0, 0], 'androidpermissionset_pointer_speed': [0, 0], 'androidpermissionbackup': [0, 0], 'androidpermissionexpand_status_bar': [0, 0], 'androidpermissionbluetooth_admin': [0, 0], 'androidpermissionaccess_fine_location': [0, 0], 'androidpermissionlocation_hardware': [0, 0], 'androidpermissionpersistent_activity': [0, 0], 'androidpermissionreorder_tasks': [0, 0], 'androidpermissionbind_text_service': [0, 0], 'androidpermissiondevice_power': [0, 0], 'androidpermissionset_wallpaper': [0, 0], 'androidpermissionread_call_log': [0, 0], 'androidpermissionwrite_external_storage': [1, 1], 'androidpermissionget_package_size': [0, 0], 'androidpermissionwrite_social_stream': [0, 0], 'androidpermissionread_external_storage': [0, 0], 'androidpermissioninstall_packages': [0, 0], 'androidpermissionauthenticate_accounts': [1, 1], 'comandroidlauncherpermissionread_settings': [0, 0], 'comandroidalarmpermissionset_alarm': [0, 0], 'androidpermissioninternal_system_window': [0, 0], 'androidpermissionclear_app_cache': [0, 0], 'androidpermissioncapture_video_output': [0, 0], 'androidpermissionget_top_activity_info': [0, 0], 'androidpermissioninject_events': [0, 0], 'androidpermissionset_activity_watcher': [0, 0], 'androidpermissionread_sms': [0, 0], 'androidpermissionbattery_stats': [0, 0], 'androidpermissionglobal_search': [0, 0], 'androidpermissionbind_nfc_service': [0, 0], 'androidpermissionpackage_usage_stats': [0, 0], 'androidpermissionset_always_finish': [0, 0], 'androidpermissionaccess_drm': [0, 0], 'androidpermissionbroadcast_sticky': [0, 0], 'androidpermissionmount_unmount_filesystems': [0, 0], 'label': ['malware', 'malware']}


来源: stackexchange

问:
Display Number Progress Bar ASPNet
first
aspx:

```<code><div class="row">
  <div class="col-sm-2">
   <asp:TextBox TextMode="Number" runat="server" ID="FromNum" placeholder="From"/>
  </div>
  <div class="col-sm-4">
   <asp:TextBox TextMode="Number" runat="server" ID="ToNum" placeholder="To"/>
  </div>
  <div class="col-sm-2">
    <asp:Button ID="BtnRec" Text="Go" runat="server" OnClick="Btn_Click" />
  </div>
</div>

 <div class="col-sm-2">
  <asp:Label runat="server" ID="Indication" />
</div>
</code>```

second
aspx.cs

```<code>protected void Btn_Click(object sender, EventArgs e)
{
    DataTable dataTable = SqlHelper.Client.GetDataTable(sql);;
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        string conMun = ((int)dataTable.Rows[i]["ConfirmNum"]).ToString();

        string subject = "No: " + conMun;
        this.Indication.Text = (i + 1).ToString() + " of" + dataTable.Rows.Count;
        this.SendEmail(subject, html, email); //mail
    }
}
</code>```

I need

Indication

to be constantly updated/refreshed by the number.
How can this be done?

ContentLicense: CC BY-SA 4.0

Title: Display Number Progress Bar ASPNet

Body:
first
aspx:

   <asp:TextBox TextMode="Number" runat="server" ID="FromNum" placeholder="From"/>

   <asp:TextBox TextMode="Number" runat="server" ID="ToNum" placeholder="To"/>

    <asp:Button ID="BtnRec" Text="Go" runat="server" OnClick="Btn_Click" />

  <asp:Label runat="server" ID="Indication" />

second
aspx.cs

protected void Btn_Click(object sender, EventArgs e)
{
    DataTable dataTable = SqlHelper.Client.GetDataTable(sql);;
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        string conMun = ((int)dataTable.Rows[i]["ConfirmNum"]).ToString();

        string subject = "No: " + conMun;
        this.Indication.Text = (i + 1).ToString() + " of" + dataTable.Rows.Count;
        this.SendEmail(subject, html, email); //mail
    }
}

I need

Indication

to be constantly updated/refreshed by the number.
How can this be done?


问:
What are problems here on Tenser flow with keras cnn problem
i ask what’s I doing to edait code in order preventing errors

I use keras model conv1d for raw dataset X_train= (142315, 23)
Y_train = (142315,)
my code

My code is

```<code>n_timesteps = X_train.shape[1] #23

input_layer = tensorflow.keras.layers.Input(shape=(n_timesteps,1))
conv_layer1 = tensorflow.keras.layers.Conv1D(filters=5,
kernel_size=7,
activation=”relu”)(input_layer)
max_pool1 = tensorflow.keras.layers.MaxPooling1D(pool_size=2, strides=5)(conv_layer1)

conv_layer2 = tensorflow.keras.layers.Conv1D(filters=3,
kernel_size=3,
activation=”relu”)(max_pool1)
flatten_layer = tensorflow.keras.layers.Flatten()(conv_layer2)
dense_layer = tensorflow.keras.layers.Dense(15, activation=”relu”)(flatten_layer)
output_layer = tensorflow.keras.layers.Dense(6, activation=”softmax”)(dense_layer)

model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)
# Prints a string summary of the network.
model.summary()
</code>```

and after that i use optimization technological for hyperprameters and when # Returning the details of the best solution. print this error can helpe me?????

error

5121 # Use logits whenever they are available. softmax and sigmoid

ValueError: Shapes (142315,)  Hi and (142315, 2) are incompatible

Body:
i ask what’s I doing to edait code in order preventing errors

I use keras model conv1d for raw dataset X_train= (142315, 23)
Y_train = (142315,)
my code

My code is

n_timesteps = X_train.shape[1] #23

input_layer = tensorflow.keras.layers.Input(shape=(n_timesteps,1))
conv_layer1 = tensorflow.keras.layers.Conv1D(filters=5,
kernel_size=7,
activation=”relu”)(input_layer)
max_pool1 = tensorflow.keras.layers.MaxPooling1D(pool_size=2, strides=5)(conv_layer1)

conv_layer2 = tensorflow.keras.layers.Conv1D(filters=3,
kernel_size=3,
activation=”relu”)(max_pool1)
flatten_layer = tensorflow.keras.layers.Flatten()(conv_layer2)
dense_layer = tensorflow.keras.layers.Dense(15, activation=”relu”)(flatten_layer)
output_layer = tensorflow.keras.layers.Dense(6, activation=”softmax”)(dense_layer)

model = tensorflow.keras.Model(inputs=input_layer, outputs=output_layer)
# Prints a string summary of the network.
model.summary()

and after that i use optimization technological for hyperprameters and when # Returning the details of the best solution. print this error can helpe me?????

error

5121 # Use logits whenever they are available. softmax and sigmoid

ValueError: Shapes (142315,)  Hi and (142315, 2) are incompatible


问:
Locateonscreen True then do ..... or with pixelmatch?
I have a def that looks  for a pixel match color if  this is true it looks for an image
can i replace this with locateonscreen? becorse the image position  change over time

this is my def and it works but i want to use locateonscreen instead of match color for the yellowbell i changed this to the code below can  this work?

```<code>
    i = 0
    #while pyautogui.pixelMatchesColor(YellowBellX , YellowBellY , (YellowR,YellowG,YellowB), tolerance = 20) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
    while pyautogui.locateOnScreen("YellowBell.png",region=(19,116,900,60), confidence=0.8) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
        if pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (blueR,blueG,blueB), tolerance = 20) == True:
            break

</code>```

Body:
I have a def that looks  for a pixel match color if  this is true it looks for an image
can i replace this with locateonscreen? becorse the image position  change over time

this is my def and it works but i want to use locateonscreen instead of match color for the yellowbell i changed this to the code below can  this work?

    i = 0
    #while pyautogui.pixelMatchesColor(YellowBellX , YellowBellY , (YellowR,YellowG,YellowB), tolerance = 20) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
    while pyautogui.locateOnScreen("YellowBell.png",region=(19,116,900,60), confidence=0.8) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
        if pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (blueR,blueG,blueB), tolerance = 20) == True:
            break


问:
Unable to upload video from C# (4.7 version) code to Azure media service
I am trying to upload video from c# to azure media service but unable to do it.Please help me if anyone have any idea how i can do it.</p>
```<code>static CloudMediaContext m_MediaContext;
static readonly string _AADTenantDomain = ConfigurationManager.AppSettings["AMSAADTenantDomain"];
static readonly string _RESTAPIEndpoint = ConfigurationManager.AppSettings["AMSRESTAPIEndpoint"];
static readonly string _AMSClientId = ConfigurationManager.AppSettings["AMSClientId"];
static readonly string _AMSClientSecret = ConfigurationManager.AppSettings["AMSClientSecret"];

azureadtokencredentials tokencredentials = new azureadtokencredentials(_aadtenantdomain, new azureadclientsymmetrickey(_amsclientid, _amsclientsecret), azureenvironments.azurecloudenvironment);
var tokenprovider = new azureadtokenprovider(tokencredentials);
m_mediacontext = new cloudmediacontext(new uri(_restapiendpoint), tokenprovider);                               uploadmedia(assetcreationoptions.none, imagename, file);

static private IAsset CreateAsset(string i_sAssetName, AssetCreationOptions i_AssetCreationOption)
{
var objAsset = m_MediaContext.Assets.Create(i_sAssetName, i_AssetCreationOption);
return objAsset;
}

static public void UploadMedia(AssetCreationOptions i_Option, string i_sFilePath, System.Web.HttpPostedFile file)
        {
            //Form a Name for asset
            var sDynamicAssetName = "Asset_" + DateTime.UtcNow.ToString();

            //Create a empty asset
            var objAsset = CreateAsset(sDynamicAssetName, i_Option);

            //Get filename with extension which needs to be associated with asset
            var fileName = i_sFilePath; //Path.GetFileName(i_sFilePath);

            //Create the asset file
            var objAssetFile = objAsset.AssetFiles.Create(fileName);

            //Create an AccessPolicy instance that defines the permissions and duration of access to the asset.
            var accessPolicy = m_MediaContext.AccessPolicies.Create(sDynamicAssetName, TimeSpan.FromDays(365 * 100), AccessPermissions.Write | AccessPermissions.List);

            //Create a Locator instance that provides access to the asset.
            var locator = m_MediaContext.Locators.CreateLocator(LocatorType.Sas, objAsset, accessPolicy);

            //Updoad the asset to Azure Storage
            var uploadStream = file.InputStream;
            //objAssetFile.Upload(i_sFilePath);
            objAssetFile.Upload(uploadStream);
            var hlsURI = objAsset.GetHlsUri();
            var mpegDashUri = objAsset.GetMpegDashUri();
            //Finally, Some Cleanup
            locator.Delete();
            accessPolicy.Delete();
            //Console.ReadLine();
        }
</code>```

Body:
I am trying to upload video from c# to azure media service but unable to do it.Please help me if anyone have any idea how i can do it.

static CloudMediaContext m_MediaContext;
static readonly string _AADTenantDomain = ConfigurationManager.AppSettings["AMSAADTenantDomain"];
static readonly string _RESTAPIEndpoint = ConfigurationManager.AppSettings["AMSRESTAPIEndpoint"];
static readonly string _AMSClientId = ConfigurationManager.AppSettings["AMSClientId"];
static readonly string _AMSClientSecret = ConfigurationManager.AppSettings["AMSClientSecret"];

azureadtokencredentials tokencredentials = new azureadtokencredentials(_aadtenantdomain, new azureadclientsymmetrickey(_amsclientid, _amsclientsecret), azureenvironments.azurecloudenvironment);
var tokenprovider = new azureadtokenprovider(tokencredentials);
m_mediacontext = new cloudmediacontext(new uri(_restapiendpoint), tokenprovider);                               uploadmedia(assetcreationoptions.none, imagename, file);

static private IAsset CreateAsset(string i_sAssetName, AssetCreationOptions i_AssetCreationOption)
{
var objAsset = m_MediaContext.Assets.Create(i_sAssetName, i_AssetCreationOption);
return objAsset;
}

static public void UploadMedia(AssetCreationOptions i_Option, string i_sFilePath, System.Web.HttpPostedFile file)
        {
            //Form a Name for asset
            var sDynamicAssetName = "Asset_" + DateTime.UtcNow.ToString();

            //Create a empty asset
            var objAsset = CreateAsset(sDynamicAssetName, i_Option);

            //Get filename with extension which needs to be associated with asset
            var fileName = i_sFilePath; //Path.GetFileName(i_sFilePath);

            //Create the asset file
            var objAssetFile = objAsset.AssetFiles.Create(fileName);

            //Create an AccessPolicy instance that defines the permissions and duration of access to the asset.
            var accessPolicy = m_MediaContext.AccessPolicies.Create(sDynamicAssetName, TimeSpan.FromDays(365 * 100), AccessPermissions.Write | AccessPermissions.List);

            //Create a Locator instance that provides access to the asset.
            var locator = m_MediaContext.Locators.CreateLocator(LocatorType.Sas, objAsset, accessPolicy);

            //Updoad the asset to Azure Storage
            var uploadStream = file.InputStream;
            //objAssetFile.Upload(i_sFilePath);
            objAssetFile.Upload(uploadStream);
            var hlsURI = objAsset.GetHlsUri();
            var mpegDashUri = objAsset.GetMpegDashUri();
            //Finally, Some Cleanup
            locator.Delete();
            accessPolicy.Delete();
            //Console.ReadLine();
        }


问:
How transformer predict future data with multiple features?
I want to design a time-series predicter to forecast stock price. And I follow the paper to construct a transformer model which I switch decoder to linear. So I met a question how do I know the future features data? If I only use date to training(like prophet) without other features, I think it may be not precisely enough.
My model be like:

```<code>class PositionalEncoding(nn.Module):
    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        '''
        x: [seq_len, batch_size, d_model]
        '''
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

def get_attn_pad_mask(seq_q, seq_k):                       # seq_q: [batch_size, seq_len] ,seq_k: [batch_size, seq_len]
    batch_size, len_q ,_= seq_q.size()         #1*64*5
    batch_size, len_k ,_= seq_k.size()
    # pad_attn_mask = seq_k.data.eq(0).unsqueeze(1)          # 判断 输入那些含有P(=0),用1标记 ,[batch_size, 1, len_k]
    pad_attn_mask = torch.ones(batch_size,len_q,len_k)     # 判断 输入那些含有P(=0),用1标记 ,[batch_size, 1, len_k]
    return pad_attn_mask  # 扩展成多维度

class ScaledDotProductAttention(nn.Module):
    def __init__(self):
        super(ScaledDotProductAttention, self).__init__()

    def forward(self, Q, K, V, attn_mask):  # Q: [batch_size, n_heads, len_q, d_k]
        # K: [batch_size, n_heads, len_k, d_k]
        # V: [batch_size, n_heads, len_v(=len_k), d_v]
        # attn_mask: [batch_size, n_heads, seq_len, seq_len]
        scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k)  # scores : [batch_size, n_heads, len_q, len_k]
        scores.masked_fill_(attn_mask, -1e9)  # 如果时停用词P就等于 0
        attn = nn.Softmax(dim=-1)(scores)
        context = torch.matmul(attn, V)  # [batch_size, n_heads, len_q, d_v]
        return context, attn

class MultiHeadAttention(nn.Module):
    def __init__(self):
        super(MultiHeadAttention, self).__init__()
        self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False).cuda()
        self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False).cuda()
        self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False).cuda()
        self.fc = nn.Linear(n_heads * d_v, d_model, bias=False).cuda()

    def forward(self, input_Q, input_K, input_V, attn_mask):  # input_Q: [batch_size, len_q, d_model]
        # input_K: [batch_size, len_k, d_model]
        # input_V: [batch_size, len_v(=len_k), d_model]
        # attn_mask: [batch_size, seq_len, seq_len]
        residual, batch_size = input_Q, input_Q.size(0)
        Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1, 2)  # Q: [batch_size, n_heads, len_q, d_k]
        K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1, 2)  # K: [batch_size, n_heads, len_k, d_k]
        V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)  # V: [batch_size, n_heads, len_v(=len_k), d_v]
        attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1).cuda().bool()  # attn_mask : [batch_size, n_heads, seq_len, seq_len]
        # print('data_type\n', attn_mask.bool())
        # pdb.set_trace()
        context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)  # context: [batch_size, n_heads, len_q, d_v]
        context = context.transpose(1, 2).reshape(batch_size, -1,
                                                  n_heads * d_v)  # context: [batch_size, len_q, n_heads * d_v]
        output = self.fc(context)  # [batch_size, len_q, d_model]
        return nn.LayerNorm(d_model).cuda()(output + residual), attn

class PoswiseFeedForwardNet(nn.Module):
    def __init__(self):
        super(PoswiseFeedForwardNet, self).__init__()
        self.fc = nn.Sequential(
            nn.Linear(d_model, d_ff, bias=False),
            nn.ReLU(),
            nn.Linear(d_ff, d_model, bias=False))

    def forward(self, inputs):  # inputs: [batch_size, seq_len, d_model]
        residual = inputs
        output = self.fc(inputs)
        return nn.LayerNorm(d_model).cuda()(output + residual)  # [batch_size, seq_len, d_model]

class EncoderLayer(nn.Module):
    def __init__(self):
        super(EncoderLayer, self).__init__()
        self.enc_self_attn = MultiHeadAttention().cuda()                                     # 多头注意力机制
        self.pos_ffn = PoswiseFeedForwardNet().cuda()                                        # 前馈神经网络

    def forward(self, enc_inputs, enc_self_attn_mask):                                # enc_inputs: [batch_size, src_len, d_model]
        #输入3个enc_inputs分别与W_q、W_k、W_v相乘得到Q、K、V                          # enc_self_attn_mask: [batch_size, src_len, src_len]
        enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs,    # enc_outputs: [batch_size, src_len, d_model],
                                               enc_self_attn_mask)                    # attn: [batch_size, n_heads, src_len, src_len]
        enc_outputs = self.pos_ffn(enc_outputs)                                       # enc_outputs: [batch_size, src_len, d_model]
        return enc_outputs, attn

class Encoder(nn.Module):
    def __init__(self):
        super(Encoder, self).__init__()
        self.src_emb = nn.Linear(15, d_model).cuda()
        self.pos_emb = PositionalEncoding(d_model).cuda()                            # 加入位置信息
        self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)]).cuda()

    def forward(self, enc_inputs):                                               # enc_inputs: [batch_size, src_len]
        enc_outputs = self.src_emb(enc_inputs)  # enc_outputs: [batch_size, src_len, d_model]
        # print('1',enc_outputs)
        enc_outputs = self.pos_emb(enc_outputs)  # enc_outputs: [batch_size, src_len, d_model]
        enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs)  # enc_self_attn_mask: [batch_size, src_len, src_len]
        enc_self_attns = []
        for layer in self.layers:
            enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)  # enc_outputs :   [batch_size, src_len, d_model],                                                                # enc_self_attn : [batch_size, n_heads, src_len, src_len]
            enc_self_attns.append(enc_self_attn)
        return enc_outputs, enc_self_attns

</code>```
```<code>class Transformer(nn.Module):
    def __init__(self):
        super(Transformer, self).__init__()
        self.Encoder = Encoder().cuda()
        self.Decoder = nn.Linear(d_model, 512).cuda()
        self.projection = nn.Linear(d_model, 1, bias=False).cuda()
        self.init_weights()
        # self.projection1 = nn.Linear(128, 1, bias=False)
    def init_weights(self):
        initrange = 0.1
        self.Decoder.bias.data.zero_()
        self.Decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, enc_inputs):                         # enc_inputs: [batch_size, src_len]                                                   # dec_inputs: [batch_size, tgt_len]
        enc_outputs, enc_self_attns = self.Encoder(enc_inputs)       # enc_outputs: [batch_size, src_len, d_model],
        dec_outputs = self.Decoder(enc_outputs)                                                            # enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
        dec_logits = self.projection(dec_outputs)                      # dec_logits: [batch_size, tgt_len, 1]
        # dec_logits = self.projection1(dec_logits)                      # dec_logits: [batch_size, tgt_len, 1]
        return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns
</code>```

I tied to make some future data by prophet, but I think this method is tricky. I want to know to use history data (up to today) to predict 5 more days result.

Body:
I want to design a time-series predicter to forecast stock price. And I follow the paper to construct a transformer model which I switch decoder to linear. So I met a question how do I know the future features data? If I only use date to training(like prophet) without other features, I think it may be not precisely enough.
My model be like:

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        '''
        x: [seq_len, batch_size, d_model]
        '''
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

def get_attn_pad_mask(seq_q, seq_k):                       # seq_q: [batch_size, seq_len] ,seq_k: [batch_size, seq_len]
    batch_size, len_q ,_= seq_q.size()         #1*64*5
    batch_size, len_k ,_= seq_k.size()
    # pad_attn_mask = seq_k.data.eq(0).unsqueeze(1)          # 判断 输入那些含有P(=0),用1标记 ,[batch_size, 1, len_k]
    pad_attn_mask = torch.ones(batch_size,len_q,len_k)     # 判断 输入那些含有P(=0),用1标记 ,[batch_size, 1, len_k]
    return pad_attn_mask  # 扩展成多维度

class ScaledDotProductAttention(nn.Module):
    def __init__(self):
        super(ScaledDotProductAttention, self).__init__()

    def forward(self, Q, K, V, attn_mask):  # Q: [batch_size, n_heads, len_q, d_k]
        # K: [batch_size, n_heads, len_k, d_k]
        # V: [batch_size, n_heads, len_v(=len_k), d_v]
        # attn_mask: [batch_size, n_heads, seq_len, seq_len]
        scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k)  # scores : [batch_size, n_heads, len_q, len_k]
        scores.masked_fill_(attn_mask, -1e9)  # 如果时停用词P就等于 0
        attn = nn.Softmax(dim=-1)(scores)
        context = torch.matmul(attn, V)  # [batch_size, n_heads, len_q, d_v]
        return context, attn

class MultiHeadAttention(nn.Module):
    def __init__(self):
        super(MultiHeadAttention, self).__init__()
        self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False).cuda()
        self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False).cuda()
        self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False).cuda()
        self.fc = nn.Linear(n_heads * d_v, d_model, bias=False).cuda()

    def forward(self, input_Q, input_K, input_V, attn_mask):  # input_Q: [batch_size, len_q, d_model]
        # input_K: [batch_size, len_k, d_model]
        # input_V: [batch_size, len_v(=len_k), d_model]
        # attn_mask: [batch_size, seq_len, seq_len]
        residual, batch_size = input_Q, input_Q.size(0)
        Q = self.W_Q(input_Q).view(batch_size, -1, n_heads, d_k).transpose(1, 2)  # Q: [batch_size, n_heads, len_q, d_k]
        K = self.W_K(input_K).view(batch_size, -1, n_heads, d_k).transpose(1, 2)  # K: [batch_size, n_heads, len_k, d_k]
        V = self.W_V(input_V).view(batch_size, -1, n_heads, d_v).transpose(1,2)  # V: [batch_size, n_heads, len_v(=len_k), d_v]
        attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1).cuda().bool()  # attn_mask : [batch_size, n_heads, seq_len, seq_len]
        # print('data_type\n', attn_mask.bool())
        # pdb.set_trace()
        context, attn = ScaledDotProductAttention()(Q, K, V, attn_mask)  # context: [batch_size, n_heads, len_q, d_v]
        context = context.transpose(1, 2).reshape(batch_size, -1,
                                                  n_heads * d_v)  # context: [batch_size, len_q, n_heads * d_v]
        output = self.fc(context)  # [batch_size, len_q, d_model]
        return nn.LayerNorm(d_model).cuda()(output + residual), attn

class PoswiseFeedForwardNet(nn.Module):
    def __init__(self):
        super(PoswiseFeedForwardNet, self).__init__()
        self.fc = nn.Sequential(
            nn.Linear(d_model, d_ff, bias=False),
            nn.ReLU(),
            nn.Linear(d_ff, d_model, bias=False))

    def forward(self, inputs):  # inputs: [batch_size, seq_len, d_model]
        residual = inputs
        output = self.fc(inputs)
        return nn.LayerNorm(d_model).cuda()(output + residual)  # [batch_size, seq_len, d_model]

class EncoderLayer(nn.Module):
    def __init__(self):
        super(EncoderLayer, self).__init__()
        self.enc_self_attn = MultiHeadAttention().cuda()                                     # 多头注意力机制
        self.pos_ffn = PoswiseFeedForwardNet().cuda()                                        # 前馈神经网络

    def forward(self, enc_inputs, enc_self_attn_mask):                                # enc_inputs: [batch_size, src_len, d_model]
        #输入3个enc_inputs分别与W_q、W_k、W_v相乘得到Q、K、V                          # enc_self_attn_mask: [batch_size, src_len, src_len]
        enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs,    # enc_outputs: [batch_size, src_len, d_model],
                                               enc_self_attn_mask)                    # attn: [batch_size, n_heads, src_len, src_len]
        enc_outputs = self.pos_ffn(enc_outputs)                                       # enc_outputs: [batch_size, src_len, d_model]
        return enc_outputs, attn

class Encoder(nn.Module):
    def __init__(self):
        super(Encoder, self).__init__()
        self.src_emb = nn.Linear(15, d_model).cuda()
        self.pos_emb = PositionalEncoding(d_model).cuda()                            # 加入位置信息
        self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)]).cuda()

    def forward(self, enc_inputs):                                               # enc_inputs: [batch_size, src_len]
        enc_outputs = self.src_emb(enc_inputs)  # enc_outputs: [batch_size, src_len, d_model]
        # print('1',enc_outputs)
        enc_outputs = self.pos_emb(enc_outputs)  # enc_outputs: [batch_size, src_len, d_model]
        enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs)  # enc_self_attn_mask: [batch_size, src_len, src_len]
        enc_self_attns = []
        for layer in self.layers:
            enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)  # enc_outputs :   [batch_size, src_len, d_model],                                                                # enc_self_attn : [batch_size, n_heads, src_len, src_len]
            enc_self_attns.append(enc_self_attn)
        return enc_outputs, enc_self_attns

class Transformer(nn.Module):
    def __init__(self):
        super(Transformer, self).__init__()
        self.Encoder = Encoder().cuda()
        self.Decoder = nn.Linear(d_model, 512).cuda()
        self.projection = nn.Linear(d_model, 1, bias=False).cuda()
        self.init_weights()
        # self.projection1 = nn.Linear(128, 1, bias=False)
    def init_weights(self):
        initrange = 0.1
        self.Decoder.bias.data.zero_()
        self.Decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, enc_inputs):                         # enc_inputs: [batch_size, src_len]                                                   # dec_inputs: [batch_size, tgt_len]
        enc_outputs, enc_self_attns = self.Encoder(enc_inputs)       # enc_outputs: [batch_size, src_len, d_model],
        dec_outputs = self.Decoder(enc_outputs)                                                            # enc_self_attns: [n_layers, batch_size, n_heads, src_len, src_len]
        dec_logits = self.projection(dec_outputs)                      # dec_logits: [batch_size, tgt_len, 1]
        # dec_logits = self.projection1(dec_logits)                      # dec_logits: [batch_size, tgt_len, 1]
        return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns

I tied to make some future data by prophet, but I think this method is tricky. I want to know to use history data (up to today) to predict 5 more days result.


问:
Updating state, gives empty state in react redux toolkit
Am trying to make a login and add the return data to state, when I try to update state, it still gets empty state. I have added the code below, Please help me fix it. Am using RTK query to make the login mutation, and am new to this.

My AuthApi.js

```<code>import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { api } from "./api";

export const authApi = createApi({
    reducerPath: "authApi",
    baseQuery: fetchBaseQuery({
        baseUrl: api
    }),

    endpoints: (builder) => ({
        loginUser: builder.mutation({
            query: (body) => {
                return {
                    url: "login",
                    method: "post",
                    body,
                };
            },
        }),
        registerUser: builder.mutation({
            query: (body) => {
                return {
                    url: "register",
                    method: "post",
                    body,
                };
            },
        }),
    }),
});

export const { useLoginUserMutation, useRegisterUserMutation } = authApi;
</code>```

My userSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";
import { authApi } from "../../services/authApi";

const initialState = {
  role: null,
  accessToken: null,
  userData: null
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logout: (state) => {
      state.currentUser = null;
      state.errorMessage = ''
    }
  },
  extraReducers: (builders) => {
    builders.addMatcher(authApi.endpoints.loginUser.matchFulfilled, (state, action) => {
      state.userData = action.payload.success.data
      state.accessToken = action.payload.success.accessToken
      state.role = action.payload.success.roles
    })
  }
})

export const { logout } = userSlice.actions

export const selectUser = (state) => state.user.accessToken

export default userSlice.reducer
</code>```

my store.js

```<code>import { configureStore } from "@reduxjs/toolkit";
import { authApi } from "../services/authApi";
import userReducer from './slices/userSlice'

const store = configureStore({
    reducer: {
        [authApi.reducerPath]: authApi.reducer,
        user: userReducer,
    },

    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(authApi.middleware),
});

export default store;
</code>```

console.log(action.payload) in userSlice extraReducer gives me the data in console, but it is not updating the state.

Body:
Am trying to make a login and add the return data to state, when I try to update state, it still gets empty state. I have added the code below, Please help me fix it. Am using RTK query to make the login mutation, and am new to this.

My AuthApi.js

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { api } from "./api";

export const authApi = createApi({
    reducerPath: "authApi",
    baseQuery: fetchBaseQuery({
        baseUrl: api
    }),

    endpoints: (builder) => ({
        loginUser: builder.mutation({
            query: (body) => {
                return {
                    url: "login",
                    method: "post",
                    body,
                };
            },
        }),
        registerUser: builder.mutation({
            query: (body) => {
                return {
                    url: "register",
                    method: "post",
                    body,
                };
            },
        }),
    }),
});

export const { useLoginUserMutation, useRegisterUserMutation } = authApi;

My userSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { authApi } from "../../services/authApi";

const initialState = {
  role: null,
  accessToken: null,
  userData: null
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logout: (state) => {
      state.currentUser = null;
      state.errorMessage = ''
    }
  },
  extraReducers: (builders) => {
    builders.addMatcher(authApi.endpoints.loginUser.matchFulfilled, (state, action) => {
      state.userData = action.payload.success.data
      state.accessToken = action.payload.success.accessToken
      state.role = action.payload.success.roles
    })
  }
})

export const { logout } = userSlice.actions

export const selectUser = (state) => state.user.accessToken

export default userSlice.reducer

my store.js

import { configureStore } from "@reduxjs/toolkit";
import { authApi } from "../services/authApi";
import userReducer from './slices/userSlice'

const store = configureStore({
    reducer: {
        [authApi.reducerPath]: authApi.reducer,
        user: userReducer,
    },

    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(authApi.middleware),
});

export default store;

console.log(action.payload) in userSlice extraReducer gives me the data in console, but it is not updating the state.


问:
Gaussian Mixture Model Plot for Soft Assignment by Color
enter image description here)

I want to show soft assignment by probabilities from GMM looking similar to the image posted. I want to show a data points membership between two (or more clusters).

Any help would be appreciated.

I tried to multiply probabilities from maximum of predict_proba(X) but it seems not working as it is not applied to labels=0.

ax.scatter(X[:, 0], X[:, 1], c=labels*probability)


问:
GA reporting API v4 fetches duplicate rows and misses relevant row when called recursively by changing the pageToken value
I am trying to extract 1-day data from ga reporting API v4 using python, I am calling the API recursively 10 times using consecutive pageTokens. The data extract has no sampling but each call has a few rows(200-1400) which are identical to data rows from the previous call. The data is extracted from the following code:

```<code>response = service.reports().batchGet(body=request).execute()
</code>```

The issue is that instead of fetching correct rows the API is fetching duplicate data rows. So, even if the number of total rows extracted is correct some of the data rows are missing, and instead there is row duplication in its place

When the dimension and metrics are not related to the event and even though more metrics and dimensions are added to the request, the extracted data is correct.

Example Input:

```<code>{'reportRequests': [{'viewId': ‘XXXX’,
                      'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                      'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                  {'expression': 'ga:uniqueEvents'}],
                      'dimensions': [{"name": "ga:date"},
                                     {"name": "ga:deviceCategory"},
                                     {"name": "ga:sourceMedium"},
                                     {"name": "ga:campaign"},
                                     {"name": "ga:region"},
                                     {"name": "ga:pagePath"},
                                     {"name": "ga:eventCategory"},
                                     {"name": "ga:eventAction"},
                                     {"name": "ga:eventLabel"}],

                      'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                      'pageSize': 100000, 'pageToken': None, 'samplingLevel': 'LARGE'}]}
</code>```

I have tried the following:

Reducing the dimensions

Adding orderbys parameter to the request

Adding 1 to pageTokens parameter, to avoid overlapping

but it only reduces the number of duplicate rows.

When data is directly exported from Google analysis to data studio, it does not have duplicates. I am trying to extract data without duplicates and exactly how it is stored in google analytics. Is there a way duplication could be avoided?

Below is the code which can be used to reproducible this problem, provided that the data is large enough to create 3-4 pageTokens, i.e. data should have 300,000 and above number of rows

```<code>
from googleapiclient.discovery import build
from google.oauth2 import service_account
import pandas as pd

def print_response(response):
    list = []
    # get report data
    for report in response.get('reports', []):
        # set column headers
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])

        for row in rows:
            # create dict for each row
            dict = {}
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

            # fill dict with dimension header (key) and dimension value (value)
            for header, dimension in zip(dimensionHeaders, dimensions):
                dict[header] = dimension

            # fill dict with metric header (key) and metric value (value)
            for i, values in enumerate(dateRangeValues):
                for metric, value in zip(metricHeaders, values.get('values')):
                    # set int as int, float a float
                    if ',' in value or '.' in value:
                        dict[metric.get('name')] = float(value)
                    else:
                        dict[metric.get('name')] = int(value)

            list.append(dict)

        df = pd.DataFrame(list)
        return df

def nextToken(pageToken):
    body = {'reportRequests': [{'viewId': '1587525',
                                'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                                'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                            {'expression': 'ga:uniqueEvents'}],
                                'dimensions': [{"name": "ga:date"},
                                               {"name": "ga:deviceCategory"},
                                               {"name": "ga:sourceMedium"},
                                               {"name": "ga:campaign"},
                                               {"name": "ga:region"},
                                               {"name": "ga:pagePath"},
                                               {"name": "ga:eventCategory"},
                                               {"name": "ga:eventAction"},
                                               {"name": "ga:eventLabel"}],

                                'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                                'pageSize': 100000, 'pageToken': pageToken, 'samplingLevel': 'LARGE'}]}
    credentials_analytics = service_account.Credentials.from_service_account_file("service_key.json",
                                                                                scopes=[
                                                                                'https://www.googleapis.com/auth/analytics.readonly',
                                                                                'https://www.googleapis.com/auth/analytics.manage.users'])

    service = build('analyticsreporting', 'v4', credentials=credentials_analytics)
    response = service.reports().batchGet(body=body).execute()

    return response

def main(request):

    body= {'reportRequests': [{'viewId': 'XXXXXX',
                      'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                      'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                  {'expression': 'ga:uniqueEvents'}],
                      'dimensions': [{"name": "ga:date"},
                                     {"name": "ga:deviceCategory"},
                                     {"name": "ga:sourceMedium"},
                                     {"name": "ga:campaign"},
                                     {"name": "ga:region"},
                                     {"name": "ga:pagePath"},
                                     {"name": "ga:eventCategory"},
                                     {"name": "ga:eventAction"},
                                     {"name": "ga:eventLabel"}],

                      'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                      'pageSize': 100000, 'pageToken': None, 'samplingLevel': 'LARGE'}]}

#creadentials for google account service
    credentials_analytics = service_account.Credentials.from_service_account_file("service_key.json",
                                                                                scopes=[
                                                                                'https://www.googleapis.com/auth/analytics.readonly',
                                                                                'https://www.googleapis.com/auth/analytics.manage.users'])

    service = build('analyticsreporting', 'v4', credentials=credentials_analytics)
# API call
    response = service.reports().batchGet(body=body).execute()
# converting response into data frame
    df = print_response(response)
# looping through the pageToken
    while response['reports'][0].get('nextPageToken') is not None:
# get data for the next Token
        response = nextToken(response['reports'][0].get('nextPageToken'))
        tmp = print_response(response)
        frame =[df,tmp]
        df = pd.concat(frame,axis=0)

main()

</code>```

Body:
I am trying to extract 1-day data from ga reporting API v4 using python, I am calling the API recursively 10 times using consecutive pageTokens. The data extract has no sampling but each call has a few rows(200-1400) which are identical to data rows from the previous call. The data is extracted from the following code:

response = service.reports().batchGet(body=request).execute()

The issue is that instead of fetching correct rows the API is fetching duplicate data rows. So, even if the number of total rows extracted is correct some of the data rows are missing, and instead there is row duplication in its place

When the dimension and metrics are not related to the event and even though more metrics and dimensions are added to the request, the extracted data is correct.

Example Input:

{'reportRequests': [{'viewId': ‘XXXX’,
                      'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                      'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                  {'expression': 'ga:uniqueEvents'}],
                      'dimensions': [{"name": "ga:date"},
                                     {"name": "ga:deviceCategory"},
                                     {"name": "ga:sourceMedium"},
                                     {"name": "ga:campaign"},
                                     {"name": "ga:region"},
                                     {"name": "ga:pagePath"},
                                     {"name": "ga:eventCategory"},
                                     {"name": "ga:eventAction"},
                                     {"name": "ga:eventLabel"}],

                      'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                      'pageSize': 100000, 'pageToken': None, 'samplingLevel': 'LARGE'}]}

I have tried the following:

Reducing the dimensions

Adding orderbys parameter to the request

Adding 1 to pageTokens parameter, to avoid overlapping

but it only reduces the number of duplicate rows.

When data is directly exported from Google analysis to data studio, it does not have duplicates. I am trying to extract data without duplicates and exactly how it is stored in google analytics. Is there a way duplication could be avoided?

Below is the code which can be used to reproducible this problem, provided that the data is large enough to create 3-4 pageTokens, i.e. data should have 300,000 and above number of rows

from googleapiclient.discovery import build
from google.oauth2 import service_account
import pandas as pd

def print_response(response):
    list = []
    # get report data
    for report in response.get('reports', []):
        # set column headers
        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])

        for row in rows:
            # create dict for each row
            dict = {}
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

            # fill dict with dimension header (key) and dimension value (value)
            for header, dimension in zip(dimensionHeaders, dimensions):
                dict[header] = dimension

            # fill dict with metric header (key) and metric value (value)
            for i, values in enumerate(dateRangeValues):
                for metric, value in zip(metricHeaders, values.get('values')):
                    # set int as int, float a float
                    if ',' in value or '.' in value:
                        dict[metric.get('name')] = float(value)
                    else:
                        dict[metric.get('name')] = int(value)

            list.append(dict)

        df = pd.DataFrame(list)
        return df

def nextToken(pageToken):
    body = {'reportRequests': [{'viewId': '1587525',
                                'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                                'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                            {'expression': 'ga:uniqueEvents'}],
                                'dimensions': [{"name": "ga:date"},
                                               {"name": "ga:deviceCategory"},
                                               {"name": "ga:sourceMedium"},
                                               {"name": "ga:campaign"},
                                               {"name": "ga:region"},
                                               {"name": "ga:pagePath"},
                                               {"name": "ga:eventCategory"},
                                               {"name": "ga:eventAction"},
                                               {"name": "ga:eventLabel"}],

                                'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                                'pageSize': 100000, 'pageToken': pageToken, 'samplingLevel': 'LARGE'}]}
    credentials_analytics = service_account.Credentials.from_service_account_file("service_key.json",
                                                                                scopes=[
                                                                                'https://www.googleapis.com/auth/analytics.readonly',
                                                                                'https://www.googleapis.com/auth/analytics.manage.users'])

    service = build('analyticsreporting', 'v4', credentials=credentials_analytics)
    response = service.reports().batchGet(body=body).execute()

    return response

def main(request):

    body= {'reportRequests': [{'viewId': 'XXXXXX',
                      'dateRanges': [{'startDate': '2022-11-01', 'endDate': '2022-11-01'}],
                      'metrics': [{'expression': 'ga:eventValue'}, {'expression': 'ga:totalEvents'},
                                  {'expression': 'ga:uniqueEvents'}],
                      'dimensions': [{"name": "ga:date"},
                                     {"name": "ga:deviceCategory"},
                                     {"name": "ga:sourceMedium"},
                                     {"name": "ga:campaign"},
                                     {"name": "ga:region"},
                                     {"name": "ga:pagePath"},
                                     {"name": "ga:eventCategory"},
                                     {"name": "ga:eventAction"},
                                     {"name": "ga:eventLabel"}],

                      'orderBys': [{'fieldName': 'ga:uniqueEvents', 'sortOrder': 'DESCENDING'}],
                      'pageSize': 100000, 'pageToken': None, 'samplingLevel': 'LARGE'}]}

#creadentials for google account service
    credentials_analytics = service_account.Credentials.from_service_account_file("service_key.json",
                                                                                scopes=[
                                                                                'https://www.googleapis.com/auth/analytics.readonly',
                                                                                'https://www.googleapis.com/auth/analytics.manage.users'])

    service = build('analyticsreporting', 'v4', credentials=credentials_analytics)
# API call
    response = service.reports().batchGet(body=body).execute()
# converting response into data frame
    df = print_response(response)
# looping through the pageToken
    while response['reports'][0].get('nextPageToken') is not None:
# get data for the next Token
        response = nextToken(response['reports'][0].get('nextPageToken'))
        tmp = print_response(response)
        frame =[df,tmp]
        df = pd.concat(frame,axis=0)

main()


问:
Chunking in Spark Dataframe
I have a spark dataframe named a which holds 5000 records and I am sending the data to hive and API to batches of 100 since that is the limit API accepts data using another dataframe b which I am cachcing . I am using dataframe.cache() for consistency. If I am trying to store data less than 3000 records in cache() using dataframe.cache() I am having no issues. But if the data crosses 4000 records I get an error. If I use unpersist and even if blocking is true in the parameter dataframe.unpersist(true) at //1 in the code or even if I use spark.catalog.clearCache() I get inconsistent results that is why I am unable to use it in my code. How do I free up my heap space and get constitent results?

ERROR org.apache.spark.util.Utils: uncaught error in thread spark-listener-group-eventLog, stopping SparkContext
java.lang.OutOfMemoryError: Java heap space

```<code>    val a=df

    val c =100

    while (a.count()>0){

      //Splitting dataframe in batch of c
      var b=spark.emptyDataFrame

      b = a.limit(c).cache()
      a=a.exceptAll(b)

      //Hive logs
      writeHiveLogs(b)

      //Payload to send to API
      val Json = createJSONOrgPayload(b)

      val postapi = posttoapi(config,Json)

      //1 b = b.unpersist(true)

    }
</code>```

I was trying to perform chunking of data but when there is huge data that I am trying to cache() I get java heap space issue. Is heap space issue related to dataframe.cache() memory not being sufficient or does it have to do with the spark configuration. If I use unpersist or clearcache(). I am getting inconsistent results

Title: Chunking in Spark Dataframe

Body:
I have a spark dataframe named a which holds 5000 records and I am sending the data to hive and API to batches of 100 since that is the limit API accepts data using another dataframe b which I am cachcing . I am using dataframe.cache() for consistency. If I am trying to store data less than 3000 records in cache() using dataframe.cache() I am having no issues. But if the data crosses 4000 records I get an error. If I use unpersist and even if blocking is true in the parameter dataframe.unpersist(true) at //1 in the code or even if I use spark.catalog.clearCache() I get inconsistent results that is why I am unable to use it in my code. How do I free up my heap space and get constitent results?

ERROR org.apache.spark.util.Utils: uncaught error in thread spark-listener-group-eventLog, stopping SparkContext
java.lang.OutOfMemoryError: Java heap space

    val a=df

    val c =100

    while (a.count()>0){

      //Splitting dataframe in batch of c
      var b=spark.emptyDataFrame

      b = a.limit(c).cache()
      a=a.exceptAll(b)

      //Hive logs
      writeHiveLogs(b)

      //Payload to send to API
      val Json = createJSONOrgPayload(b)

      val postapi = posttoapi(config,Json)

      //1 b = b.unpersist(true)

    }

I was trying to perform chunking of data but when there is huge data that I am trying to cache() I get java heap space issue. Is heap space issue related to dataframe.cache() memory not being sufficient or does it have to do with the spark configuration. If I use unpersist or clearcache(). I am getting inconsistent results


问:
How do you make a Sprite Rotate to where your cursor is?
I'm quite stupid, and I'm making a small pygame game that requires the player to move and rotate towards the mouse, one in a confined or unconfined area. For, now, just give the solution for the rotation, and if you can solve the other part, Thanks in advance!

I tried to get the mouse pos, and then try to find a command that can self-initiate the process, but obviously, didn't work.


问:
mov_cli Python package not installing
I was trying to install the mov_cli package and it was showing legacy-install-failure
Is there any specific reason

pip install mov_cli

legacy-install-failure

Title: mov_cli Python package not installing


问:
getting absolute path of mount point in linux kernel
I'm currently working on enhancment to FAT file system implmentation in the linux kernel. I need to know just after a mount, what is the absolute path to the mount point. I tried different approaches, but it seems that the VFS mount and the actual mount are not binded. Does anyone has an idea how to accomplish that ?</p>

ContentLicense: CC BY-SA 3.0


问:
Using both, @ConstructorProperties and @JsonCreator on POJO constructor
I have a very weird problem which is forcing me to use @JsonCreator and @ConstructorProperties, both, on a java POJO.

Actually, I am trying to use protobuf with mapstruct. The POJOs that we have in our codebase have private final fields and a constructor annotated with @JsonCreator for deserilization purposes. Now, while I am trying to map my protobuf objects to java POJOs, mapstruct was setting all the attributes in the POJO as null. While reading mapstruct documentation, "Using Constructors" section, I got to know that we can use @ConstructorProperties, which is working for me as well. I wanted to know if we use both @JsonCreator and @ConstructorProperties on the same constructor. Am I expected to run into some issues?


问:
How to add a breaking row that my auto fil formula shuld not run after that row?
I my Excel sheet, I have more than 200 thousand rows data in multiple columns, once I use "fill down" option to a column, that fills the entire column (more than 1 million) with the fourmula and the PC will start hanging.
So I need to set a cell or row line which breaks the foumula from auto filling after that cell or row.

Here you can see the empty active cell also filled with the formula and it is running out of the boundary. So I need to stop running the formula when I use "fill down" option after 268,425th row.
How can I do that?


问:
Keyboard doesn't show when set hint in edit text onFocusChangeListener Android Kotlin
If I set hint programatically on focus of the edit field, then the keyboard doesn't pop up as normally would do if the hint wasn't modified inside this method. Therefore I have to click 2 times on the edit text field in order to show the keyboard.

I want to understand why it behaves this way. Any thoughts?

```<code>editText.onFocusChangeListener = View.OnFocusChangeListener { _, focused ->
       editText.hint = ...
}
</code>```

Body:
If I set hint programatically on focus of the edit field, then the keyboard doesn't pop up as normally would do if the hint wasn't modified inside this method. Therefore I have to click 2 times on the edit text field in order to show the keyboard.

I want to understand why it behaves this way. Any thoughts?

editText.onFocusChangeListener = View.OnFocusChangeListener { _, focused ->
       editText.hint = ...
}


问:
Isn't it possible to create two different AppModule with NestJS?
For normal usage, it works well with app.module.ts and main.ts.

app.module.ts

    import { MiddlewareConsumer, Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import jwt from 'express-jwt';

    import config from './config';

    @Module({
      imports: [
        ConfigModule.forRoot({
          isGlobal: true,
          load: [config],
          envFilePath: '.env',
        }),
        TypeOrmModule.forRootAsync({
          inject: [ConfigService],
          useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }),
        }),
        GraphqlModule,
      ],
      controllers: [],
    })
    export class AppModule {
      constructor(private config: ConfigService) {}

      configure(consumer: MiddlewareConsumer) {
        consumer
          .forRoutes('graphql');
      }
    }
```
<p>main.ts</p>
<pre class="lang-js prettyprint-override"><code>    import { INestApplication } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import { NestFactory } from '@nestjs/core';
    import compression from 'compression';
    import { createConnection } from 'typeorm';

    import { AppModule } from './app.module';

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      app.use(compression());

      const config = app.get(ConfigService);

      if (config.get('pubsub.enable')) {
        const pubsubConnection = await createConnection(
          Object.assign(config.get('db'), { name: 'pubsub' }),
        );
        .....
      }

      useContainer(app.select(AppModule), { fallbackOnErrors: true });

      const server = await app.listen(config.get('PORT', ''));
      server.setTimeout(3 * 60 * 1000);
    }

    bootstrap();
</code>```

But if add another app.test.module.ts with a new name

app.test.module.ts

    import { MiddlewareConsumer, Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import jwt from 'express-jwt';

    import config from './config';

    @Module({
      imports: [
        ConfigModule.forRoot({
          isGlobal: true,
          load: [config],
          envFilePath: '.env.test',
        }),
        TypeOrmModule.forRootAsync({
          inject: [ConfigService],
          useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }),
        }),
        GraphqlModule,
      ],
      controllers: [],
    })
    export class AppTestModule {
      constructor(private config: ConfigService) {}

      configure(consumer: MiddlewareConsumer) {
        consumer
          .forRoutes('graphql');
      }
    }
```
<p>It will fail when db connection. It said can't find the default connection name but it exists in the config.ts.</p>
<p>In the main.ts, it only importing <code>AppModule</code> class but why can't work well for the whole application?</p>
<p>Some NestJS related packages:</p>
<pre class="lang-js prettyprint-override"><code>      "dependencies": {
        "@nestjs/cli": "^8.2.6",
        "@nestjs/common": "^8.4.5",
        "@nestjs/config": "^2.0.1",
        "@nestjs/core": "^8.4.5",
        "@nestjs/graphql": "^9.1.1",
        "@nestjs/platform-express": "^8.4.5",
        "@nestjs/swagger": "^5.2.1",
        "@nestjs/typeorm": "^8.0.2",
      "devDependencies": {
        "@nestjs/testing": "^8.4.7",
</code>```

Body:
For normal usage, it works well with app.module.ts and main.ts.

app.module.ts

    import { MiddlewareConsumer, Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import jwt from 'express-jwt';

    import config from './config';

    @Module({
      imports: [
        ConfigModule.forRoot({
          isGlobal: true,
          load: [config],
          envFilePath: '.env',
        }),
        TypeOrmModule.forRootAsync({
          inject: [ConfigService],
          useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }),
        }),
        GraphqlModule,
      ],
      controllers: [],
    })
    export class AppModule {
      constructor(private config: ConfigService) {}

      configure(consumer: MiddlewareConsumer) {
        consumer
          .forRoutes('graphql');
      }
    }

main.ts

    import { INestApplication } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import { NestFactory } from '@nestjs/core';
    import compression from 'compression';
    import { createConnection } from 'typeorm';

    import { AppModule } from './app.module';

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      app.use(compression());

      const config = app.get(ConfigService);

      if (config.get('pubsub.enable')) {
        const pubsubConnection = await createConnection(
          Object.assign(config.get('db'), { name: 'pubsub' }),
        );
        .....
      }

      useContainer(app.select(AppModule), { fallbackOnErrors: true });

      const server = await app.listen(config.get('PORT', ''));
      server.setTimeout(3 * 60 * 1000);
    }

    bootstrap();

But if add another app.test.module.ts with a new name

app.test.module.ts

    import { MiddlewareConsumer, Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import jwt from 'express-jwt';

    import config from './config';

    @Module({
      imports: [
        ConfigModule.forRoot({
          isGlobal: true,
          load: [config],
          envFilePath: '.env.test',
        }),
        TypeOrmModule.forRootAsync({
          inject: [ConfigService],
          useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }),
        }),
        GraphqlModule,
      ],
      controllers: [],
    })
    export class AppTestModule {
      constructor(private config: ConfigService) {}

      configure(consumer: MiddlewareConsumer) {
        consumer
          .forRoutes('graphql');
      }
    }

It will fail when db connection. It said can't find the default connection name but it exists in the config.ts.

In the main.ts, it only importing AppModule class but why can't work well for the whole application?

Some NestJS related packages:

      "dependencies": {
        "@nestjs/cli": "^8.2.6",
        "@nestjs/common": "^8.4.5",
        "@nestjs/config": "^2.0.1",
        "@nestjs/core": "^8.4.5",
        "@nestjs/graphql": "^9.1.1",
        "@nestjs/platform-express": "^8.4.5",
        "@nestjs/swagger": "^5.2.1",
        "@nestjs/typeorm": "^8.0.2",
      "devDependencies": {
        "@nestjs/testing": "^8.4.7",


问:
How to send multiple comments to content.js from popup.js?

Actual behavior:

When I click any single button like btn1/btn2/btn3, the console shows "message",
"message 2" and "message 3".

Expected behavior:

When I click button 1, the console should show the text "message".

When I click button 2, the console should show the text "message 2".

When I click button 3, the console should show the text "message 3".

Popup.js

```<code> document.querySelector('#btn1').addEventListener('click', function(){
      let message= document.getElementById('one-input').value
           chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
           chrome.tabs.sendMessage(tabs[0].id, message );
         })

 document.querySelector('#btn2').addEventListener('click', function(){
      let message2= document.getElementById('two-input').value;
           chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
           chrome.tabs.sendMessage(tabs[0].id, message2);
         });

        document.querySelector('#btn3').addEventListener('click', function(){
      let message3= document.getElementById('three-input').value;
         chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
         chrome.tabs.sendMessage(tabs[0].id, message3);
         });
</code>```

Content.js

```<code>chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {
       console.log("message")

chrome.runtime.onMessage.addListener(
  function(message2,sender, sendResponse ) {
      console.log("message2")

chrome.runtime.onMessage.addListener(
  function(message3, sender, sendResponse) {
      console.log("message3")
</code>```

Body:
Actual behavior:

When I click any single button like btn1/btn2/btn3, the console shows "message",
"message 2" and "message 3".

Expected behavior:

When I click button 1, the console should show the text "message".

When I click button 2, the console should show the text "message 2".

When I click button 3, the console should show the text "message 3".

Popup.js

 document.querySelector('#btn1').addEventListener('click', function(){
      let message= document.getElementById('one-input').value
           chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
           chrome.tabs.sendMessage(tabs[0].id, message );
         })

 document.querySelector('#btn2').addEventListener('click', function(){
      let message2= document.getElementById('two-input').value;
           chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
           chrome.tabs.sendMessage(tabs[0].id, message2);
         });

        document.querySelector('#btn3').addEventListener('click', function(){
      let message3= document.getElementById('three-input').value;
         chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
         chrome.tabs.sendMessage(tabs[0].id, message3);
         });

Content.js

chrome.runtime.onMessage.addListener(
  function(message, sender, sendResponse) {
       console.log("message")

chrome.runtime.onMessage.addListener(
  function(message2,sender, sendResponse ) {
      console.log("message2")

chrome.runtime.onMessage.addListener(
  function(message3, sender, sendResponse) {
      console.log("message3")


问:
table showing white space instead of actual content on scrolling horizontally (only in mobile)
when the page is rendered the first time the table is showing a part of the content then the rest of the width is white space and no content showing, if I use the pagination and go to page 2 then back to page 1, the table is all shown but then if I scroll to the right then back to the left it goes white again

here you can see the white space I'm talking about

and here's what should be there (and as I said I got this when I paginated to page 2 then back to 1)

I'm using Vuejs and BootstrapVue table. I don't know what other info would be useful here.

I don't even know where to start, because when I use chrome devtools to open mobile view, this problem doesn't occur.. I'm really clueless!

-- UPDATE --

here's the live link: https://business-abdal-dev.code95.info/ar/invoices/salary-invoices/details/ec599492-a622-ed11-8131-00224899ee26

and this is the code of the table:

```<code>            <b-table :items="paginatedData" :fields="fields">
              <template #cell()="data" v-if="invoice.details.status.key == 2">
                <div
                  class="edit-cell cursor-pointer"
                  v-if="data.field.editable"
                  @click="
                    data.item.startEdit = true;
                    inEditField = data.field.key;
                  "
                >
                  <input
                    class="form-control"
                    type="number"
                    min="0"
                    required
                    v-model="tableData[data.index][data.field.key]"
                    v-validate="'required|decimal|min:0'"
                    v-show="data.item.startEdit && inEditField == data.field.key"
                    :name="`${data.field.key}__${data.index}`"
                    :data-vv-as="data.field.label"
                    @blur="
                      setEditedValue(
                        data.item,
                        data.index,
                        data.field.key,
                        $event,
                        data.item.InvoiceDetailsId
                      )
                    "
                    @keydown.enter.prevent="
                      setEditedValue(
                        data.item,
                        data.index,
                        data.field.key,
                        $event,
                        data.item.InvoiceDetailsId,
                        data.field.equation
                      )
                    "
                  />

                  <span v-show="!data.item.startEdit || inEditField !== data.field.key">
                    {{ data.value }}
                  </span>
                  <template v-if="data.field.validate.length">
                    <div v-for="(rule, i) in data.field.validate" :key="i">
                      <span
                        v-if="
                          equationValues(data.item, rule.criteria, data.index)
                        "
                        class="text-danger font-12 bold"
                      >
                        {{ rule.errorMessage }}
                        {{
                          SetValidate(
                            data.index,
                            data.field.key,
                            equationValues(data.item, rule.criteria, data.index)
                          )
                        }}
                      </span>
                      <span v-else>
                        {{
                          SetValidate(
                            data.index,
                            data.field.key,
                            equationValues(data.item, rule.criteria, data.index)
                          )
                        }}
                      </span>
                    </div>
                  </template>
                  <span
                    v-if="errors.first(`${data.field.key}__${data.index}`)"
                    class="d-block text-danger font-12"
                  >
                    {{ errors.first(`${data.field.key}__${data.index}`) }}
                  </span>
                </div>
                <div class="has-equation" v-else-if="data.field.equation">
                  {{
                    (tableData[data.index][data.field.key] = equationValues(
                      data.item,
                      data.field.equation,
                      data.index
                    ))
                  }}
                  <div></div>
                </div>

                <div class="default-value" v-else>{{ data.value }}</div>
              </template>
            </b-table>
</code>```

Body:
when the page is rendered the first time the table is showing a part of the content then the rest of the width is white space and no content showing, if I use the pagination and go to page 2 then back to page 1, the table is all shown but then if I scroll to the right then back to the left it goes white again

here you can see the white space I'm talking about

and here's what should be there (and as I said I got this when I paginated to page 2 then back to 1)

I'm using Vuejs and BootstrapVue table. I don't know what other info would be useful here.

I don't even know where to start, because when I use chrome devtools to open mobile view, this problem doesn't occur.. I'm really clueless!

-- UPDATE --

here's the live link: https://business-abdal-dev.code95.info/ar/invoices/salary-invoices/details/ec599492-a622-ed11-8131-00224899ee26

and this is the code of the table:

              <template #cell()="data" v-if="invoice.details.status.key == 2">

                  <input
                    class="form-control"
                    type="number"
                    min="0"
                    required
                    v-model="tableData[data.index][data.field.key]"
                    v-validate="'required|decimal|min:0'"
                    v-show="data.item.startEdit && inEditField == data.field.key"
                    :name="`${data.field.key}__${data.index}`"
                    :data-vv-as="data.field.label"
                    @blur="
                      setEditedValue(
                        data.item,
                        data.index,
                        data.field.key,
                        $event,
                        data.item.InvoiceDetailsId
                      )
                    "
                    @keydown.enter.prevent="
                      setEditedValue(
                        data.item,
                        data.index,
                        data.field.key,
                        $event,
                        data.item.InvoiceDetailsId,
                        data.field.equation
                      )
                    "
                  />

                    {{ data.value }}

                  <template v-if="data.field.validate.length">

                        {{ rule.errorMessage }}
                        {{
                          SetValidate(
                            data.index,
                            data.field.key,
                            equationValues(data.item, rule.criteria, data.index)
                          )
                        }}

                        {{
                          SetValidate(
                            data.index,
                            data.field.key,
                            equationValues(data.item, rule.criteria, data.index)
                          )
                        }}

                  </template>
                  <span
                    v-if="errors.first(`${data.field.key}__${data.index}`)"
                    class="d-block text-danger font-12"
                  >
                    {{ errors.first(`${data.field.key}__${data.index}`) }}

                  {{
                    (tableData[data.index][data.field.key] = equationValues(
                      data.item,
                      data.field.equation,
                      data.index
                    ))
                  }}

{{ data.value }}

              </template>


问:
How to use SetProgressValue in Flutter
I'm trying to us ITaskbarList3::SetProgressValue() in my Flutter App like this:

Get the hWnd (thanks to Kirill):

final user32 = DynamicLibrary.open('user32.dll');
final findWindowA = user32.lookupFunction<
   Int32 Function(Pointer<Utf8> lpClassName, Pointer<Utf8> lpWindowName),
   int Function(Pointer<Utf8> lpClassName, Pointer<Utf8> lpWindowName)>('FindWindowA');

final hWnd = findWindowA('FLUTTER_RUNNER_WIN32_WINDOW'.toNativeUtf8(), nullptr);
print(hWnd);
```
<p>And my try to use the API:</p>
<pre class="lang-dart prettyprint-override"><code>final explorerframe = DynamicLibrary.open('Explorerframe.dll');
final setProgressValue = explorerframe.lookupFunction<
    Int32 Function(Int32 hwnd, Uint64 ullCompleted, Uint64 ullTotal),
    int Function(int hwnd, int ullCompleted, int ullTotal)>('SetProgressValue');

setProgressValue(hWnd, 50, 100);
</code>```

However I get the error:

Invalid argument(s): Failed to lookup symbol 'SetProgressValue': error code 127

To be honest I do not understand what I'm doing wrong. I was currios which functions are exposed by that dll file I get found out: Nothing

Should that functions not be exported here?

Title: How to use SetProgressValue in Flutter

Body:
I'm trying to us ITaskbarList3::SetProgressValue() in my Flutter App like this:

Get the hWnd (thanks to Kirill):

final user32 = DynamicLibrary.open('user32.dll');
final findWindowA = user32.lookupFunction<
   Int32 Function(Pointer<Utf8> lpClassName, Pointer<Utf8> lpWindowName),
   int Function(Pointer<Utf8> lpClassName, Pointer<Utf8> lpWindowName)>('FindWindowA');

final hWnd = findWindowA('FLUTTER_RUNNER_WIN32_WINDOW'.toNativeUtf8(), nullptr);
print(hWnd);

And my try to use the API:

final explorerframe = DynamicLibrary.open('Explorerframe.dll');
final setProgressValue = explorerframe.lookupFunction<
    Int32 Function(Int32 hwnd, Uint64 ullCompleted, Uint64 ullTotal),
    int Function(int hwnd, int ullCompleted, int ullTotal)>('SetProgressValue');

setProgressValue(hWnd, 50, 100);

However I get the error:

Invalid argument(s): Failed to lookup symbol 'SetProgressValue': error code 127

To be honest I do not understand what I'm doing wrong. I was currios which functions are exposed by that dll file I get found out: Nothing

Should that functions not be exported here?


问:
Program stops when I call function and displays an Exception thrown at 0x00007FFC0DCC2487 (ucrtbased.dll) error in C
I have an array of structs. Here is my struct:

```<code>struct tree {
    itemType name[MAX];
    struct tree* left;
    struct tree* right;
};

typedef struct tree* treenode;
</code>```

and I am creating this function to print out the names:

```<code>void printRoot(treenode root[]){

    int i = 0;
    while (root[i] != NULL) {
        printf("\n\t\t%c %s", 254, root[i]->name);
        i++;
    }
}
</code>```

When I call my printRoot function, my program stops and gives me an error of Exception thrown at 0x00007FFC0DCC2487 (ucrtbased.dll) 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. and then opens up the file of stdio.h.

I tried not using a loop to see if my program really works:

```<code>        char folname[MAX];
        printf("Enter folder name: ");
        scanf(" %s", &folname);

        ROOT[0] = createFolder(folname);
        printf("%s", ROOT[0]->name);
</code>```

and it does. So my assumption is that the problem is really within my printRoot function, but I can't seem to find out what it is that's causing it to not run.

--- [EDIT] ---
This is actually sort of a project in school in which we are to create some sort of a file explorer. So my idea is to create an array with structs in it to make a BST in each index.

we are tasked to create 3 different files: main, implementation, and header. So here is my code for more info (this is unifinished):

```<code>#include "Header.h"

int main() {

    treenode ROOT[50];
    char choice;

    printf("\n\t\tDo you want to create a folder? [Y/N]: ");
    scanf("%c", &choice);

    choice = tolower(choice);

    if (choice == 'y') {
        itemType folname[MAX];
        printf("\n\t\tEnter folder name: ");
        scanf(" %s", folname);

        ROOT[0] = createFolder(folname);
        printf("%s", ROOT[0]->name); //this works
        //printRoot(ROOT); --> this is the problem i'm trying to fix

    }
    else
    {
        printf("\ntest");
    }
</code>```

implementation:

```<code>treenode createFolder(itemType x[]) {
    treenode touch = (struct tree*)malloc(sizeof(struct tree));
    strcpy(touch->name, x);
    touch->left = NULL;
    touch->right = NULL;

    return touch;
}

void printRoot(treenode root[]){

    int i = 0;

    while (root[i] != 0) {
        printf("\n\t\t%c %s", 254, root[i]->name);
        i++;
    }

}

</code>```

Body:
I have an array of structs. Here is my struct:

struct tree {
    itemType name[MAX];
    struct tree* left;
    struct tree* right;
};

typedef struct tree* treenode;

and I am creating this function to print out the names:

void printRoot(treenode root[]){

    int i = 0;
    while (root[i] != NULL) {
        printf("\n\t\t%c %s", 254, root[i]->name);
        i++;
    }
}

When I call my printRoot function, my program stops and gives me an error of Exception thrown at 0x00007FFC0DCC2487 (ucrtbased.dll) 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. and then opens up the file of stdio.h.

I tried not using a loop to see if my program really works:

        char folname[MAX];
        printf("Enter folder name: ");
        scanf(" %s", &folname);

        ROOT[0] = createFolder(folname);
        printf("%s", ROOT[0]->name);

and it does. So my assumption is that the problem is really within my printRoot function, but I can't seem to find out what it is that's causing it to not run.

--- [EDIT] ---
This is actually sort of a project in school in which we are to create some sort of a file explorer. So my idea is to create an array with structs in it to make a BST in each index.

we are tasked to create 3 different files: main, implementation, and header. So here is my code for more info (this is unifinished):

#include "Header.h"

int main() {

    treenode ROOT[50];
    char choice;

    printf("\n\t\tDo you want to create a folder? [Y/N]: ");
    scanf("%c", &choice);

    choice = tolower(choice);

    if (choice == 'y') {
        itemType folname[MAX];
        printf("\n\t\tEnter folder name: ");
        scanf(" %s", folname);

        ROOT[0] = createFolder(folname);
        printf("%s", ROOT[0]->name); //this works
        //printRoot(ROOT); --> this is the problem i'm trying to fix

    }
    else
    {
        printf("\ntest");
    }

implementation:

treenode createFolder(itemType x[]) {
    treenode touch = (struct tree*)malloc(sizeof(struct tree));
    strcpy(touch->name, x);
    touch->left = NULL;
    touch->right = NULL;

    return touch;
}

void printRoot(treenode root[]){

    int i = 0;

    while (root[i] != 0) {
        printf("\n\t\t%c %s", 254, root[i]->name);
        i++;
    }

}