text:
Q: Internal Diagnostics Hub Exception in VS 2015. DataWareHouseRestWebHost error My VS 2015 has recently started to show me error on Debugging. "Internal Diagnostics Hub Exception". I have activated logging for diagnostics, but i cant figure it out from the logfile. Can someone help?
Debug --- Diagnostics Hub Components Loader --- Plug-ins have been loaded.
Debug --- Diagnostics Hub Components Loader --- Component 44d04ed9-f786-458c-93a9-7207a3cc52e1 (Microsoft.DiagnosticsHub.Components.LazyCollectorFactory) has been loaded.
Debug --- DiagnosticsHubPackage --- Visual Studio asks service 'Microsoft.DiagnosticsHub.VisualStudio.SDK.SVsDiagnosticsHubService'
Debug --- DiagnosticsHubPackage --- Creating service 'Microsoft.DiagnosticsHub.VisualStudio.SDK.SVsDiagnosticsHubService'.
Debug --- Service Microsoft.DiagnosticsHub.IDocumentsService implementation --- New document was created 'C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession'
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'Unknown' to 'Created'.
Debug --- Document ('C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession') --- Changing document state from 'New' to ActiveSession.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'Created'.
Debug --- SessionsService --- New session has been created for document 'C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession'
Debug --- SessionTargetsService --- New target added PerfDebuggerTarget.
Info --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Initializing performance debugger session.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'Created' to 'InitializePerformanceDebugger'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'InitializePerformanceDebugger'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Collectors count: 1
Debug --- StandardClientTransportConnection --- Connection protocol version: VS14Update3MicroUpdate
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'InitializePerformanceDebugger' to 'PerformanceDebuggerInitialized'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'PerformanceDebuggerInitialized'.
Debug --- ConcordModuleLoadListener --- Concord Module Load Listener is loaded.
Debug --- DiagnosticsHubPackage --- Visual Studio asks service 'Microsoft.DiagnosticsHub.VisualStudio.Collectors.CollectorService.SVsDiagnosticsHubClientEventHandler'
Debug --- DiagnosticsHubPackage --- Creating service 'Microsoft.DiagnosticsHub.VisualStudio.Collectors.CollectorService.SVsDiagnosticsHubClientEventHandler'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'PerformanceDebuggerInitialized' to 'SetupTargets'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'SetupTargets'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'SetupTargets' to 'CollectionStarting'.
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'CollectionStarting'.
Debug --- DataWarehouseRestWebHost --- {"analyzers":[{"type":2,"clsid":"dca8b3ef-28c5-4b08-bafc-b072f8aa9277","localDllPath":"C:\\Users\\PointLevel\\AppData\\Local\\assembly\\dl3\\E4CLB8TO.4TB\\0D6WQKHM.YD8\\b1cf5283\\0070979a_f1cad101\\amd64\\DiagnosticsHub.CpuSamplingAnalyzer.dll","initialize":false},{"type":1,"clsid":"66edddf1-2277-40f3-983a-6ff57a433ecb","localDllPath":null,"initialize":false},{"type":1,"clsid":"66edddf1-2277-40f3-983a-6ff57a433ecb","localDllPath":null,"initialize":false},{"type":1,"clsid":"4694940b-046b-4885-9b7d-1fb0e8f2d54b","localDllPath":null,"initialize":false}],"dataSources":[],"symbolStorePath":"","symbolCachePath":"C:\\Users\\PointLevel\\AppData\\Local\\Temp\\910275ad-c212-4cce-afda-d4393654dbef.PackageExtraction\\TempSymCache","isJmcEnabled":true,"symbolLocatorServiceFullPath":"","portablePdbLibraryFullPath":"","sessionId":"910275ad-c212-4cce-afda-d4393654dbef"}
Debug --- DataWarehouseRestWebHost --- Request queued. Controller ID: DataWarehouse, Action ID: 1, Session ID: 910275ad-c212-4cce-afda-d4393654dbef
Debug --- PerformanceDebuggerDocumentViewModel --- Updating Performance Debugger view for document state: ActiveSession
Debug --- PerformanceDebuggerDocumentViewModel --- Updating Performance Debugger view for session state: CollectionStarting
Debug --- PerformanceDebuggerDocumentViewModel --- Done updating Performance Debugger view for document state: ActiveSession
Debug --- PerformanceDebuggerDocumentViewModel --- Done updating Performance Debugger view for session state: CollectionStarting
Error --- DataWarehouseRestWebHost --- Request failed (VS Package). Controller ID: DataWarehouse, Action ID: 1, Session ID: 910275ad-c212-4cce-afda-d4393654dbef, Error message: {"Message":"An error has occurred.","ExceptionMessage":"Det går inte att hitta den angivna modulen. (Undantag från HRESULT: 0x8007007E)","ExceptionType":"System.IO.FileNotFoundException","StackTrace":"   vid Microsoft.DiagnosticsHub.Hosting.IDataWarehouseHost.ConstructSessionAnalyzer(Guid& sessionId, Guid& analyzerId, String fullPathToDll)\r\n   vid Microsoft.DiagnosticsHub.DataWarehouse.ServiceModule.DataWarehouseHostWrapper.ConstructAnalyzer(Guid sessionId, Guid analyzerId, String fullPathToDll)\r\n   vid Microsoft.DiagnosticsHub.DataWarehouse.ServiceModule.Controllers.DataWarehouseController.BeginInitializeDataWarehouse(DataWarehouseConfigurationPayload config)"}
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- Changing state from 'CollectionStarting' to 'CollectionStartFailed'.
Debug --- PerformanceDebuggerDocumentViewModel --- Done updating Performance Debugger view for session state: CollectionStartFailed
Debug --- PerformanceDebuggerDocumentViewModel --- Updating Performance Debugger view for session state: CollectionStartFailed
Debug --- Document ('C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession') --- Changing document state from 'ActiveSession' to Failed.
Debug --- PerformanceDebuggerDocumentViewModel --- Updating Performance Debugger view for document state: Failed
Debug --- SessionsService --- Closing session for document C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession
Debug --- SessionsService --- Session for document C:\Users\PointLevel\AppData\Local\Temp\Report20170109-2333.diagsession was closed
Debug --- ApplicationPathService --- Hub application path is 'C:\Users\PointLevel\AppData\Local\assembly\dl3\E4CLB8TO.4TB\0D6WQKHM.YD8\6dfa46a3\0070979a_f1cad101'
Debug --- Scripted Control (PerformanceDebuggerSwimLanesView.manifest.json) --- Initializing the ScriptedControl with manifest file 'C:\Users\PointLevel\AppData\Local\assembly\dl3\E4CLB8TO.4TB\0D6WQKHM.YD8\6dfa46a3\0070979a_f1cad101\WebViews\PerformanceDebuggerSwimLanesView.manifest.json'. Base directory 'C:\Users\PointLevel\AppData\Local\assembly\dl3\E4CLB8TO.4TB\0D6WQKHM.YD8'
Error --- Scripted Control (PerformanceDebuggerSwimLanesView.manifest.json) --- System.ArgumentException: Manifest file 'C:\Users\PointLevel\AppData\Local\assembly\dl3\E4CLB8TO.4TB\0D6WQKHM.YD8\6dfa46a3\0070979a_f1cad101\WebViews\PerformanceDebuggerSwimLanesView.manifest.json' not found.
   at Microsoft.VisualStudio.ScriptedHost.Library.FileSystemManifestLoader..ctor(String basePath, String manifestFile, Action`1 pathValidator, Action`2 startUriValidator)
   at Microsoft.VisualStudio.ScriptedHost.Library.FileSystemManifestLoader..ctor(String basePath, String manifestFile)
   at Microsoft.DiagnosticsHub.VisualStudio.Utilities.ManifestMergeLoader..ctor(String primaryRootPath, String primaryManifest, NameValueCollection additionalRootPathManifestPairs)
   at Microsoft.DiagnosticsHub.VisualStudio.Presentation.Controls.VisualStudioScriptedControl.Initialize(IScriptedControlConfiguration scriptedControlConfiguration)
Error --- Service Microsoft.DiagnosticsHub.Presentation.Controls.ISwimLanesViewService implementation --- Could not create IScriptedControl.
Error --- DispatcherProvider --- Unhandled exception on DispatcherProvider.Invoke
Microsoft.DiagnosticsHub.Diagnostics.InternalHubException: Internal Diagnostics Hub Exception. See log for more details.
   at Microsoft.DiagnosticsHub.VisualStudio.Presentation.Controls.SwimLanesViewService.CreateControl(ViewDestinations viewDestinations, IEnumerable`1 swimLaneConfigurations)
   at Microsoft.DiagnosticsHub.Presentation.ViewModels.CustomViewsViewModel.OnActivated()
   at Microsoft.DiagnosticsHub.Presentation.ViewModels.PerformanceDebuggerDocumentViewModel.<CreateMessageView>b__22_0()
   at Microsoft.DiagnosticsHub.Presentation.DispatcherProvider.<>c__DisplayClass5_0.<Invoke>b__0()
Debug --- ConcordModuleLoadListener --- Processing modules for process. PID: '7296', Unique ID: '887f380d-df93-47b6-ad99-a37782218a63'.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'mscorlib.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'mscorlib.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Web.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Core.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Web.ApplicationServices.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Configuration.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Xml.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'mscorlib.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Web.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Core.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Web.ApplicationServices.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Configuration.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Xml.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Runtime.Caching.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Runtime.Caching.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'mscorlib.resources.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'Microsoft.Build.Utilities.v4.0.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'Microsoft.Build.Utilities.v4.0.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'Microsoft.JScript.dll' to False.
Info --- ModuleJmcStateService --- Setting JMC user state for module 'Microsoft.VisualStudio.Web.PageInspector.Loader.dll' to False.
Debug --- PerformanceDebuggerDocumentViewModel --- Done updating Performance Debugger view for document state: Failed
Debug --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- State has been changed to 'CollectionStartFailed'.
Error --- Session ('910275ad-c212-4cce-afda-d4393654dbef') --- System.AggregateException: One or more errors occurred. ---> Microsoft.DiagnosticsHub.Diagnostics.InternalHubException: Request to web host was unsuccessful: 'An error has occurred.'
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouseRestWebHost.<Request>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouse.DataWarehouseInstance.<InitializeDataWarehouseInternal>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Collectors.CollectorService.StandardClientCollector.<OnStartCollection>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Runtime.PerformanceDebuggerSession.<StartCollectionAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.Sessions.SessionBase.<>c__DisplayClass51_0.<<ContinueCurrentTaskWith>b__0>d.MoveNext()
   --- End of inner exception stack trace ---
---> (Inner Exception #0) Microsoft.DiagnosticsHub.Diagnostics.InternalHubException: Request to web host was unsuccessful: 'An error has occurred.'
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouseRestWebHost.<Request>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouse.DataWarehouseInstance.<InitializeDataWarehouseInternal>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Collectors.CollectorService.StandardClientCollector.<OnStartCollection>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Runtime.PerformanceDebuggerSession.<StartCollectionAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.Sessions.SessionBase.<>c__DisplayClass51_0.<<ContinueCurrentTaskWith>b__0>d.MoveNext()<---

Info --- ModuleJmcStateService --- Setting JMC user state for module 'System.Runtime.InteropServices.dll' to False.
Error --- PerformanceDebuggerSessionManager --- Microsoft.DiagnosticsHub.Diagnostics.InternalHubException: Request to web host was unsuccessful: 'An error has occurred.'
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouseRestWebHost.<Request>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.DataWarehouse.DataWarehouseInstance.<InitializeDataWarehouseInternal>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Collectors.CollectorService.StandardClientCollector.<OnStartCollection>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.Runtime.PerformanceDebuggerSession.<StartCollectionAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.Sessions.SessionBase.<>c__DisplayClass51_0.<<ContinueCurrentTaskWith>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.DiagnosticsHub.Sessions.SessionBase.<>c__DisplayClass51_0.<<ContinueCurrentTaskWith>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.Sessions.SessionBase.<ExecuteTaskAfter>d__53.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DiagnosticsHub.VisualStudio.PerformanceDebuggerSessionManager.<OnAfterLaunch>d__25.MoveNext()

A: This link helped me, https://stackoverflow.com/a/38517169/3560234.
I believe I had the same errors in the log you posted, but after looking in the ActivityLog mentioned in that link it showed a Typescript support error.
EDIT: This worked for me when running VS as user, but running VS as administrator still gives me the exception.
EDIT2: I found the following link: https://arstechnica.com/civis/viewtopic.php?f=20&t=1293083.
That there resolved my problems, adding your user to have read/write permissions to vcruntime140.dll and msvcp140.dll. Hope this fixes it for you as well.


text:
Q: Can you reuse a SSD after applying a Zero-Fill software? I am returning my laptop to the retailer but I have had it for 1 month, In this time I have stored some confidential information, Because of this I am planning to zero fill my SSD using http://cmrr.ucsd.edu/people/Hughes/secure-erase.html or https://www.piriform.com/defraggler
Once I have done the zero fill, will I be able to easily install windows 8.1 back on it?
By easy I mean a normal approach, possibly involving some formatting/partitioning.
I must be able to install windows 8.1 because the retailer will check to see if it works.
I am not concerned that zero filling can reduce the SSD read/write cycles as the laptop is faulty in other areas anyway.
An except from Secure Erase Q&A page states
Q:  What is the difference between secure erase and enhanced secure erase?

A:  Secure erase overwrites all user data areas with binary zeroes.  Enhanced
secure erase writes predetermined data patterns (set by the manufacturer) to
all user data areas, including sectors that are no longer in use due to
reallocation. ***NOTE:  the enhanced secure erase option is not supported by
all ATA drives.

Am I going about this the wrong way, is there something better I should do?

A: Your approach is flawed.
You will only zero-fill the remaining free space of the SSD because you're doing it from the OS. That is bad in many ways, as the OS itself can have remnants of your confidential files in its caches/event logs/whatever, and this utility won't erase them because technically they are still a file.
You should use a Linux live-CD instead, and erase the whole disk multiple times using the following command : shred -v /dev/sdX which would rewrite the SSD three times using random data.
You can also try, in addition to the above approach (technically the secure erase command should suffice, but its implementation might be flawed so we still keep the 3x overwrite mentioned above), the ATA secure erase command :
First check to make sure the disk's security status is not "frozen"; some laptops with disk password support in the BIOS freeze the disk to prevent the OS from disabling/changing that password :
hdparm -I /dev/sdX

If the command says "frozen", you should try suspending the system. On next boot, the drive will be reset to its default state due to the loss of power and won't be frozen again because the BIOS isn't executed.
Now, let's do the actual erase :
hdparm --user-master u --security-set-pass verysecure /dev/sdX
hdparm --user-master u --security-erase verysecure /dev/sdX

The first command sets a security password which is necessary to perform any security-related commands, the second command issues the secure erase command do the drive. You don't have to be worried about the machine asking for the password on next boot since the secure erase command also clears that password.

A: You will be able to reinstall Windows 8.1 after using Zero Fill software, don't worry about it.
And even if you are worried about the write count on your disk, some other users may be worried. You (and the others) don't need to be concerned. Those guys wrote lots and lots of data to some SSDs before they failed. A Zero Fill software will not create any wear on the drive.

A: Read this article about SSD endurance testing. It means you can write many GB per day for several years. Of course some disks will fail to meet this, but overall this should work out for almost all disks. Your one time secure erase won't harm it.
Grueling endurance test blows away SSD durability fears

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get an array of values from $entry In Gravity Form's class GF_Field_Checkbox there is a method called get_value_export() that returns implode( ', ', $selected ) for a bunch of elements created by GFCommon::selection_display()
The class-gf-field-checkbox.php code so you can see what I am referencing.
    public function get_value_export( $entry, $input_id = '', $use_text = false, $is_csv = false ) {

        if ( empty( $input_id ) || absint( $input_id ) == $input_id ) {

            $selected = array();

            foreach ( $this->inputs as $input ) {

                $index = (string) $input['id'];

                if ( ! rgempty( $index, $entry ) ) {
                    $selected[] = GFCommon::selection_display( rgar( $entry, $index ), $this, rgar( $entry, 'currency' ), $use_text );
                }

            }

            return implode( ', ', $selected );
        ...

This is all well and good, however, the problem with this is that I'm exploding the values that are returned from this method.
$answer = explode(', ', $field->get_value_export($entry));
I do not want to do this as there exists an edge case where a potential value could have a comma which gets exploded. For example, say there is an option in my form like below
Label: Are you not entertained?
Value:
 [x] Lorem ipsum dolor sit amet, consectetur adipiscing elit
 [x] Duis blandit, risus vel rutrum suscipit
 [ ] Duis cursus ex risus

As you can see the first two selections are selected, and this will be picked up and will then be exploded as such
['Lorem ipsum dolor sit amet', 'consectetur adipiscing elit', 'Duis blandit', 'risus vel rutrum suscipit']

When it should have been exploded like this
['Lorem ipsum dolor sit amet, consectetur adipiscing elit', 'Duis blandit, risus vel rutrum suscipit']

What method exists in GFAPI, or custom code can I use that could resolve this issue?

A: You can retrieve the checkbox values in the following way:
    $entry = GFAPI::get_entry( **entry id here** );//add your entry id in parenthesis
    $field_id = **add field number here**;
    $items = array();
    $field_keys = array_keys( $entry );
    foreach ( $field_keys as $input_id ) {
      if ( is_numeric( $input_id ) && absint( $input_id ) == $field_id ) {
        $value = rgar( $entry, $input_id );
        if ( "" !== $value ) $items[ $input_id ] = str_replace(",",",",$value);
      }
    }
    $answer = implode(",",$items);

A: Rochelle's answer was useful in producing this solution. Instead of using GF_Field_Checkbox's method, I've created my own function that will pull out the necessary values into an array, while effectively getting rid of the comma issue, due to using explode()
function get_value_export($entry, $input_id)
{
    $items = array();
    foreach ($entry as $key => $value) {
        if ($value == "") continue;
        if (!is_numeric($key)) continue;
        if (absint($key) !== absint($input_id)) continue;

        $items[] = $value;
    }
    return $items;
}


text:
Q: MySQL joined subqueries optimization I have the following query in MySQL
 select * from
    (
        select asiento, fecha, sum(debe) as debe, sum(haber) as haber
        from apuntes
        where apuntes.sobreescrito is null
        group by asiento, fecha
        order by fecha, asiento
    )asientos
    left join
    (
        select id_diario, asiento, fecha, sum(debe) as debe, sum(haber)  as haber
        from apuntes
        where apuntes.sobreescrito is not null
        group by asiento, fecha, id_diario
        order by fecha, asiento
    )asientos_antiguos
    on asientos.asiento = asientos_antiguos.asiento and asientos.fecha  = asientos_antiguos.fecha
    where
        asientos_antiguos.debe <> asientos.debe
        or
        asientos_antiguos.haber <> asientos.haber

Thi first subquery(asientos) returns around 20k records, while the second query, in a normal situation, should return no more thatn 20k records, that produces an acceptable query of 3-4 seconds but, in theory, it could duplicate records on each operation, so I´m testing with 100k records produced, and it takes around 30 seconds (not acceptable).
At this point, I tried to create indexes for fields "asiento" and "fecha", but subqueries don´t benefit from this. Also, I created two views for each subquery, hoping I could create an Index in those subviews, but, views limitations include "no indexes".
Any help would be appreciated.
EDIT 1
Ok, I will try to give an explanation of what I´m trying to achieve, and feel free to correct my English, I´m gonna use financial words that I probably don´t know.
I have developed a web app that read excel files with book entries ( Each one containing usually 20k records ) and save those book entries to a table (apuntes, in my case).
Sometimes, some of those entries may be overwritten in the case that the fields "fecha" and "asiento" are the same and the field "id_diario" is different (NOTE: each excel book generates a set of book entries with its own "id_diario", so I can discriminate older records)
At this point, everything goes ok, but now I have to generate a report indicating if, at some point, overwritten book entries(financial word, don´t know if it´s correct) have a different amount than the new ones that overwrited them.
And here is when I came with this query, where 1st subquery takes all records that are not overwriten (apuntes.sobreescrito is NULL) and the 2nd subquery takes all overwritten records matching 1st subquery.
In my test case, 2nd subquery generates 3 overwriten records for each valid book entry(there were 3 overwriting operations) what means comparing 60k vs 20k records.
As a next step, I will use "GROUP_CONCAT" operation to generate a json-formated array with the results of the 2nd query, but 1st, I have to fix the performance issue.

A: Wonder if you can use a more basic query to determine the records where there is a mismatch, and then just get the real details for those. This might help if the number of changed records you are interested in are only a small number of all the records.
For example something like this should find records that have changed -
SELECT asiento, fecha
FROM
(
    SELECT id_diario, asiento, fecha, SUM(debe) AS debe, SUM(haber) AS haber
    FROM apuntes
    GROUP BY id_diario, asiento, fecha
) sub0
GROUP BY asiento, fecha
HAVING MIN(debe) != MAX(debe)
OR MIN(haber) != MAX(haber)

You could maybe use this to narrow down the actual records that you need to check.


text:
Q: Inside foreach loop, the await is not working Below this code downloadcontroller.js
// Retrieve all downloads from the database.
exports.findAll = async (req, res) => {
  downloadObj
  .findAll(
    {
      include: [
        {
            model: composerObj,
            required: false,
        },
        {
            model: raagaObj,
            required: false,
        },
        {
            model: taalaObj,
            required: false,
        },
      ],
      where: req.query,
      raw:true,
      nest: true,
    })
    .then((data) => {

    data.forEach(async (element) => {
        const artistsArray = [];
        let whereConstraint = {};
        JSON.parse(element.artists).forEach( async (ele) => {
          artistsArray.push(ele.artistId);
        });;
        whereConstraint = {
          id : {
            [Op.in]: artistsArray
          }
        }
        element.Active = "true11";
        const artistData =  artistService.customfindAll(whereConstraint);
        element.artistData = artistData;
        console.log("artistData",artistData);
    });

      console.log("data",data);
      console.log("3");

       res.status(200).send({
         status:200,
         message: "ok",
         data:data
       });

       console.log("4");
    })
    .catch((err) => {
      res.status(500).send({
        status:500,
        message:
          err.message || "Some error occurred while retrieving Download.",
      });
    });
};

Below this code, artistServer.js file
exports.customfindAll = async (whereConstraint) => {
    return new Promise(function(resolve, reject) {
        artistObj
        .findAll({
          attributes:{
            include: [
                  [fn('IF',literal('imagePath!=""'),(fn('CONCAT', artistImagePath, 'artist/', col('imagePath'))),artistImageDefaultPath), 'imageFullPath'],
            ],
          },
          where: whereConstraint,
          order: [
                ['artistName', 'ASC'],
          ],
            raw:true,
            nest: true,
        })
        .then((data) => {
            resolve(data);
        });
    });
  }

Here my problem is
const artistData =  artistService.customfindAll(whereConstraint);
not waiting for the data. .So that I got the result, below have mentioned. Actually the artistData attribute column, need result data.
{
    "status": 200,
    "message": "ok",
    "data": [
        {
            "id": 1,
            "fileType": "1",
            "customFileName": "test filename",
            "artists": "[{\"artistId\":1},{\"artistId\":4},{\"artistId\":2}]",
            "accompanyingArtists": "[{\"instrumentId\":1,\"accompanyingArtistId\":1},{\"instrumentId\":2,\"accompanyingArtistId\":6},{\"instrumentId\":3,\"accompanyingArtistId\":4}]",
            "Active": "true11",
            "artistData": {}
        },
        {
            "id": 2,
            "fileType": "1",
            "customFileName": "new file name",
            "artists": "[{\"artistId\":1},{\"artistId\":4},{\"artistId\":2},{\"artistId\":6},{\"artistId\":3}]",
            "accompanyingArtists": "[{\"instrumentId\":1,\"accompanyingArtistId\":1},{\"instrumentId\":2,\"accompanyingArtistId\":6},{\"instrumentId\":3,\"accompanyingArtistId\":4},{\"instrumentId\":3,\"accompanyingArtistId\":3},{\"instrumentId\":4,\"accompanyingArtistId\":2}]",
            "Active": "true11",
            "artistData": {}
        }
    ]
}

In console page, I artistdata attribute pending...
enter image description here

A: The customFindAll function returns a Promise but the forEach does not wait for it. Add an await:
const artistData = await artistService.customfindAll(whereConstraint);

Also, forEach does not wait, it just fires off the async functions and move on. To wait for the forEach to finish, you need a map and a Promise.all, like this:
    await Promise.all(data.map(async (element) => {
        const artistsArray = [];
        let whereConstraint = {};
        JSON.parse(element.artists).forEach( async (ele) => {
          artistsArray.push(ele.artistId);
        });;
        whereConstraint = {
          id : {
            [Op.in]: artistsArray
          }
        }
        element.Active = "true11";
        const artistData =  await artistService.customfindAll(whereConstraint);
        element.artistData = artistData;
        console.log("artistData",artistData);
    }));

The way it works this way is that data.forEach(async (e) => ... runs the async function and discards the results (the Promises). If you use a map, like data.map(async (e) => ..., you'll get an array of Promises, then use await Promise.all(...) to wait for them.


text:
Q: ES5 Module pattern usage Could you explain to me what is the difference between that two approaches (FirstModule and SecondModule:
var MyModule = (function () {
    return {
        method: function () {
            console.log("MyModule:method");
        }
    }
})();

var FirstModule = (function () {
    return {
        test: function () {
            MyModule.method();
        }
    }
})();

var SecondModule = (function (myMethod) {
    return {
        test: function () {
            myMethod.method();
        }
    }
})(MyModule);

In both cases we have the same object, it isn't a copy. I would be grateful for any good information, advantages, disadvantages of any approach.

A: The first approach uses the MyModule variable, which can be overwritten by other code, outside the module, after the FirstModule value has been asigned.
The second uses the myMethod variable, which can't (although properties of the object assigned to myMethod still can because that object is still globally available via the MyModule variable).


text:
Q: how to avoid 'Database is Locked' Error in SQLite? I've searched all over but I can't find any solution for me.
I have sequences in my program where I do 'select' commands then follow it with 'update' or 'insert' commands. I'm suspecting this is where I got this error. Please help me how I can avoid this. I can't use try catch because the error appears few seconds after I trigger the event.


text:
Q: Back button in fragment Android-Related I have one fragment in which a listview is created. When the list is clicked the same list is refreshed and its child elements are loaded on the same. Could anyone please tell me how to enable the backbutton in android to get the parent list?

A: You can override your activity's onBackPressed() and get the fragment instance by FragmentManager, and do what you want.

A: You have to take callback from onBackPressed of Activity to Fragment and check in Fragment if there is child elements open or not.
In Activiity
public void onBackPressed()
{
  if(!fragment.onBackPressed())//onBackPressed in fragment is your own function
  {
    super.onBackPressed();
  }
}

In Fragment
public boolean onBackPressed() //your custom onBackPressed not overrided
{
  if(childListOpen)
  {
    //close the child list
    return true;
  }
  else
  {
   // whatever to do in back pressed of list
    return false;
  }
}

A: For your simplicity, Define one static variable in your activity that track the which fragment is currently visible, like
public static fragIndex = 0;
then in your fragment oncreateView before returning view set it accordingly to fragments. like in list view fragment
MainActivity.fragIndex = 0;
and for detailed fragment
MainActivity.fragIndex = 1;
now on your activities onbackpressed method do like
if(fragIndex == 0){
//whatever you want to do.
}else if(fragIndex == 1){
// change the fragment back to list view
}

A: Use the method onResume()
@Override
public void onResume() { // TODO Auto-generated method stub
    super.onResume();
}


text:
Q: Adding timestamp to dataframe in Google Earth Engine Python API I came across an example shared on YouTube by Madhu Mysore. Here is the link: https://www.youtube.com/watch?v=IGUYSeoeHhg&t=2105s.
I changed the code as I am not interested in regions at the moment, but rather in daily/weekly observations. What I am struggling to do is to add a timestamp to the following code. I checked multiple forums and EE developers page but cannot figure it out.
import ee
import pandas as pd
ee.Initialize()
districts = ee.FeatureCollection('users/mdm/za/za_districts')

chirps = ee.ImageCollection("UCSB-CHG/CHIRPS/DAILY").select('precipitation').filterDate('2018-01-01', '2018-12-31').mean()
evi = ee.ImageCollection('MODIS/006/MOD13A2').select('EVI').filterDate('2018-01-01', '2018-12-31').mean()

composite = ee.Image.cat([chirps, evi])

dist_stats = composite.reduceRegions(districts, 'mean', 5000)

dist_stats = dist_stats.select(['precipitation', 'EVI'], ['tot_rainfall', 'med_evi'], retainGeometry=False).getInfo()

dtstats_df = pd.DataFrame()
for dist in dist_stats['features']:
    df = pd.DataFrame([dist['properties']],columns=dist['properties'].keys())
    dtstats_df = pd.concat([dtstats_df, df], axis=0)

dtstats_df = dtstats_df[['tot_rainfall', 'med_evi']]

dtstats_df

A: You can add a timestamp to your dataframe like this:
dtstats_df['date'] = '2018-07-01'
dtstats_df

Since you are taking the mean of a collection of images, the time element has sort of been lost. Here I have simply added the middle of your date range as a YYYY-MM-dd formatted date to the dataframe.


text:
Q: How can I build other people's projects from github? I suspect this is not as hard as I'm making it but I'm having trouble understanding how to build other people's source into jar files I can use for my own projects.
For example(please make the answer general so I can apply it to other sources), I'm looking at https://github.com/xetorthio/jedis and the source seems newer than the provided jars(for which I noticed a few bugs), so I wanted to try to build it so its like the provided jars(this way I can test it in my project).  I know how to clone the repository but I don't feel like copying/pasting or import one file at a time into eclipse to export a jar.
Is there something easy that I can go into a folder and run a command to get the jar(my understanding jar's are just zipped files)?

A: Each project will provide its own way of building and packaging. There are some standard methods. The project you linked to is using a tool called Gradle.
Try running gradlew to see if that will build the project for you. If that fails, you could learn to use Gradle. Alternatively you could contact the project owner and ask for a new release.

A: Clone the project using git clone then build it using make, maven, ant or whatever is given there.
In your case doing a git clone https://github.com/xetorthio/jedis.git will clone the repo then you use Gradle to build the project. Since I didn't use it, see their tutorial for more


text:
Q: Constructing a Java method that returns a primitive data type that is decided by the input? I would like a method to read a string, and return it's value in the implied (best fitting) data type. I would like to avoid doing the string to data type conversion in "main", as the code is likely to create clutter. Is this possible? Can I create a method that returns different types? What does the constructor look like?

A: It's not possible to return different primitive types. What you can do is declare the method as returning Object, and at runtime return boxed primitives: instances of Integer, Double, Boolean, etc.

A: A single Java method cannot return multiple types. This is because Java is a strongly typed language.
There are a few different ways to accomplish this. If you'd like to go the constructor route as mentioned in the OP, it would look something like this:
public class Demo(){
    Demo(String str){
        // Do something...
    }

    Demo(int newInt){
        // Do something...
     }

    // Other constructors for other types here
}

A: You could explore an enum type as a way to classify the type you end up with. You don't say what you want to use it for, so this may not be best, but it could be done in a way that handles the requirements you do give.
public class ClassifiedType
{
  public enum ClassifiedTypeType { INTEGER,  FLOAT,  STRING,  BOOLEAN };

  ClassifiedTypeType  typeType = null;
  int                 integerValue;
  float               floatValue;
  String              stringValue;
  boolean             booleanValue;

  public ClassifiedType(int i) { integerValue = i; typeType = ClassifiedTypeType.INTEGER; }
  public ClassifiedType(float f) { floatValue = f; typeType = ClassifiedTypeType.FLOAT; }
  // etc.

  public int getIntegerValue()
  {
    if (typeType != ClassifiedTypeType.INTEGER)
    {
      throw new IllegalArgumentException("Attempting getInteger on type of " + this.toString());
    }
    else
    {
      return integerValue;
    }
  }

  // do gets for other types similarly.

  public static ClassifiedType getClassifiedType(String string)
  {
    // parse the string, determine which type you want,
    // instantiate a ClassifiedType with its value and
    // and type, and return it.
  }
}

Other classes can use the ClassifiedTypeType (hopefully with a better name) to determine what kind of value to get from it, to the extent they need that.
Anyway, it beats returning Object and then having to use instanceof all over the place to figure out what you're dealing with, and this extends to non-primitives if you ever need that.


text:
Q: Properties vs. Keys vs. Values in JavaScript I'm trying to clarify my understanding of the terms "property" vs. "keys" vs. "values" in the JavaScript realm.  After reading a few books on the language and even googling the terms, I still don't feel like I'm clear on their precise meaning.  So suppose we have the following:
var object = {"name" : 5};

Is my understanding of the following terms correct:

property refers to "name"
key refers to "name"
value refers to 5

I'm most concerned about "property": does it refer to identifiers only, or to the whole name/value pair?

A: This topic was really confusing for me as well. Different courses I did had different interpretations for the term "property". After consulting with different mentors I came up with this conclusion. Correct me if I'm still wrong.
name : 5 => property(key/value pair)
name => key or property name
5 => value or property value

A: Property is that part of object named "name" with value 5. Key is a word "name".

A: They don't have a precise meaning, especially "property" is ambiguous.
The term property  (also: attribute, less common or even used for different things in JS) usually refers to the key/value pair that describes a member of an object. While, especially when used with a specific identifier (key), it often refers to the whole combination, it can also denote the value of that member. It does usually not mean the identifier itself.
When people try to be accurate, they distinguish between "property" (the whole thing, part of an object), "property name" (the string used as the key) and "property value" (the stored data).

A: Just want to point out - I was also confused about this because of the hasOwnProperty() method, where this returns true:

const object1 = new Object();
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));

And this returns false:

const object1 = new Object();
object1.property1 = 42;
console.log(object1.hasOwnProperty('42'));

So, while the other answers are correct, in the case of the hasOwnProperty() method, property does = the property's key.


text:
Q: Prove that $\frac{1+2\sin{\theta}\cos{\theta}}{\cos^2{\theta}-\sin^2{\theta}}=\frac{1+\tan{\theta}}{1-\tan{\theta}}$ Prove that $$\frac{1+2\sin{\theta}\cos{\theta}}{\cos^2{\theta}-\sin^2{\theta}}=\frac{1+\tan{\theta}}{1-\tan{\theta}}$$
Here's my attempt
$$\require{cancel}\text{Left - Right} = \frac{(1+2\sin{\theta}\cos{\theta})(1-\tan{\theta})-(1+\tan{\theta})(\cos^2{\theta}-\sin^2{\theta})}{(\cos^2{\theta}-\sin^2{\theta})(1-\tan{\theta})}=
\frac{\cancel1\cancel{-\tan{\theta}}+2\sin^2{\theta}\cancel{+2\sin{\theta}\cos{\theta}}\cancel{-\cos^2{\theta}+\sin^2{\theta}}\cancel{-\sin{\theta}\cos{\theta}}\cancel{+\tan{\theta}}\cancel{-\sin{\theta}\cos{\theta}}}{(\cos^2{\theta}-\sin^2{\theta})(1-\tan{\theta})}
=\frac{2\sin^2{\theta}}{(\cos^2{\theta}-\sin^2{\theta})(1-\tan{\theta})}$$
It should be zero, but it isn't? Here's the proof:
$$\text{Left}=\frac{\sin^2{\theta}+\cos^2{\theta}+2\sin{\theta}\cos{\theta}}{\cos^2{\theta}-\sin^2{\theta}}=\frac{(\sin{\theta}+\cos{\theta})^2}{(\cos{\theta}+\sin{\theta})(\cos{\theta}-\sin{\theta})}=\frac{\sin{\theta}+\cos{\theta}}{\cos{\theta}-\sin{\theta}}
\\\text{Right}=\frac{1+\frac{\sin{\theta}}{\cos{\theta}}}{1-\frac{\sin{\theta}}{\cos{\theta}}}=\frac{\cos{\theta}+\sin{\theta}}{\cos{\theta}-\sin{\theta}}
\\{\therefore}\text{Left=Right}$$

A: Direct way:
Factor out $\cos^2\theta$ from numerator and denominator of the l.h.s. fraction and do some trigonometry:
$$\frac{1+2\sin\theta\cos\theta}{\cos^2\theta-\sin^2\theta}=\frac{\dfrac1{\cos^2\theta}+2\tan\theta}{1-\tan^2\theta}=\frac{1+\tan^2\theta+2\tan\theta}{1-\tan^2\theta}=\frac{(1+\tan\theta)^2}{1-\tan^2\theta}$$
and simplify.

A: Note that
$$
1+2\sin\theta\cos\theta=\cos^2\theta+\sin^2\theta+2\sin\theta\cos\theta=
(\cos\theta+\sin\theta)^2
$$
Therefore
\begin{align}
\frac{1+2\sin\theta\cos\theta}{\cos^2\theta-\sin^2\theta}
&=\frac{(\cos\theta+\sin\theta)^2}{(\cos\theta+\sin\theta)(\cos\theta-\sin\theta)}
\\[6px]
&=\frac{\cos\theta+\sin\theta}{\cos\theta-\sin\theta}
\\[6px]
&=\frac{\cos\theta(1+\tan\theta)}{\cos\theta(1-\tan\theta)}
\\[6px]
&=\frac{1+\tan\theta}{1-\tan\theta}
\end{align}

A: Use
\begin{equation}
 2 \sin \theta \cos \theta
 =
 \sin 2\theta
 =
 \frac{2 \tan \theta}{1 + \tan^2 \theta}
\end{equation}
\begin{equation}
\cos^2 \theta - \sin^2 \theta
=
 \cos 2\theta = \frac{1 - \tan^2 \theta}{1 + \tan^2 \theta}
\end{equation}
Replacing the above quantities, we get
\begin{equation}
 \frac{1 + \frac{2 \tan \theta}{1 + \tan^2 \theta}}{\frac{1 - \tan^2 \theta}{1 + \tan^2 \theta}}
 =
 \frac{1 + \tan^2 \theta + 2 \tan \theta}{1 - \tan^2 \theta}
 =
 \frac{(1 + \tan \theta)^2}{( 1 - \tan \theta) (1 + \tan \theta)}
 =
 \frac{1 + \tan \theta}{1 - \tan \theta}
\end{equation}

A: Abbreviating $\sin\theta$ by $s$ and $\cos\theta$ by $s$ we have on base of $c^2+s^2=1$:$$1+2sc=c^2+2sc+s^2=(c+s)^2$$ so that:$$(1+2sc)(c-s)=(c+s)^2(c-s)=(c^2-s^2)(c+s)$$
Dividing boths sides by $c$ and abbreviating $\tan(\theta)$ by $t$ we get on base of $t=s/c$:$$(1+2sc)(1-t)=(c^2-s^2)(1+t)$$
Now divide both sides by $(1-t)(c^2-s^2)$ to achieve:$$\frac{1+2sc}{c^2-s^2}=\frac{1+t}{1-t}$$

A: $\dfrac{1+\tan t}{1-\tan t} =$
$\dfrac{\cos t + \sin t}{\cos t -\sin t}=$
$\dfrac{(\cos t+\sin t)^2}{\cos^2 t - \sin^2t}=$
$\dfrac{1+2\sin t \cos t}{\cos^2 t-\sin^2 t}$.


text:
Q: Raw ReactJS update properties I am using React to render some components needed to my web app and I have a timer with a play and a stop button. I am retrieve all of my time records from a get request and I want to rerender my component each time It changes, how can I do that?
I have everything working but with a simple setInterval to a function that calls this.forceUpdate() but that gives me the warning of:

Warning: forceUpdate(...): Can only update a mounted or mounting component. This usually means you called forceUpdate() on an unmounted component. This is a no-op. Please check the code for the TimerBox component.

My component:
var TimerBox = React.createClass({
    displayName: 'TimerBox',

    updateTime: function () {
      getTime();
      this.forceUpdate();
      this.props.records = allRecords(); // get all time records
    },

    componentDidMount: function () {
      setInterval(this.updateTime, 1000); // set interval to each second
    },

    render: function () {
      this.props.records = allRecords();
      return (
        React.createElement('div', { className: 'main-timer-box' },
          React.createElement('div', { className: 'timer-box' }, hours + ' hours, ' + minutes + ' minutes and ' + seconds + ' seconds',
            React.createElement(ControlButton, null)),
          React.createElement('hr', null)
        )
      );
    }
  });

I am new to reactjs and I started using react without jsx, babel or webpack and I don't wan't to change the entire code, for now.
What I simply want is to know I can I declare a property and then make the property call a rerender on each time it changes value.
Thank you.

A: You should update component state and it will automatically re-render component. Furthermore,  you have to clear timeout in componentWillUnmount lifecycle method to make sure that setState is called only if component hasn't been unmounted.
 updateTime: function () {
      getTime();
      this.setState({
         records: yourRecordsData
      })
  }
  componentDidMount: function () {
      this.myTimer = setInterval(this.updateTime, 1000); // set interval to each second
  },
  componentWillUnmount: function () {
      clearInterval(this.myTimer)
  },

Now you can use state data in render functions like this: this.state.records.
Please note that React components are re-rendered when their state has been updated or when their parent has been re-rendered. You should never set component own props - you can only set props on child components. And generally you shouldn't use forceUpdate (and to be honest you will almost never need it). Check react docs for more details and explanation why forceUpdate should be avoided.

A: The problem here is you have a setInterval that has no notion of when the component has unmounted from the DOM. So once the component does unmount, the setInterval function fires off anyways and tries to update the state of the unmounted component which causes this problem.
To resolve that warning you just need to do:
componentDidMount: function () {
     this.interval =  setInterval(this.updateTime, 1000); // set interval to each second
    },

componentWillUnmount: function() {
  clearInterval(this.interval);
}

what this does is set this.interval to the timer id of the interval and then using the componentWillUnmount lifecycle method we make sure we clear the timer that way the code isn't being executed after the component has unmounted.


text:
Q: Custom popup like infoWindow for button I am trying to find a way to create a custom popup like infowindow for buttons but I am not able to find out any tutorial or any other solution for this. Can anyone guide me to create a popup like infowindow for buttons button with custom popup

A: There are lot of libraries available for this type of feature -

*

*http://www.codeproject.com/Articles/521455/Quick-action-pattern-in-Android-and-simple-impleme

*http://shardulprabhu.blogspot.ro/2012/08/blog-post_29.html

*https://github.com/michaelye/EasyDialog
You can go through these links and use any of those you like.


text:
Q: How to use regular expression in hbase I am new to HBase and trying to do some scan query. Below is my sample data:
2470883371  column=card info:CARD_TYPE, timestamp=1439291958723, value=MASTERCARD
2470883371  column=card info:UNIQUE_NO, timestamp=1439291958767, value=991-761-828-450
2470883371  column=card info:EXPIRY_DATE, timestamp=1439291958747, value=Wed Oct 03 18:09:34 IST 2018
3495415072  column=card info:CARD_TYPE, timestamp=1439291958835, value=MASTERCARD
3495415072  column=card info:UNIQUE_NO, timestamp=1439291959618, value=973-470-914-600
3495415072  column=card info:EXPIRY_DATE, timestamp=1439291958850, value=Wed Oct 03 18:09:34 IST 2018

I want to query like:

*

*Retrive all results that start from rowkey id 2470883 (actual value is 2470883371)

*Retrive all results whose unique number starts from 991-761-828 (actual value is 991-761-828-450)
Is it possible in HBase using scan? Basically I want to know how to use a regular expression.

A: Take a look at Filters and Comparators, for example RegexStringComparator https://hbase.apache.org/0.94/apidocs/org/apache/hadoop/hbase/filter/RegexStringComparator.html

A: This regular expression should match what you need:
((?:^2470883.*?$)|(?:^.*?value=991-761-828.*?$))


text:
Q: Capture multiple values from a tag  in a String vector In my spring application, I have an html form with a  which needs to send values serverside.
The code in the JSP page to send the values to server is:
html form
<form name="form_lista_horario">
    <select name="id_evento" id="id_evento">
        <c:forEach var="evento" items="${lista_eventos}">
          <option value="<c:out value="${evento.id}"/>"> ${evento.nome} - ${evento.descricao} </option>
        </c:forEach>
    </select>

            <select name="lista_usuarios" id="usuarios" size="10" multiple="multiple">
                <c:forEach var="usuario" items="${lista_usuarios}">
                    <option value="${usuario.id}">${usuario.nome}</option>
                </c:forEach>
            </select>

 <button type="button" class="btn btn-lg btn-default" id="for_left"> << </button>

 <button type="button" class="btn btn-lg btn-default" id="for_right"> >> </button>

            <select name="selecao_usuarios" id="selecao" size="10" multiple="multiple">
            </select>

    <button type="button" class="btn btn-lg btn-default" id="btn_enviar">OK</button>
</form>

jQuery code
$("#btn_enviar").click(function(){
    $.ajax({
        url: "lista_horario.html",
        data: { id_evento: $('#id_evento option:selected').val(), id_usuarios: $('#selecao option').val()  },
        cache: false
    }).done(function(data) {
        $("#result").show();
        $("#result").empty().append( data );
    });
});

This data is read by this method from my controller:
@RequestMapping(value="/lista_horario", method=RequestMethod.GET)
@ResponseBody
public String lista_horario(@RequestParam("id_evento") String id_evento, @RequestParam("id_usuarios") String[] id_usuarios)
{
     ...
    }

My problem is this method is reading only the first value of the . Does anyone know how to solve this issue?
UPDATE
Ok, problem not entirely solved yet. Sorry, I realize don't make enough tests. Now, when I try submit the form to server, the console of the browser show this is being sent:
**id_evento:"1"**

and
id_usuario[] 9
id_usuario[] 4
id_usuario[] 7
id_usuario[] 8
**_:"1395536033181"**;

only the first parameter is being sent correctly.
My jquery code now is this:
$("#btn_enviar").click(function(){
    var selecao_usuario=[];
    $('#selecao option').each(function(){
        selecao_usuario.push($(this).val());
    });
    $.ajax({
        url: "lista_horario.html",
        data: { id_evento: $('#id_evento option:selected').val(), id_usuarios: selecao_usuario },
        cache: false
    }).done(function(data) {
        $("#result").show();
        $("#result").empty().append( data );
    });
});

A: Try this:
<select name="id_evento" id="id_evento" multiple>
    <c:forEach var="evento" items="${lista_eventos}">
      <option value="<c:out value="${evento.id}"/>"> ${evento.nome} - ${evento.descricao} </option>
    </c:forEach>
</select>

See what it does. It should allow for multi-select which will separate the selected values with a comma.

A: try this
var id_evento_valores=[];
$('#id_evento option:selected').each(function() {
id_evento_valores.push($(this).val());
});

//..

 $.ajax({
        url: "lista_horario.html",
        data: { id_evento: id_evento_valores, id_usuarios: $('#selecao option').val()  },
        //...

or if you want it as a comma seperated list instead of an array
var id_evento_valores=[];
    $('#id_evento option:selected').each(function() {
    id_evento_valores.push($(this).val());
    });

var id_evento_cuerda=id_evento_valores.join(",");
//..


text:
Q: Voltage drops on circuit powering a servo motor. Is there a solution? I have a 5 Volts, 4 Amps power supply that gives power to a Raspberry Pi Zero W (120-230mA at 5.19V), and a servo motor with these specifications:
Operating Voltage Range (Volts DC)  4.8V ~ 6.0V
Current Draw at Idle                8 mA
No Load Operating Current Draw      240 mA
Stall Current Draw                  1,200 mA
Maximum Torque Range oz. / in.      42 ~ 49
Maximum Torque Range kg. / cm.      3.0 ~ 3.5

Sometimes it is able to perform its action, and some other times it stalls half-way with the voltage dropping in the 3.5 V - 4 V range. Even though my power supply should be good enough in theory, I thought that adding a 4 F (16 V) capacitor could alleviate the problem, but it does not seem to make any difference.
Do you think the voltage drops because I am using the servo to perform a task at the limit of its strength, or that the servo stalls because it does not have a good enough power source?
Unfortunately, I do not have any tool to measure the torque of the item the servo is rotating.
Servo Motor: Hitec 32085S HS-85MG Metal Gear Micro BB HS/HT Universal Servo
Please bear with me. I have some electronics notions, but I am no electrical engineer. If you think I posted this message in the wrong stack, please let me know. It just seemed the most appropriate one to me for this question.

A: You basically had the right idea to use a cap for voltage stabilisation. But a cap with 4F capacity is a supercapacitor, and those have a very high output resistance. So your Supercap is not able to deliver the current needed for the servo.
Please try to use a few 220uF aluminium electrolytic type caps. They have output resistance in the milliohms range and they should do the trick of stabilizing your voltage.


text:
Q: Array Randomica entre valores especificos Gostaria de elaborar um array() onde eu possa colocar:
$arr = "argumento1, argumento2, argumento3..";
E retornar apenas 1, 2 ou 3, randomicamente.
Como é possível fazer?

A: Você pode fazer assim:
array_rand
//Criando array
$a = array("red","green","blue","yellow","brown");

//Número máximo do rand
$max = (count($a) - 1);

//Resultado randômico
echo rand(0, $max);

A: Existem várias e várias alternativas.
random_int (PHP 7):
$array = ['um', 'array', 'qualquer'];

// Contagem de elementos da array:
$contagem = count($array);

// Gera a "randomização" (ex. '2'):
$gerador = random_int(0, ($contagem - 1));

# É necessário subtrair um porque existem 3 elementos, porém array começa em 0 até 2, ao invés de 0 até 3. Portanto reduzindo 1, irá fazer com que entre na condição de 0 até 2. ;)

// Seleciona o item gerado previamente (ex. 'qualquer'):
$final = $array[$gerador];

Este método (random_int) é supostamente o mais seguro!

Veja mais na documentação
array_rand (PHP 4, PHP 5, PHP 7):
$array = ['um', 'array', 'qualquer'];

// Gera a "randomização" (ex. '2'):
$gerador = array_rand($array);

// Seleciona o item gerado previamente (ex. 'qualquer'):
$final = $array[$gerador];

Veja mais na documentação
mt_rand (PHP 4, PHP 5, PHP 7):
$array = ['um', 'array', 'qualquer'];

// Contagem de elementos da array:
$contagem = count($array);

// Gera a "randomização" (ex. '2'):
$gerador = mt_rand(0, ($contagem - 1) );

# É necessário subtrair um porque existem 3 elementos, porém array começa em 0 até 2, ao invés de 0 até 3. Portanto reduzindo 1, irá fazer com que entre na condição de 0 até 2. ;)

// Seleciona o item gerado previamente (ex. 'qualquer'):
$final = $array[$gerador];

Veja mais na documentação


text:
Q: How to run an application (.exe) via a button in the main menu created in minecraft I am developing a modpack (package with modifications) for minecraft specifically technic. But recently the technic removed modpacks update their system. I made a script in C # to help me with this. It ran everything perfectly, but when using the mod called "Custom Main Menu" there would be the possibility of making when I clicked the button that I created it launched the program?
Link to mod: CustomMainMenu - CurseForge
All assistance is well accepted.
So did the program of the system (in steps):

1: Open the program
2: It connects to the database on my server from my site and checks the versions of that particular modpack. (I used PHP and JSON to perform this step)
3: Return: Has version? He asks if you want to upgrade, but for this he asks the player to leave the game to the program to make an automatic backup of the worlds he created.
4: It starts downloading modpack update file. (Usually we use Zip it will depend on who uses this my application on their modpacks. Type the person asked the program, I ask how you want the modpacks be updated and it me of the answer. We compile the application and send the way the person asked).
5: Finished it, it erases the "mods" folder and the "config" folder to place the new files. And asks the player whether to keep the created worlds.
6: After having updated it asks for the player to run the technic again and have fun with modpack. :)

.

See too: CustomMainMenu on Youtube


text:
Q: Why would I be getting a NoSuchMethodError at super.onCreate() for registerFragmentLifecycleCallbacks in Android? I have been receiving this error:
02-06 14:14:33.984 2806-2806/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.ibm.cher.tabatha, PID: 2806
                                             java.lang.NoSuchMethodError: No virtual method registerFragmentLifecycleCallbacks(Landroid/support/v4/app/FragmentManager$FragmentLifecycleCallbacks;Z)V in class Landroid/support/v4/app/FragmentManager; or its super classes (declaration of 'android.support.v4.app.FragmentManager' appears in /data/app/com.ibm.cher.tabatha-1/base.apk:classes9.dex)
                                                 at android.arch.lifecycle.LifecycleDispatcher$DispatcherActivityCallback.onActivityCreated(LifecycleDispatcher.java:75)
                                                 at android.app.Application.dispatchActivityCreated(Application.java:197)
                                                 at android.app.Activity.onCreate(Activity.java:961)
                                                 at android.support.v4.app.BaseFragmentActivityDonut.onCreate(BaseFragmentActivityDonut.java:41)
                                                 at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:315)
                                                 at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
                                                 at com.ibm.cher.tabatha.tabatha_mobile_app.MainActivity.onCreate(MainActivity.java:46)
                                                 at android.app.Activity.performCreate(Activity.java:6679)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                 at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:154)
                                                 at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

It seems to happen when the AVD I am running crashes during compilation and then never fixes itself. I have tried invalidating cache and restarting as well as doing a complete rebuild of the project with no success. These are my gradle files for the project as well as the sub project causing this error.
build.gradle(subproject)
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.3'

defaultConfig {
    applicationId "com.ibm.cher.tabatha"
    minSdkVersion 23
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
lintOptions {
    abortOnError false
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':shared')
    compile 'com.google.android.gms:play-services-wearable:'
    compile 'com.android.support:appcompat-v7:'
    compile 'com.android.support:multidex'
    compile files('libs/watson-iot-0.2.6.jar')
    compile 'com.google.android.gms:play-services:9.6.0'
    compile 'com.androidplot:androidplot-core:1.5.1'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile files('libs/org.eclipse.paho.android.service-1.1.1.jar')
    compile files('libs/org.eclipse.paho.client.mqttv3-1.1.1.jar')
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
    compile 'android.arch.lifecycle:extensions:1.0.0-rc1';
    compile 'android.arch.persistence.room:runtime:1.0.0-rc1';
    annotationProcessor 'android.arch.lifecycle:compiler:1.0.0-rc1';
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-rc1';
}

packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
    exclude 'META-INF/ASL2.0'
}
}

build.gradle(overall project)
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath('com.android.tools.build:gradle:2.3.3') {
        force = true
    }

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Has anybody else gotten this specific error or ran into something similar?

A: What's the version of appcompat? (in your posted code there is just a colon). Same for multidex.
Does another library in your dependencies bring in another version of appcompat that is older?
You should try adding the version. If it's not working after that try adding force=true to your appcompat dependency.
Also:  I am not sure, but multidex might be dependent on certain build tools/Gradle versions,so you might want to update everything to the latest version.
Also try building without instant run and try deinstalling/reinstalling  app from avd via adb.
Essentially there is 2 possibilities I can see : either in your class path is a version of appcompat that has not the method you are calling or multidex is not able to put the stuff in the right dex files. For the latter you might have to look into the documentation by Google. There are ways to change which dex files contain which classes and the order of loading (I think).


text:
Q: ViewController Delegate Doesn't Get Invoked I am trying to implement an external module called JTAppleCalendar in my app and load a calendar when a user taps on a button. While the view associated with the external calendar loads properly, the delegate method for the viewcontroller associated with the view doesn't get invoked; thus, no calendar shows up. Tried debugging and figuring out why this happens, no luck. I have the entire project here: https://github.com/cooderatgit/CalendarApp/tree/master/KataNews
Problem code is in the CalendarViewController.swift. The associated xib is Calendar.xib. The delegate function is calendar(). ViewController.swift manages the main storyboard views.
The tutorial that I am following for setting up the calendar: https://patchthecode.github.io/MainTutorial/

A: The problem is related to the way you are presenting CalendarViewController.
In line 30 of ViewController.swift you only add the CalendarViewController's view as a subview of the navigationController.
A better way to do this could be:
self.navigationController?.present(overlayView, animated: true)

This should properly present the view controller.


text:
Q: Switching from user mode to kernel mode In my operating systems class, I'm asked whether switching from user to kernel mode is privileged. This is not OS-specific. At first I thought yes, but it seems like a big Catch 22. I referred to my textbook:

The hardware allows privileged instructions to be executed only in
  kernel mode.  ...
The instruction to switch to kernel mode is an example of a privileged
  instruction.
Gagne, Greg; Abraham Silberschatz; Peter B. Galvin (2010-01-26).
  Operating System Concepts (p. 22). Wiley Higher Ed. Kindle Edition.

So we start in user mode. To switch to kernel mode requires a privileged instruction. A privileged instruction must be done in kernel mode, therefore we must switch to kernel mode to enable switching to kernel mode.
I'm thinking the system does not allow a user to switch itself to kernel mode directly, but that it is done by the kernel when the user seeks to execute another privileged instruction. Is that correct?

A: That is a typo introduced in the 8th edition and kept in the 9th. In the seventh edition, page 19, it says instead:

"The instruction to switch to user mode is an example of a privileged
  instruction."

Which clearly makes a lot more sense.

A: In user mode you cannot just switch to kernel mode. Interaction between user and kernel is done via system-calls. Each system-call is providing one defined service. The user sends the service name (usually a number) and the required parameters.
Here is a real world example how this is done. It's x86 AT&T style assembler.
It moves the system-call name into the EAX register, the pointer to the parameters into the EBX register of the CPU and then emits the software interrupt number 42. The interrupt handling will do the switch to kernel mode. The interrupt number is looked up in the Interrupt Descriptor Table (IDT) and invokes the function that's registered there, the syscall handler. This handler executes in kernel mode. On return to the user mode the code will move the content of EAX into the variable ret.
pok_ret_t pok_do_syscall (pok_syscall_id_t syscall_id, pok_syscall_args_t* args)
{
  pok_ret_t ret;
  uint32_t  args_addr;
  uint32_t  id;

  args_addr = (uint32_t) args;
  id        = (uint32_t) syscall_id;

  asm volatile ( "movl %1,%%eax  \n\t"
                 "movl %2,%%ebx  \n\t"
                 "int $42        \n\t"
                 "movl %%eax, %0 \n\t"
                 :"=g"(ret)
                 :"g"(id), "g"(args_addr)
                 : "%eax" , "%ebx"
               );
  return ret;
}

The OS Dev wiki is a good point to read more about this.
So you don't just switch to the kernel, but you can ask the kernel to do something for you. And then the kernel is telling you if it was done or not.

A: There are usually as set of instructions that are not really to switch to kernel mode in s general way, but to request system services. So these switch to kernel mode, but only in the context of calling some piece of functionality which was set up by the operation system for the purpose of being called by user code.
In most modern systems, even this is hidden by an API layer that implements a specific function part of which may be doing an operating system call as above.
But in general it is true that user code cannot do the equivalent of saying "from this point on, I want to be running in kernel mode".

A: In user land, you request privileged operations via system calls to the kernel, which performs the switch to kernel mode as necessary.  The user is using an API, the kernel is performing the privileged operations.


text:
Q: INSERT INTO new MYSQL row only if all values are present I'm trying to work out a MySQL query that only adds a new row to an existing table if all fields have a value present, otherwise it should be dropped/ignored.
The query I have at the moment is as follows:
 INSERT INTO markers (`name`, `address`, `details`, `date`, `link`, `lat`, `lng`, `type`)
    VALUES ("{1}", "{2}", "{3}", "{15}", "{4}", "{11}", "{12}", "{5}")

If {15} is left blank by my form then I don't want any of the other values added to the table.
Hope that makes sense!
Thanks

A: I would suggest you do a couple of different solutions.
You could setup your database to not allow null values, and then when you go to insert, handle your null errors (probably not the best solution out there though). If you need to have null values, then you will have to handle this in code.
The other thing is to implement form validation. You can do this with JavaScript, code behind, or even both. Both is suggested as some people may have JavaScript disabled on their browser.

A: I'd  say check the inputs on the front-end with Java, C#, Swift, whatever. Then if an entry is blank, just make a pop-up message letting your user know to fill out every field, or for your application to just skip that record.

A: If you want to do this directly in MySQL, you can create a trigger that checks the values before they are inserted, and throw an error if some validation rule is not fulfilled.
Example:
delimiter $$
create trigger no_emtpy_values before insert into markers
for each row
begin
    declare msg varchar(255);
    declare condition_fail int default 0;
    -- Write the appropriate validations and set condition_fail to 1
    -- if the validations are not fulfilled. For example:
    if NEW.`date` IS NULL then
        set condition_fail = 1;
    end if;
    -- That "NEW" refers to the row about to be inserted

    -- If the validation rules are not fulfilled, throw an error:
    if condition_fail then
        set msg = "You can't insert the data!";
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
    end if;
end $$
delimiter ;

References:

*

*"How to abort INSERT operation in MySql trigger?"

*MySQL reference manual: CREATE TRIGGER Syntax
Hope this helps


text:
Q: Is it possible to modify the state of a react functional component in an external function(Another file)? I have a lot of methods in my functional component which i would like to place in separate files,these methods use the state of the functional component and it should be able to set the states.Example below:
export default functional_component(){
   const [state, setState] = React.useState({
        //state variables
})
}

//another file.js
const foo = () =>{
          setState();

}

A: You can pass setState function as parameter to your functions in other files though it does not really make sense to seperate state logic of component to seperate script files unless you have a very good reason to do it.
export default functional_component(){
 const [state, setState] = React.useState({
    //state variables

   foo(setState)
 })
}

//another file.js
const foo = (setState) =>{
      setState();

}


text:
Q: angular expression not working for html I'm using angular grid -
let's say i have a scope object as follows:
$scope.test = 3

If I want to dynamically set an html id, I would do something like this:

Checking the DOM, I see the following:

For my angular grid, I want to do something like this:

Checking the DOM I literally get:

Is there a way around this?

A: You can use ngAttr and do this like the following:
ng-attr-ag_grid="{{test}}"

Please check if this helps

A: Use

Check following link and check first example html file forag-grid tag with binding variable
Note: Based on example test should be object not string or other type.

A: Is {{ }} necessary?
You can try:
ag-grid="test"


text:
Q: One-Tap verification fails at SmsBroadcastReceiver I am trying to make the one-tap verification work in an example app (https://developers.google.com/identity/sms-retriever/user-consent/overview?hl=en).
Currently I do not receive an SMS call in the onReceive of my BroadCastReceiver:
class MainActivity : AppCompatActivity() {

    object Constants {
        const val RESOLVE_HINT = 0
        const val CREDENTIAL_PICKER_REQUEST = 1
        const val SMS_CONSENT_REQUEST = 2
    }

    private val smsVerificationReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
                val extras = intent.extras
                val smsRetrieverStatus = extras?.get(SmsRetriever.EXTRA_STATUS) as Status

                when (smsRetrieverStatus.statusCode) {
                    CommonStatusCodes.SUCCESS -> {
                        // Get consent intent
                        val consentIntent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
                        try {
                            // Start activity to show consent dialog to user, activity must be started in
                            // 5 minutes, otherwise you'll receive another TIMEOUT intent
                            startActivityForResult(consentIntent, SMS_CONSENT_REQUEST)
                        } catch (e: ActivityNotFoundException) {
                            // Handle the exception ...
                        }
                    }
                    CommonStatusCodes.TIMEOUT -> {
                        // Time out occurred, handle the error.
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        registerReceiver(
            smsVerificationReceiver,
            intentFilter,
            SmsRetriever.SEND_PERMISSION,
            Handler(Looper.getMainLooper())
        )

    }

    override fun onResume() {
        super.onResume()
        startSMSRetreiver(this)
    }

    private fun startSMSRetreiver(activity: Activity) {
        val smsRetreiver = SmsRetriever.getClient(activity)
        smsRetreiver.startSmsUserConsent("+1 650 555-6789")
        // +1-555-521-5554 Emulator Phone Number
        // +1 650 555-6789 Sender Number
        // pass null if you want to select a phone number
    }

    // Obtain the phone number from the result
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            SMS_CONSENT_REQUEST ->
                // Obtain the phone number from the result
                if (resultCode == Activity.RESULT_OK && data != null) {
                    // Get SMS message content
                    val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                    // Extract one-time code from the message and complete verification
                    // `message` contains the entire text of the SMS message, so you will need
                    // to parse the string.
                    val oneTimeCode = parseOneTimeCode(message) // define this function

                    // send one time code to the server
                } else {
                    // Consent denied. User can type OTC manually.
                }
        }
    }

    private fun parseOneTimeCode(message: String?): String? {
        return message
    }
}

As you can see I want to try it out with the emulator, where you can send SMS to yourself conveniently. My problem is that after starting the app and sending myself an SMS, I do not receive a call in the BroadcastReceiver. I am not sure if I setup my Receiver correctly, also maybe the PhoneNumber is not correct (does is have a specific format?). Maybe I am missing something else.
My goal is to not use additional Permissions in the Manifest, receive the SMS code and parse it / pass it somewhere.

A: I did some deeper debugging and found out, that if I check the success of
smsRetreiver.startSmsUserConsent(null).addOnSuccessListener {
                    println("SmsUserConsent success")
                }
                .addOnFailureListener {
                    println("SmsUserConsent failure: $it")
                }

it fails on the emulator with com.google.android.gms.common.api.ApiException: 17: API: SmsRetriever.API is not available on this device. Connection failed
Maybe this is fixable with some setup of the emulator or some proxy settings that I am missing, but on my real device the code works. Hope this can help someone, if you got questions, feel free!


text:
Q: What are different forms of a verb falling under the same criteria I have seen many different verbs that have different forms based on the conditions in/by which they may occur. Example can be as following:

*

*See

*Watch

*Gaze

*Stare

*Glimpse

Is there a name for these kind of verbs (falling under the same criteria, yet expressing different forms of its occurance)?

A: You're talking about synonyms, related words, and hyponyms: words that share a meaning, hold a related meaning, or that are subcategorical words within a larger category. To illustrate using your example with a search in the Merriam-Webster thesaurus for "see,"

*

*Watch - word related to see (entry 1)

*Gaze - no mention (but listed as related to watch, verb entry 1)

*Stare - no mention (but listed as related to watch, verb entry 1)

*Glimpse - word related to see (entry 1)

Notice how the editors classify two of the words as related, and how the other two words are at least related to watch. This signals that they aren't strict synonyms (there's a denotative difference between seeing and watching) but they are related as words referring to sight-related actions. Here's how Merriam-Webster explains related words:

... this thesaurus includes lists of related words, which are words whose meanings are close enough to the synonymy group to be of interest to the user. These related words do not qualify as synonyms because they have meanings that differ from the basic meaning shared by the synonymy group in some significant way.

The tricky thing is that other thesauruses will list some of these words as synonyms. The distinction is inexact.
If the messiness of how to categorize a word as synonym or related word is too imprecise, another way to describe all of this is to say that gaze, glimpse, watch, and stare are hyponyms of the general verb to see. This is the example that ThoughtCo uses to explain the concept of hyponyms:

Hyponymy is not restricted to nouns. The verb to see, for example, has several hyponyms—glimpse, stare, gaze, ogle, and so on. Edward Finnegan points out that although "hyponymy is found in all languages, the concepts that have words in hyponymic relationships vary from one language to the next"
  (Language: Its Structure and Use, 2008).


text:
Q: .NET Nullable CS8619 Possible null reference assignment fix I have a .NET6 project with nullable set to enable.. with that brings up this CS8619 issue with the following code. How would you go about handling this?
using System.Data;

DataTable dt = new DataTable();

dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Description",typeof(string));

dt.PrimaryKey = new DataColumn[]
{
    // CS8619
    // Possible null reference assignment.
    dt.Columns["ID"]
};

This code worked fine in the old days, but obvisouly not with the column lookup being a DataColumn? type

A: You can use the return value of Add.
var idColumn = dt.Columns.Add("Id", typeof(int));
...

dt.PrimaryKey = new DataColumn[]
{
    idColumn
};

If you don't/can't do this and you know the value is definitely not null use the null-forgiving operator.
dt.PrimaryKey = new DataColumn[]
{
    dt.Columns["ID"]!
};

If you cannot guarantee it's not null than just check if it's null:
var primaryKeyColumn = dt.Columns["ID"];
if(primaryKeyColumn == null)
{
    throw new Exception("Failed to find ID column");
}
dt.PrimaryKey = new DataColumn[]
{
     primaryKeyColumn
};


text:
Q: JAVA SQL catching / declaring exceptions Can somebody please tell me how to fix the error on line 8 of my Test class
I have no idea wtf is wrong with it or how to even search for solution
Main class
package T;
public class Test {
    public static void main(String[] args) {
        SQL sql = new SQL();
        sql.getData();//Error here "Unreported exception Exception; must be caught or declared to be thrown"
    }
}

SQL Class
package T;
public class SQL {
    private Connection connect = null;

    public String getData() throws Exception {
        String name = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection("jdbc:mysql://localhost/vehicles?" + "user=sqluser&password=sqluserpw");
            Statement st = connect.createStatement();
            ResultSet rs = st.executeQuery("SELECT * from vehicles.test");
            if (rs.next()) {
               name = rs.getString("word");
            }
            return name;
        }
        catch (Exception e) {
            throw e;
        }
    }
}

A: The method in your SQL class throws an exception and in the main method you don't handle that exception. This is a checked exception so you MUST do something about it.
At least you need to have a simple catch like that
public static void main(String[] args) {

    SQL sql = new SQL();
    try{
      sql.getData();//Error here "Unreported exception Exception; must be caught or declared to be thrown"
    }catch(Exception e){
      e.printStackTrace();
    }
}

A: As your Calling  method is throwing the exception it is required to catch that exception in Called method.So just put your call inside try catch block.

A: is that questionmark necessary? is not a typo and you meant something else?
here are some examples of sqlconnections in java, they look a little bit different than yours. How to make SQL connection statements common

A: Simply surround your line with a try-catch loop

A: public String getData() throws Exception {
    //
}

Here throws Exception means that this method might throw an exception of type Exception, which is a checked exception.
So it must be handled while calling this method. Means use a try/catch.
This article might help you learn about checked and unchecked exceptions.


text:
Q: What mail service/server to use while in dev mode in Rails? It does not seem that SendGrid has a free account that one could use to test in development mode. What are the current alternatives/best practices for this?

A: One good option is using the letter_opener gem.  See https://github.com/ryanb/letter_opener
First add the gem to your development environment and run the bundle command to install it.
gem "letter_opener", :group => :development

Then set the delivery method in config/environments/development.rb
config.action_mailer.delivery_method = :letter_opener

Now any email will pop up in your browser instead of being sent. The messages are stored in tmp/letter_opener.


text:
Q: Calc question on radioactive decay The method of carbon dating makes use of the fact that all living organisms contain two isotopes of
carbon, carbon-12, denoted 12C (a stable isotope), and carbon-14, denoted 14C (a radioactive isotope).
The ratio of the amount of 14C to the amount of 12C is essentially constant (approximately 1/10,000).
When an organism dies, the amount of 12C present remains unchanged, but the 14C decays at a rate
proportional to the amount present with a half-life of approximately 5700 years. This change in the
amount of 14C relative to the amount of 12C makes it possible to estimate the time at which the organism
lived.
a)A fossil found in an archaeological dig was found to contain 20% of the original amount
of 14C. What is the approximate age of the fossil?
-Should I be doing $0.20=0.5^{t/5700}$ to get a final result of $13235$ years or using the equation $t=[\ln0.20/(-.693)]\cdot5700$?
b) The Dead Sea Scrolls are approximately 2000 years old. What percent of the original
14C remains in them?
-I'm very unsure of which parts of the given question to use for this part & what equation I should use for the calculation in general. Maybe A=Ce^kt? With k=.0001 amd t=2000?

A: Natural logarithms need to be used in this sort of problem ONLY when you're dealing with instantaneous rates of change.  You've got
$$
\left(\frac 12\right)^{t/5700} = 0.2 = \frac15.
$$
So
$$
2^{t/5700} = 5.
$$
Hence
$$
\frac{t}{5700} = \log_2 5,
$$
and the bottom line is
$$
t = 5700\log_2 5.
$$
This is the same thing as
$$
e^{(-\ln2)t/5700} = \frac15,
$$
etc.  So you've got $e^{-kt}$, where $k=-(\ln2)/5700$.  You need that form if you want to talk about how fast it's changing at a particular instant in time.  Here's a commonplace clumsy mistake: Put in some rounded value of $(\ln2)/5700$ and go from there, and end up with an approximate answer, where use of $1/2$ instead of $e^{-\ln2}$ would yield an exact answer.  So bringing in $e$ and natural logarithms adds complications.  It should be used when needed, but it's not needed to answer questions like the one posed here.
For part (b), you've got $\left(\frac12\right)^{2000/5700}$.


text:
Q: JQuery: elegant way to replace set of elements with another set? I have a bunch of DOM like

and I want to replace it with a new set of stuff

Which will be fetched via Ajax. My question is: what is the best way to do this?
$.replaceWith doesn't quite do what I want, because I then end up with multiple copies of the new stuff.
I can guarantee that all the stuff will be in one contiguous block, and so presumably I could put in some placeholder after the last element (or before the first element) of the old stuff, remove the old stuff, and replace the placeholder with the new stuff.
However, this seems rather roundabout and inelegant. Is there any clever way of, removing all the old stuff and putting in a single copy of the new stuff, all at one go?
EDIT: I would also like to do this without using any container divs. Using container divs would work in the above case, but would fail in some cases, like when the stuff is inside a
:

If i want to replace the rows labelled stuff with another set of rows, possibly more, possibly fewer, there is no way I can nicely put them in a container thingy without breaking the HTML, since the  can only contain
s (IIRC).

A: Yes: $('#tagetDiv').html(newContent)

A: One way to do it would be with wrapAll:
$('.stuff').wrapAll('
').parent().replaceWith('
');

I'm not sure if that passes the "elegant" test, but it does work regardless of whether there is any other content in the containing element.
With that said, though, this seems to be a very complicated solution to a simple problem. The simple solution would be to wrap your elements in a containing element; this shouldn't be a problem if, as you say, you can guarantee that they will always be together.

A: $('#outerdiv').empty().append(newContent);

Unlike .html(), this will work regardless of whether newContent is an HTML string, or an existing DOM structure.
If there are multiple elements to be replaced but where you need to retain their siblings, you can do this:
$('.stuff').first().before(newContent).end().remove();

i.e. take the first .stuff element, add the new content before it, and then remove all the .stuff elements.


text:
Q: OCAML how to find the next element of the variant I have  -> type week = MON | TUE | WED......        I want to create the function tomorrow which return the next day! For example , if I call "tomorrow MON", the function will return TUE.

A: There is no built-in language construction which allows you to do this. So you should write the function yourself:
let tomorrow = function
  | MON -> TUE
  | TUE -> WED
  ...

Another possibility is to implement these functions:
val int_of_week: week -> int
val week_of_int: int -> week

It happens that those functions are trivial to write with Obj.magic. They would allow you to implement tomorrow as:
let tomorrow w =
  week_of_int ((int_of_week w + 1) mod 7)

which is probably closer to what you had in mind.
But this solution is less safe:

*

*function tomorrow assumes that int_of_week MON = 0, int_of_week TUE = 1 and so on;

*you need to document the behavior of week_of_int for integers which are not between 0 and 6;

*and, last but not least, Obj.magic is not actually part of the language.

A: Unlike in Haskell, you cannot just do deriving(Ord) and call succ/pred
You will haveto code these functions by hand. For example
let tomorrow = function
  | MON -> TUE
  | TUE -> WED
  | (* etc.. *)


text: Q: What is the switching/amplifier component in a 2.4 GHz wifi microwave transmitter I know that it is hard for the transistors that i know to switch at high frequency but the latest microprocessors and microwave transmitting chips use GHz frequency, what is the gain element there (like a transistor, spark gap etc)


text:
Q: fragment observe issue I am facing an issue with LiveData and Fragment Lifecycle.
The flow goes like this:

*

*The 1st Fragment shows a recyclerview of comments. Each comment has a delete button.

*The 1st Fragment has a menu button, which when pressed, navigates the user to a 2nd Fragment to create a new comment.

*When the user creates the comment, a feedback dialog is shown and onBackPressed is called to dismiss the 2nd Fragment.

*The 1st Fragment refreshes the list of comments to show the changes.

Take a look at the code snippets below. The method observe is getting called on the Fragment's onCreateView.
1st Fragment:
private void observe() {
    //getComments method observes the API response from the allComments method
    mainViewModel.getComments().observe(getViewLifecycleOwner(), resp -> {
        if (resp != null && resp.getStatus().equalsIgnoreCase("success")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("success message");
            builder.setPositiveButton("ΟΚ", (dialog, id) -> {
                dialog.dismiss();
                getActivity().onBackPressed();
            });
            builder.create().show();
        }
    });
}
mainViewModel.getCommentDelete().observe(getViewLifecycleOwner(), resp -> {
        if (resp != null && resp.getStatus().equalsIgnoreCase("success")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Comment deleted.");
            builder.setPositiveButton("ΟΚ", (dialog, id) -> {
                dialog.dismiss();
            });
            builder.create().show();
            //allComments method makes an http call to the API to fetch comments
            mainViewModel.allComments(mainViewModel.getSelected().getId());
        }
    });

//initView. The adapter has a listener to listen for button clicks.
mAdapter = new BuildingCommentsAdapter(new RecyclerMultipleOptionsClick() {
        @Override
        public void onItemClicked(int position, int id) {
            Comments comment = mAdapter.getItemAtPosition(position);
            switch (id) {
                case R.id.comment_save:
                    mainViewModel.commentUpdate(new UpdateCommentReq(mainViewModel.getSelected().getId(), comment.getComment(), comment.getId()));
                    break;
                case R.id.comment_delete:
                    mainViewModel.commentDelete(comment.getId());
                    break;
            }

        }
    });

The issue i am facing is:
I run the app and I go to the comment list fragment, I press the add comment button and go to 2nd Fragment. Adding a comment and going back. So far so good. Now, I delete one comment from the list (works great). I navigate again to the 2nd Fragment to create a new comment and going back again to the 1st Fragment. The mainViewModel.getCommentDelete().observe(..) runs again, showing the success dialog (without deleting something). The problem is that the observer is triggered again and again once I delete one comment from the list.
I can provide more code if you like. Any help would be really helpful.

A: Problem is LiveData cached your value, and when you comeback to screen you are getting the old value. Should google about SingleLiveData event for navigation purpose.
Here or here.