text:
Q: Upload form data fails with axios I have a form with multiple fileds, which one is a file input. I use axios to upload the file under a separate attribute:
axios.post(ENDPOINT,{
  form: formData,
  image: image
}, getAuthorizationHeader())

function getAuthorizationHeader() {
  return {
    headers: {
      'Authorization': //...,
      'Content-Type': undefined
    }
  };
}

formData is created like this:
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);

And the image is:

Under the network tab of the Chrome Dev tool, When I look at the request, it looks like this:

As you can see in the screenshot, the file is empty? The CONTENT-TYPE is application/json which is not what I  expected. I expected browser to detect the CONTENT-TYPE as multipart/form-data
What is wrong here?

A: First of all, image should be part of the formData:
formData.append('image', <stream-of-the-image>, 'test.png')

Secondly, formData should be the second parameter of axios.post:
axios.post(ENDPOINT, formData, getAuthorizationHeader())

Last but no least, you should merge formData.getHeaders():
function getAuthorizationHeader() {
   return {
       headers: Object.assign({
           'Authorization': //...,
           }, formData.getHeaders())
    };
}

Sample code for your reference: https://github.com/tylerlong/ringcentral-js-concise/blob/master/test/fax.spec.js


text:
Q: Dropdown menu for nav with this css So how do I make a dropdown menu using this css? Tried some tuts, but with this css I can't get any of those dropdowns working ;(.
CSS:
.main {
    list-style: none;
    margin: 0;
    margin-bottom: 100px;
    padding: 0px;
    height: 44px;
    text-decoration: none;
    background-color: #171a21;
    width: 100%;
    text-align: left;
    font-size: 18px;
    -webkit-box-shadow: 0px 0px 8px rgba(0, 6, 0, 0.45);
    -moz-box-shadow: 0px 0px 8px rgba(0, 6, 0, 0.45);
    box-shadow: 0px 0px 8px rgba(0, 6, 0, 0.45);
}
.main li {
    float: left;
    padding: 16px;
    margin: 0;
    line-height: 17px;
    height: 16px;
    margin-bottom: -6px;
    margin-left: 45px;
    list-style:none;
}
.main p {
    float: left;
    margin: 0;
    padding: 0;
    line-height: 17px;
    height: 44px;
    margin-bottom: -6px;
}
.main a {
    display: block;
    color: #b8b6b4;
    text-decoration: none;
    transition: all linear 0.15s;
}
.main a:hover  {
    display: block;
    color: white;
    text-decoration: none;
}

HTML:

Test

Test1

Test2

Test3

I'm just starting with html&css and making a site.
Thanks for any help ;).

A: Check this Fiddle:
The key is in those lines of CSS code:
.main li ul {
    display: none;
}
.main li:hover > ul {
        display: block;
}

Should be quite self explicative.

A: add these lines to your css file:
.main li ul {display: none;}
.main li:hover ul {display: block;}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Organizing files to prevent duplicity (but still automating backup) In an ideal world, we'd have a "Google File System" right now which would have journaling and even versioning built in, no need for folders and we'd just label files. I believe this is still far to happen.
My question here is: how to get as close to that world as possible, today?
Also, can we do it on a mac and keep dropbox ok with it?
Let me give an example... I was applying to many universities and had many files in common between them, including my own document IDs, most of which are files I already save in a dropbox folder. I wanted to group them within a folder for each application, since they all have different files as well.
The common way to do this today is copying the files. This is quite bad, because it will generate many duplicated files. Let's say I want to update one of them, I have to replicate everything, supposing I remember where is each copy. Copying files make sense when you do want differences among them, you want to make a new version. Not just to organize in folders.
For that there exists hardlinks and related stuff such as alias. Both are problematic. hardlinks break too easily, alias are too big. 2mb for a file that is actually 100kb. Also, when copying either into a pen drive, for instance, it copies the "link" instead of the actual file data and then it will break.
Alias also doesn't work with dropbox, which is my common way to backup most important files (I also have crashplan and time machine). While hardlinks will remove space quota from my account.
I actually think there's just no answer to this. Maybe mods will close as "too subjective", or whatever... But whatever happens will be a good enough answer to me! ;)


text:
Q: How to build and deploy a working unity app with MRTK v2 RC for HoloLens 1? The problem
To sum up, both Unity and Visual Studio 2017 builds the project, deploys the project, but once opening the app, nothing appears, not even a Unity splash screen. However making the bloom gesture on HoloLens proved that the app is "open" and closable, but that's as far as it gets.
What we tried
Our deployment target is a HoloLens 1 running the latest OS for said device (10.0.17763.380).
We went through the provided solution here:
MRTK (V2) Need to update Hololens?
As can be seen in below image:
NOTE: Images below shows Visual Studio 2019, but we tested both cases with Visual Studio 2017 AND Visual Studio 2019.

We installed the Windows 10 Insider Preview SDK (Pardon the Danish)

And tried to follow the solution provided here:
Cannot build with MRTK v2.0.0-RC1
Which seems to conflict with what the other answer to the problem seemed to be.

This solution-attempt however provided another error, saying that the deployment target (HoloLens 1) had to run OS 10.0.18326, which makes sense as this OS does not exist for this particular device as far as we know. We're as previously mentioned, running on the latest OS which is 10.0.17763.
As far as changing the C# language to 7.2, we had troubles dealing with that as all guides says to access the language from Build in the Solution Properties but we were unable to find this tab. Here's what happens when we attempt to press "Properties" after right-clicking the projectname.sln in the Visual Studio hierarchy:

However, we hoped we could change the language settings as in here:

but as you can see, there's no "Build" tab, and what we see looks a bit far from what we're suggested should be shown.
What we hoped for
A working HoloLens 1 app that can be opened up, like with the MRTK v2 Beta version.
What actually happens
As mentioned in the problem, the app gets built and deployed, but not only is it filled with errors, nothing appears on opening the built app.

Unity errors can be seen here:
Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Normal` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Quaternion Windows.Perception.People.JointPose::Orientation` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.People.JointPose::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.Spatial.SpatialRay::Origin` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityEyeGazeDataProvider::Update().
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference rewriter: Error: field `System.Numerics.Vector3 Windows.Perception.Spatial.SpatialRay::Direction` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityEyeGazeDataProvider::Update().
UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1064)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Reference Rewriter found some errors while running with command "--target=Temp\StagingArea\Data\Managed\Assembly-CSharp.dll" "--target=Temp\StagingArea\Data\Managed\Unity.Analytics.DataPrivacy.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Utilities.Gltf.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Services.TeleportSystem.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Services.SpatialAwarenessSystem.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Services.InputSystem.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Services.DiagnosticsSystem.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Services.BoundarySystem.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.SDK.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Extensions.PhotoCapture.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Extensions.Experimental.SpectatorView.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Extensions.Experimental.Sharing.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Extensions.Experimental.ScreenRecording.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Extensions.Experimental.MarkerDetection.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Core.Utilities.Async.dll" "--target=Temp\StagingArea\Data\Managed\Microsoft.MixedReality.Toolkit.Providers.WindowsVoiceInput.dll" "--target=Temp\StagingArea\Data\Managed\Unity.Subsystem.Registration.dll" "--target=Temp\StagingArea\Data\Managed\Unity.TextMeshPro.dll" "--target=Temp\StagingArea\Data\Managed\Unity.XR.ARExtensions.dll" "--target=Temp\StagingArea\Data\Managed\Unity.XR.WindowsMR.dll" "--target=Temp\StagingArea\Data\Managed\Unity.XR.FaceSubsystem.dll" "--target=Temp\StagingArea\Data\Managed\Unity.XR.ARFoundation.dll" "--target=Temp\StagingArea\Data\Managed\UnityEngine.Timeline.dll" "--target=Temp\StagingArea\Data\Managed\UnityEngine.SpatialTracking.dll" "--target=Temp\StagingArea\Data\Managed\Unity.Analytics.Tracker.dll" "--target=Temp\StagingArea\Data\Managed\Unity.Analytics.StandardEvents.dll" "--additionalreferences=Temp\StagingArea\Data\Managed,Temp\StagingArea\Data\Managed\Plugins\X86,Temp\StagingArea\Data\Managed\Plugins\X64,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\X64,Temp\StagingArea\Data\Managed\Plugins\ARM,Temp\StagingArea\Data\Managed\Plugins\X86,Temp\StagingArea\Data\Managed\Plugins\X64,Temp\StagingArea\Data\Managed\Plugins\X86,Temp\StagingArea\Data\Managed\Plugins\X64,Temp\StagingArea\Data\Managed\Plugins\X86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86,Temp\StagingArea\Data\Managed\Plugins\x86" "--platform=C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.18362.0\Facade\Windows.winmd" "--dbg=pdb" "--framework=Temp\StagingArea\Data\Managed" "--alt=Microsoft.Win32.SafeHandles,mscorlib;System,mscorlib;System,System;System,System.ComponentModel.Composition;System,System.Core;System.CodeDom.Compiler,System;System.Collections,mscorlib;System.Collections.Concurrent,mscorlib;System.Collections.Concurrent,System;System.Collections.Generic,mscorlib;System.Collections.Generic,System;System.Collections.Generic,System.Core;System.Collections.ObjectModel,mscorlib;System.Collections.ObjectModel,System;System.Collections.Specialized,System;System.ComponentModel,System;System.ComponentModel.DataAnnotations,System.ComponentModel.DataAnnotations;System.ComponentModel.DataAnnotations.Schema,System.ComponentModel.DataAnnotations;System.Data,System.Data;System.Data.Common,System.Data;System.Diagnostics,mscorlib;System.Diagnostics,System;System.Diagnostics.CodeAnalysis,mscorlib;System.Diagnostics.Contracts,mscorlib;System.Diagnostics.Tracing,mscorlib;System.Dynamic,System.Core;System.Globalization,mscorlib;System.IO,mscorlib;System.IO,System;System.IO,System.Core;System.IO.Compression,System;System.IO.Compression,System.IO.Compression.FileSystem;System.IO.IsolatedStorage,mscorlib;System.Linq,System.Core;System.Linq.Expressions,System.Core;System.Net,System;System.Net.NetworkInformation,System;System.Net.Security,System;System.Net.Sockets,System;System.Numerics,System.Numerics;System.Reflection,mscorlib;System.Reflection.Emit,mscorlib;System.Resources,mscorlib;System.Runtime,mscorlib;System.Runtime.CompilerServices,mscorlib;System.Runtime.CompilerServices,System.Core;System.Runtime.ExceptionServices,mscorlib;System.Runtime.InteropServices,mscorlib;System.Runtime.InteropServices,System;System.Runtime.InteropServices,System.Core;System.Runtime.InteropServices.ComTypes,mscorlib;System.Runtime.InteropServices.ComTypes,System;System.Runtime.InteropServices.WindowsRuntime,mscorlib;System.Runtime.Serialization,mscorlib;System.Runtime.Serialization,System.Runtime.Serialization;System.Runtime.Serialization.Json,System.Runtime.Serialization;System.Runtime.Versioning,mscorlib;System.Runtime.Versioning,System;System.Security,mscorlib;System.Security.Authentication,System;System.Security.Authentication.ExtendedProtection,System;System.Security.Claims,mscorlib;System.Security.Principal,mscorlib;System.Text,mscorlib;System.Text.RegularExpressions,System;System.Threading,mscorlib;System.Threading,System;System.Threading,System.Core;System.Threading.Tasks,mscorlib;System.Threading.Tasks,System.Core;System.Windows.Input,System;System.Xml,System.Runtime.Serialization;System.Xml,System.Xml;System.Xml.Linq,System.Xml.Linq;System.Xml.Schema,System.Xml;System.Xml.Serialization,System.Xml;<winmd>,Windows.winmd;<winmd>,Windows.AI.MachineLearning.MachineLearningContract.winmd;<winmd>,Windows.AI.MachineLearning.Preview.MachineLearningPreviewContract.winmd;<winmd>,Windows.ApplicationModel.Calls.Background.CallsBackgroundContract.winmd;<winmd>,Windows.ApplicationModel.Calls.CallsPhoneContract.winmd;<winmd>,Windows.ApplicationModel.Calls.CallsVoipContract.winmd;<winmd>,Windows.ApplicationModel.CommunicationBlocking.CommunicationBlockingContract.winmd;<winmd>,Windows.ApplicationModel.SocialInfo.SocialInfoContract.winmd;<winmd>,Windows.ApplicationModel.StartupTaskContract.winmd;<winmd>,Windows.Devices.Custom.CustomDeviceContract.winmd;<winmd>,Windows.Devices.DevicesLowLevelContract.winmd;<winmd>,Windows.Devices.Printers.PrintersContract.winmd;<winmd>,Windows.Devices.SmartCards.SmartCardBackgroundTriggerContract.winmd;<winmd>,Windows.Devices.SmartCards.SmartCardEmulatorContract.winmd;<winmd>,Windows.Foundation.FoundationContract.winmd;<winmd>,Windows.Foundation.UniversalApiContract.winmd;<winmd>,Windows.Gaming.XboxLive.StorageApiContract.winmd;<winmd>,Windows.Graphics.Printing3D.Printing3DContract.winmd;<winmd>,Windows.Networking.Connectivity.WwanContract.winmd;<winmd>,Windows.Networking.Sockets.ControlChannelTriggerContract.winmd;<winmd>,Windows.Services.Maps.GuidanceContract.winmd;<winmd>,Windows.Services.Maps.LocalSearchContract.winmd;<winmd>,Windows.Services.Store.StoreContract.winmd;<winmd>,Windows.Services.TargetedContent.TargetedContentContract.winmd;<winmd>,Windows.System.Profile.ProfileHardwareTokenContract.winmd;<winmd>,Windows.System.Profile.ProfileSharedModeContract.winmd;<winmd>,Windows.System.Profile.SystemManufacturers.SystemManufacturersContract.winmd;<winmd>,Windows.System.SystemManagementContract.winmd;<winmd>,Windows.UI.ViewManagement.ViewManagementViewScalingContract.winmd;<winmd>,Windows.UI.Xaml.Core.Direct.XamlDirectContract.winmd;<winmd>,Windows.ApplicationModel.Activation.ActivatedEventsContract.winmd;<winmd>,Windows.ApplicationModel.Activation.ActivationCameraSettingsContract.winmd;<winmd>,Windows.ApplicationModel.Activation.ContactActivatedEventsContract.winmd;<winmd>,Windows.ApplicationModel.Activation.WebUISearchActivatedEventsContract.winmd;<winmd>,Windows.ApplicationModel.Background.BackgroundAlarmApplicationContract.winmd;<winmd>,Windows.ApplicationModel.Calls.LockScreenCallContract.winmd;<winmd>,Windows.ApplicationModel.FullTrustAppContract.winmd;<winmd>,Windows.ApplicationModel.Preview.InkWorkspace.PreviewInkWorkspaceContract.winmd;<winmd>,Windows.ApplicationModel.Preview.Notes.PreviewNotesContract.winmd;<winmd>,Windows.ApplicationModel.Resources.Management.ResourceIndexerContract.winmd;<winmd>,Windows.ApplicationModel.Search.Core.SearchCoreContract.winmd;<winmd>,Windows.ApplicationModel.Search.SearchContract.winmd;<winmd>,Windows.ApplicationModel.Wallet.WalletContract.winmd;<winmd>,Windows.Devices.Portable.PortableDeviceContract.winmd;<winmd>,Windows.Devices.Printers.Extensions.ExtensionsContract.winmd;<winmd>,Windows.Devices.Scanners.ScannerDeviceContract.winmd;<winmd>,Windows.Devices.Sms.LegacySmsApiContract.winmd;<winmd>,Windows.Gaming.Input.GamingInputPreviewContract.winmd;<winmd>,Windows.Gaming.Preview.GamesEnumerationContract.winmd;<winmd>,Windows.Gaming.UI.GameChatOverlayContract.winmd;<winmd>,Windows.Gaming.UI.GamingUIProviderContract.winmd;<winmd>,Windows.Globalization.GlobalizationJapanesePhoneticAnalyzerContract.winmd;<winmd>,Windows.Management.Deployment.Preview.DeploymentPreviewContract.winmd;<winmd>,Windows.Management.Workplace.WorkplaceSettingsContract.winmd;<winmd>,Windows.Media.AppBroadcasting.AppBroadcastingContract.winmd;<winmd>,Windows.Media.AppRecording.AppRecordingContract.winmd;<winmd>,Windows.Media.Capture.AppBroadcastContract.winmd;<winmd>,Windows.Media.Capture.AppCaptureContract.winmd;<winmd>,Windows.Media.Capture.AppCaptureMetadataContract.winmd;<winmd>,Windows.Media.Capture.CameraCaptureUIContract.winmd;<winmd>,Windows.Media.Capture.GameBarContract.winmd;<winmd>,Windows.Media.Devices.CallControlContract.winmd;<winmd>,Windows.Media.MediaControlContract.winmd;<winmd>,Windows.Media.Playlists.PlaylistsContract.winmd;<winmd>,Windows.Media.Protection.ProtectionRenewalContract.winmd;<winmd>,Windows.Networking.NetworkOperators.LegacyNetworkOperatorsContract.winmd;<winmd>,Windows.Networking.XboxLive.XboxLiveSecureSocketsContract.winmd;<winmd>,Windows.Perception.Automation.Core.PerceptionAutomationCoreContract.winmd;<winmd>,Windows.Security.EnterpriseData.EnterpriseDataContract.winmd;<winmd>,Windows.Security.ExchangeActiveSyncProvisioning.EasContract.winmd;<winmd>,Windows.Storage.Provider.CloudFilesContract.winmd;<winmd>,Windows.System.Profile.ProfileRetailInfoContract.winmd;<winmd>,Windows.System.UserProfile.UserProfileContract.winmd;<winmd>,Windows.System.UserProfile.UserProfileLockScreenContract.winmd;<winmd>,Windows.UI.ApplicationSettings.ApplicationsSettingsContract.winmd;<winmd>,Windows.UI.Core.AnimationMetrics.AnimationMetricsContract.winmd;<winmd>,Windows.UI.Core.CoreWindowDialogsContract.winmd;<winmd>,Windows.UI.Shell.SecurityAppManagerContract.winmd;<winmd>,Windows.UI.Xaml.Hosting.HostingContract.winmd;<winmd>,Windows.Web.Http.Diagnostics.HttpDiagnosticsContract.winmd;<winmd>,Windows.Embedded.DeviceLockdown.DeviceLockdownContract.winmd;<winmd>,Windows.Networking.NetworkOperators.NetworkOperatorsFdnContract.winmd;<winmd>,Windows.Phone.PhoneContract.winmd;<winmd>,Windows.Phone.StartScreen.DualSimTileContract.winmd;<winmd>,Windows.UI.WebUI.Core.WebUICommandBarContract.winmd" "--ignore=System.IConvertible,mscorlib".
Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
Error: field `System.Numerics.Vector3 Windows.Perception.People.HandMeshVertex::Normal` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
Error: field `System.Numerics.Quaternion Windows.Perception.People.JointPose::Orientation` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
Error: field `System.Numerics.Vector3 Windows.Perception.People.JointPose::Position` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityArticulatedHand::UpdateControllerData(UnityEngine.XR.WSA.Input.InteractionSourceState).
Error: field `System.Numerics.Vector3 Windows.Perception.Spatial.SpatialRay::Origin` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityEyeGazeDataProvider::Update().
Error: field `System.Numerics.Vector3 Windows.Perception.Spatial.SpatialRay::Direction` doesn't exist in target framework. It is referenced from Microsoft.MixedReality.Toolkit.Providers.WindowsMixedReality.dll at System.Void Microsoft.MixedReality.Toolkit.WindowsMixedReality.Input.WindowsMixedRealityEyeGazeDataProvider::Update().

UnityEngine.Debug:LogError(Object)
PostProcessWinRT:RunReferenceRewriter() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:1062)
PostProcessWinRT:Process() (at C:/buildslave/unity/build/PlatformDependent/MetroPlayer/Extensions/Managed/PostProcessWinRT.cs:217)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Visual Studio 2017 errors can be seen here:
(pasting this exceeds the stackoverflow limit of 30000 characters, so I'm providing a pastebin instead)
https://pastebin.com/bx2QA2wL

A: Try to disable WSA Holographic Remoting Supported flag under Project Settings > Player > Universal Windows Platform settings > XR Settings.
With that option enabled, the scene is loaded successfully but is not shown on the screen.

A: The errors starting with "Reference Rewriter" are benign and can safely be ignored, (tracked by this bug).
It's possible that your SampleScene that you are building is actually empty, in other words has no content. It may be a good idea to try instead to build and deploy the HandInteractionAllExample scene, located at Assets\MixedRealityToolkit.Examples\Demos\HandTracking\Scenes\HandInteractionExamples.unity.
Otherwise, your steps are looking correct. Please also see this answer for instructions on how to build a UWP using MRTK v2.


text:
Q: Cycle through div content on click without Jquery I've got the following code which works as intended.  It shows the first content div, and then on button click, it rotates to content-2, content-3 etc.
    $(document).ready(function () {
        var divs = $('div[id^="content-"]').hide(),
            i = 0;

        function cycle() {
            divs.fadeOut(400).delay(400).eq(i).fadeIn(400);
            i = ++i % divs.length;
        };
        cycle()

        $('button').click(cycle);
        // click button to show next paragraph
    });

Unfortunately, the embedded content I'm using doesn't support external libraries, so I need to get this into raw Javascript.
Can anyone point me in the direct direction to do this please?

A: var counter=2;
function cycle(){
document.getElementsByClassName("content")[counter].style.opacity=0;
 counter++;
 if(counter==3){
 counter=0;
 }
 document.getElementsByClassName("content")[counter].style.opacity=1;
}

window.onload=function(){
document.getElementById("button").addEventListener("click",function(){cycle();});
cycle();
}

And then css
.content{
transition:all ease 3s;
opacity:0;
position:absolute;
top:0px;
left:0px;
}

A: You can try doing it by css. animate.css can be helpful.
An approach for something like what you are trying can be:

Animated DIV

JSFIDDLE


text:
Q: check array of objects if specific value is unique across all the array I have an array like this
const arr = [{ name: 'sara' }, { name: 'joe' }];

and i want to check if name is unique across the array so
const arr = [{ name: 'sara' }, { name: 'joe' }];//sara is unique //true
const arr = [{ name: 'sara' }, { name: 'sara' },{ name: 'joe' }];//sara is unique //false

i know there's array.some but it doesn't help in my situation
whats is the best way to achieve that using javascript thanks in advance

A: You could take a single loop and a Set for seen value.
isUnique is a function which takes a property name and returns a function for Array#every.

const
    isUnique = (key, s = new Set) => o => !s.has(o[key]) && s.add(o[key]),
    a = [{ name: 'sara' }, { name: 'joe' }],
    b = [{ name: 'sara' }, { name: 'sara' }, { name: 'joe' }];

console.log(a.every(isUnique('name'))); //  true
console.log(b.every(isUnique('name'))); // false

A: i have this implementation and it dose the job
const arr = [{ name: "salah" }, { name: "joe" }];

let bols = [];
arr.forEach((item1, i1) => {
  arr.forEach((item2, i2) => {
    if (i1 !== i2) {
      bols.push(item2.name === item1.name);
    }
  });
});

bols.some((item) => item === true);


text:
Q: Lazy-evaluate dependent-types (CRTP) I'd like the following piece of code to work:
template <typename Self>
struct foo_base {
    auto get(typename Self::type n) { return n; }
};

template <typename T>
struct foo : public foo_base<foo<T>> {
    using type = T;
};

The problem of course is that the base is instantiated first so you cannot refer to the derived member types. I'd need some kind of lazy-evaluation here.
I've tried to make the function template and have SFINAE on it, something like:
template <typename Self>
struct foo_base {
    template <typename T, typename = std::enable_if_t<std::is_same_v<T, typename Self::type>>>
    auto get(T n) { return n; }
};

but it doesn't seem to affect the order. Any ideas?
Edit:
Constraints of solution:

*

*I can't pass the type as a template parameter from the derived class.
Main reason is: The type is very complicated to construct, several
hundred characters. So can't do something like struct foo : foo_base<foo<T>, T> or variants.

*I need to constraint the function to that type, I
can't check inside the function. Maybe there are overloads in the
derived class.

A: You might create external traits, something like:
template <template T>
struct TypeT;

template <typename Self>
struct foo_base {
    auto get(typename TypeT<Self>::type n) { return n; }
};

template <typename T> struct foo;

template <template T>
struct TypeT<foo<T>> {
    using type = T; // Don't use foo<T>::type, so traits can be used with incomplete type
};

template <typename T>
struct foo : public foo_base<foo<T>> {
    using type = typename TypeT<foo>::type; // Or directly = T
};

Else you might indeed use SFINAE, but you must wait the type to be complete (when instantiating the method works in your case),
as for example:
template <typename Self>
struct foo_base
{
    template <typename T = Self>
    auto get(typename T::type n) { return n; }
};


text:
Q: C program to reverse a string with new lines I am having trouble fixing this function to reverse the words from a file, line by line. I cannot figure out how to handle the new lines. This is not an assignment for school, I am just trying to figure this out on my own and I have been at it for a while. I gather that the '\n' character is appended to the end of the word and the algorithm is not accounting for that, and I don't know how. Will you show me how to implement this properly?
void reverseWord (char* buffer, int size)
{
    char* start = buffer;

    // bounds
    char* temp = buffer;

    // Reversing the words
    while (*temp) {
        temp++;
        if(*temp == '\n'){
            temp++;
        }
        if (*temp == '\0') {
            reverse(start, temp - 1);
        }
        else if (*temp == ' ') {
            reverse(start, temp - 1);
            start = temp + 1;
        }
    }

    // Reverse the entire string
    reverse(buffer, temp - 1);
}

void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
    temp = *begin;
    *begin++ = *end;
    *end-- = temp;
    }
}

My input file is:
    this is line 1
    this is line 2
    this is line 3
    this is line 4
    this is line 5

My desired output is:
    5 line is this
    4 line is this
    3 line is this
    2 line is this
    1 line is this

My actual output is this:
    5
     line is this4
     line is this3
     line is this2
     line is this1

Thank you in advance.

A: First of all: if you post a question here in such a "simple" language like C, please provide a minimal reproducible example like @Yunnosch said. It will get you more people trying your code.
It is sufficient if it is as primitive as
int main() {
  char buffer[] =
    "this is line 1\n"
    "this is line 2\n"
    "this is line 3\n"
    "this is line 4\n"
    "this is line 5\n";
  printf("%s", buffer);
  reverseWord(buffer, strlen(buffer));
  printf("%s", buffer);
}

BTW, the output I got from your unmodified code is a bit different to what you posted:
5
 line is 4
this line is 3
this line is 2
this line is 1
this line is this

Well, now to your code.
Your while-loop will never evaluate if (*temp == '\0') to true because its condition will break the loop beforehand. But this is not the cause.
You can look at newlines like any other whitespace character. So I successfully tried this:
while (*temp) {
    temp++;
    if (isspace(*temp)) {
        reverse(start, temp - 1);
        start = temp + 1;
    }
}

You need to #include <ctype.h> for isspace().
It seems to work even for Windows-style newlines like \r\n. But you should investigate quite closely that the newlines are correct. You might like to learn to use a debugger for this.

A: I've ran your code and I've found some answers that will work for you:
1) If your input for reverseWord(..) is a single line, for example "this is line 1", then your output will be "1 line is this" which is perfect. What you can do now is just call that function for every line in your file.
2) If your input for reverseWord(..) is the entire text in a file, then in reverseWord(..), where you've said if(*temp =='\n')...
Just write the same thing that you've written for ' '.
This:
If (*temp == '\n') {
    reverse(start, temp-1);
    start = temp + 1;
}

ALSO!! Make sure that you get the sizes correctly. In your case, every line is 15 chars. (Including the '\n' and the '\0')
BTW, consider combining the '\n' with the ' ' and use an ||.


text:
Q: Angular: When using mat-select , Is there a way to not select the focused item when I press SPACE button? By looking at, https://v5.material.angular.io/components/select/overview
There are several keyboard interactions.

*

*Keyboard interaction

*DOWN_ARROW: Focus next option

*UP_ARROW: Focus previous option

*ENTER or SPACE: Select focused item

I am able to stop the whole interaction, BUT what I want is:
keep the all the keyboard interactions, except the SPACE one
Is there a way to do it?
Thank you.

A: Take account the Georg-un's answer
But if there a great great reason you always can "re-writte" the function.
Use a template reference variable in your select
<mat-select #select="matSelect">
   ...
</mat-select>

And you can use ViewChild to get the mat select and rewrite the function
  @ViewChild('select', { static: true }) select: any;

  ngOnInit() {
    this.select._handleKeydown = (event: KeyboardEvent) => {
      if (event.keyCode==SPACE)
        return
      if (!this.select.disabled) {
        this.select.panelOpen
          ? this.select._handleOpenKeydown(event)
          : this.select._handleClosedKeydown(event);
      }
    };
  }

NOTE: SPACE is defined in
import { SPACE} from '@angular/cdk/keycodes';

Update we can use a directive also
@Directive({
  selector: '[no-space]',
})
export class NoSpaceDirective {
  @Output('spacekeydown') spacekeydown: EventEmitter<any> =
    new EventEmitter<any>();

constructor(@Self() private select: MatSelect) {
    this.select._handleKeydown = (event: KeyboardEvent) => {
      if (event.keyCode == SPACE) {
          const active=this.select.panelOpen?
                 this.select.options.filter(x=>x.active)[0]|| null:
                 null
        this.spacekeydown.emit(active?active.value:null);
      } else {
        if (!this.select.disabled) {
          this.select.panelOpen
            ? (this.select as any)._handleOpenKeydown(event)
            : (this.select as any)._handleClosedKeydown(event);
        }
      }
    };
  }

}

And you use as
<mat-select no-space
     (spacekeydown)="doSomething($event)">
   ...
</mat-select>

As always, if we use as "selector" instead [no-space] mat-select
@Directive({
  selector: 'mat-select',
})
...

The directive is applied to all ours mat-select
see a stackblitz with the directive

A: If you look at the source code, you'll find that the keys are hardcoded. Therefore, you cannot easily override them.
Besides that, you probably should not override them anyways sice this would conflict with accessibility.

A: I think this is related and it might be of interest to someone who has an input field in mat-select and needs to disable the closing of mat-select when the user presses a space in the input. You just need to prevent default behavior on click and keydown:
<mat-select>
    <mat-option
        <input
            (click)="$event.stopPropagation()"
            (keydown)="$event.stopPropagation()">
        </input>
    </mat-option>
</mat-select>


text:
Q: Vagrant up doesn't work, doesn't return any errors (Windows 7) I'm working on a site running on the Roots WP stack and we're now planning on switching from xampp to vagrant. The issue is when I run "vagrant up", nothing happens. No errors, no output whatsoever, it just hangs until I exit the command. Running vagrant init creates a vagrantfile, but vagrant up does absolutely nothing.
I'm working on Windows 7 right now, on a work computer. I've used vagrant successfully in the past without issues.
    # -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "precise32"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  config.vm.box_url = "http://files.vagrantup.com/precise32.box"

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

A: I'd had the same issue (Windows7 Pro SP1, VirtualBox 5.1.26, vagrant 1.9.7).
I' have resolved this issue via downgrade vagrant to 1.9.6.

A: If Vagrant commands are hanging on Windows because they're communicating to VirtualBox, this may be caused by a permissions issue with VirtualBox. This is easy to fix. Starting VirtualBox as a normal user or as an administrator will prevent you from using it in the opposite way. Please keep in mind that when Vagrant interacts with VirtualBox, it will interact with it with the same access level as the console running Vagrant.
To fix this issue, completely shut down all VirtualBox machines and GUIs. Wait a few seconds. Then, launch VirtualBox only with the access level you wish to use..

A: Issue exists due to call to powershell within vagrant. This is still an issue with current (2.0.1) vagrant version.
Related link.
There are multiple solutions:

*

*Downgrade vagrant to 1.9.6

*Update powershell to higher version

A: I had a similar issue,too.
My environment is Vagrant 2.0.2 , virtualbox 5.2.6  and win 7.
And I finally solved it by updating powershell 2 to powershell 4.


text:
Q: Persisting references non-root entities outside of aggregate All material on DDD specify this as a strict no no, but i recently came across a scenario that makes a compelling case for thinking otherwise. Imagine 2 aggregate roots Template and Document where Template --> (1:n) TemplateParam, Document --> (1:n) ParamValue and finally the 2 roots have a reference Document --> (n:1) Template.
Given aggregate root constraint ParamValue should not persist a reference to TemplateParam, only it can refer it through a transient reference obtained through Template aggregate root. Now if i want to have a rule enforce like "each ParamValue of document should refer to a valid TemplateParam belonging to the Template referred to by its owning document". Ideally at db level i would let ParamValue have FK to the TemplateValue, how to do it in DDD paradigm ??

A: Aggregate Roots are there for a reason. They act as a single entry point to a group of related entities in order to enforce their invariants. They make sure that no external object can mess up with these entities and potentially violate their invariants.
However, in your particular scenario, even if ParamValue holds a direct reference to TemplateParam, TemplateParam is not at risk of being modified by an entity in the Document aggregate. The value associated to a parameter for a given document will be modified, but not the parameter per say.
To make sure this is the case, you can make TemplateParam an immutable value object :
(in C#)
public class TemplateParam
{
    private readonly string name;

    public TemplateParam(string name)
    {
        this.name = name;
    }

    public string Name
    {
        get { return name; }
    }
}

Thus you can encapsulate TemplateParam in ParamValue with no risk that one of the Template aggregate's invariants will be broken due to the "externalization" of TemplateParam.
Technically speaking that may be a violation of DDD's aggregate root constraint, but I don't believe it is one in spirit as long as you keep the "externalized" entity immutable and don't modify the object graph it originally belongs to.

A: One way you could go about this is to have the Template entity have a factory method for creating Document instances, which can enforce the constraint that all ParamValue instances are associated with appropriate TemplateParam. If the document is immutable then you're done. Otherwise, you can apply updates to the document through its associated template. This template can be referenced directly from the document or with an ID in which case the encapsulating application service would retrieve it when required for an operation. Direct references between ARs are not a strict violation of DDD, in fact the blue book specifies that are the only things that can be referenced by external ARs. It has become a constraint as of late because of other considerations such as consistency, performance, ORM mapping, etc. Take a look at this series of articles on effective aggregate design for some inspiration.


text:
Q: Prove if $\{ a_n \}$ converges and $\{ b_n \}$ is bounded, then $\{ a_n \cdot b_n \}$ is convergent I need to prove it and say what condition is needed for $\{ a_n\}$ to converge to $\{ a_n \cdot b_n \}$
My attempt

suppose $\{ a_n \}$ is such that $a_n = 1 + \frac{1}{n}$ and $b_n =
> \Bigg\{ \begin{matrix} 1, n \,\, is \,\, even\\
> -1, n \,\, is \,\, odd\\ \end{matrix} $
We have that $a_n \rightarrow 1$, $b_n$ is bounded, but $\{ a_n \cdot
> b_n \}$ does not converge, since $a_n \cdot b_n = \Bigg\{
> \begin{matrix} 1 + \frac{1}{n}, n \,\, is \,\, even\\
> -1 -\frac{1}{n}, n \,\, is \,\, odd\\ \end{matrix} $
If $a_n \rightarrow 0$ and $b_n$ is bounded. Then $\{ a_n \cdot b_n
> \}$  converges and $\lim_{n \to \infty} \{ a_n \cdot b_n \}=0$
$\blacksquare$

Is this an appropriate prove? or how do I complete it?

A: $\{a_n\}$ and $\{b_n \}$ two two sequence such that
$\{a_n\}\to 0 $ and $\{b_n\}$ is bounded, then $\{a_n b_n \}\to 0 $
Proof : There exists $K>0 $ such that $|b_n|<K $ for all $n\in \Bbb{N}$.
Again, given any $\epsilon >0$ there exists $N\in \mathbb{N}$ such that $\forall n>N$
$|a_n|<\frac{\epsilon }{K} $
Proof : \begin{align} |a_n b_n -0 |&= |a_n| |b_n|<\frac{\epsilon }{K}•K =\epsilon \space \space \forall n>N\end{align}
Hence, $\{a_n b_n \}\to 0 $
If $\{a_n\} $ converges to $a\neq 0$ , then the sequence $\{a_n b_n \}$ may not converge.
Example : $(a_n )=\{1,1,1,...\}$ and $b_n=\{(-1)^n\}$
Then $\{a_n\}$ is convergent and $\{b_n\}$ is bounded but $\{a_n b_n\}=\{(-1)^n\}$ is not convergent.


text:
Q: Hadoop is sometimes too slow (stuck at 100%) I set up a cluster of ten machines in which I installed CDH4 (yarn).
I run the nameNode, the resourceManger and the historyServer in the same node, and the client in another node.
On the rest of machines, I turned on dataNode and NodeManager.
I launched my application on a 100GBytes file, it worked at first and it was relatively quick, but now it gets really really slow at the end of the map (around 90% 100% it takes 30 minutes).
I don't know if the problem comes from the way I coded the program or the way I configured cloudera CDH4.
The problem is that it works sometimes but does not work other times although I didn't change anything.

A: I found out why it took so much time at the end, in fact I thought that the command hadoop fs -expunge allows me to empty the trash but it doesn't, so when Hadoop tried to write in HDFS files the result it was very slow because there was a very little space left.


text:
Q: unequal sample size and linear regression Can i use simple linear regression when there is unequal sample sizes for the dependent and independent variable? Will this be a problem?
That is;
 y=a+bx+epsilon,
where y and x have unequal sample sizes.

A: If you have a data point that lacks either a value for the dependent or the independent variable, the data point does not carry any meaningful information and hence it is pretty much useless.
For example, assume you are investigating the influence of education on income and in your sample you have a person who earns $100,000 per year, but you don't know his education level. Such information does not tell you anything about the relation between education and income, simply because you have no idea what his education level is.
Therefore you can only meaningfully use observations for which both the dependent and independent values are known.


text:
Q: JQuery extend transforms string in array I'm creating a jquery plugin and extending default options, like this:
$.fn.myplugin = function(options) {

    var defaults = {
        myOption: true
    }

    var options = $.extend({}, defaults, options); // <---- this line is important

    /* stuff */
}

if I call $('selector').myplugin('999.999') the 'important' line above transforms string '999.999' to an array, and options holds {'9', '9', '9', '.', '9', '9', '9' }.
What should I do to keep options as a string '999.999'?
Another approach, same problem:
var defaults = { some: 'thing' };
var options = 'foo';

// all code below returns an Object { 0: "f", 1: "o", 2: "o", some: "thing" }
$.extend(false, {}, defaults, options)
$.extend(true, {}, defaults, options)
$.extend(defaults, options)

// The expected is Object { 0: "foo", some: "thing" }

Some help?

A: Just use...
.join("")

At the end of the array to convert it into a string.

<script>
  document.write(['9', '9', '9', '.', '9', '9', '9'].join(""));
</script>


text:
Q: Cannot connect to a local web service from my android emulator I am having a problem connecting from the emulator to a local web server. I can connect to it outside the emulator.
Emulator gets:
org.apache.http.conn.httphostconnectexception connection to http //localhost;808 refused
protected String doInBackground(String... args) {
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products,
                    "GET", params);
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
             System.out.println("Got an IOException: " + e.getMessage());
            // TODO: handle exception
        }
        return null;
    }

A: Try connecting to http://10.0.2.2:8080 instead.
The 10.0.2.2 IP address is special within the emulator and will transparently connect to your host development machine's localhost (127.0.0.1).
If you use localhost or 127.0.0.1 within the emulator, this will refer to the internal emulated loopback interface instead. This is useful if you have another program running in the emulator, acting as a TCP or UDP server at the same port. However, in your specific case, you really want to get 'out of the sandbox'.
The official documentation has more information (and examples).

A: You are probably using the wrong network address to access the web service.
http://localhost goes to the device in an Android emulator. Use 10.0.2.2 to access your host loopback interface (i.e., 127.0.0.1 on your development machine).
See Android Emulator Networking
EDIT: Your exception says http //localhost;808, but your hostname should be http //localhost:808 with a : instead of ;.


text:
Q: Bootstrap 3: Tooltip image just after the input field? I would like to get that question sign image just after the email address input field and align right to the center of the input field?

    {{translation.TELEPHONE}}:

        <input type="text" class="form-control"  ng-model="jdeRetailer.phone" placeholder="Telephone">

    {{translation.EMAIL}}:

        <input type="text" class="form-control"  ng-model="jdeRetailer.email" placeholder="Email address">

A: The form-control class of bootstrap has width:100% property. Better way set glyphicon in absolute position with right 0 position.
Just add this property to span:
position: absolute;
right: 20px;
top: 15px;

and position:relative; to parent of span.
Here is code.

A: You can do it like this by adding style to input to have display:inline

    {{translation.TELEPHONE}}:

        <input type="text" class="form-control"  ng-model="jdeRetailer.phone" placeholder="Telephone">

    {{translation.EMAIL}}:

        <input type="text" class="form-control"  ng-model="jdeRetailer.email" placeholder="Email address" style="display:inline">
        ?


text:
Q: Exception when changing edittext font size this segment of code make an exception
I dont know exxactly where is the problem  ..
  Spinner dropdown = (Spinner)findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
    dropdown.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

            etFName.setTextSize(TypedValue.COMPLEX_UNIT_SP,Integer.parseInt(items[position]));

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

here is my logcat :
 12-07 23:04:35.047: E/AndroidRuntime(7505): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.invitationcard/com.example.invitationcard.Graduation}: java.lang.NullPointerException
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.os.Handler.dispatchMessage(Handler.java:99)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.os.Looper.loop(Looper.java:137)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread.main(ActivityThread.java:4424)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at java.lang.reflect.Method.invokeNative(Native Method)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at java.lang.reflect.Method.invoke(Method.java:511)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at dalvik.system.NativeStart.main(Native Method)
 12-07 23:04:35.047: E/AndroidRuntime(7505): Caused by: java.lang.NullPointerException
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at com.example.invitationcard.Graduation.onCreate(Graduation.java:46)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.Activity.performCreate(Activity.java:4492)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
 12-07 23:04:35.047: E/AndroidRuntime(7505):    ... 11 more

there is anyone know whats my errror ??

A: The first thing Ive noticed is the edittext
etFName.setTextSize(TypedValue.COMPLEX_UNIT_SP,Integer.parseInt(items[position]));

You are parsing an object to an int. Would you have a variable inside items called textSize?
etFName.setTextSize(TypedValue.COMPLEX_UNIT_SP,Integer.parseInt(items[position].textSize));

Secondly that error you are receiving has nothing to do with the code you provided.
You are trying to pass something, create a new activity or create a view somewhere that is null.
You will have to provide more code if you want deeper explanation.
New information:
The issue is here:
Intent intent = new Intent(context, g1.class);
                        startActivity(intent);
      Intent intent1 = new Intent(context , g1.class);
      intent1.putExtra("fname" , et.getText().toString());
      startActivity(intent1);

This makes no sense. You are creating 2 intents and starting both. Why do you want to do that?
When the first activity is opened it will lose that context.
Remove:
Intent intent = new Intent(context, g1.class);
                        startActivity(intent);

Please make sure you are using proper debugging tools provided by the IDE. That bug should be easily traceable.

A: this is my .java
public class Graduation extends ActionBarActivity {

ImageView imageView ;
private Spinner spinner;
public static final String[]items = {"8", "12", "16", "18", "20", "24", "28"};

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

    Spinner dropdown = (Spinner)findViewById(R.id.spinner);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
    dropdown.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

            et.setTextSize(TypedValue.COMPLEX_UNIT_SP,Integer.parseInt(items[position]));

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    addListenerOnImageg1() ;

    et = (EditText) findViewById(R.id.et);

}

public void addListenerOnImageg1() {

    final Context context = this;

    imageView = (ImageView) findViewById(R.id.g1);

    imageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, g1.class);
                        startActivity(intent);
      Intent intent1 = new Intent(context , g1.class);
      intent1.putExtra("fname" , et.getText().toString());
      startActivity(intent1);

        }

    }); }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
this is my xml file :
 <?xml version="1.0" encoding="utf-8"?>
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

 <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/backf"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter your Text Here  : "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10" >

    <requestFocus />
</EditText>
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="choose your frame : "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView
    android:id="@+id/g1"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g1" />
 <ImageView
    android:id="@+id/g2"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g2" />
  <ImageView
    android:id="@+id/g3"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g3" />
   <ImageView
    android:id="@+id/g4"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g4" />
    <ImageView
    android:id="@+id/g5"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g5" />
    <ImageView
    android:id="@+id/g6"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g6" />
    <ImageView
    android:id="@+id/g7"
    android:layout_width="122dp"
    android:layout_height="111dp"
    android:clickable="true"
    android:onClick="onClick"
    android:src="@drawable/g7" />

 </LinearLayout>
 </ScrollView>

when i put the spinner code as a comment the code work correctly ,, so the exception is in the spinner code


text:
Q: Definition of $\exp(x)$ I've been thought at school that the definition of $\exp(x)$ is the unique function satisfying $\exp'(x)=\exp(x)$ and $\exp(0)=1$. But I've never found this definition somewhere else. On Wikipedia there are multiple definitions which are :
$$\exp(x)=\sum_{k=0}^{\infty}\frac{x^k}{k!}$$
$$\text{The solution $y$ to the equation }x=\int_1^y\frac{1}tdt$$
$$\text{and } \exp(x)=\lim_{n\to+\infty}\left(1+\frac{x}{n}\right)^n$$
As I know, something can have only one definition, but can have multiply ways to define it and properties. So which one is the real definition of the exponential function?

A: The following are equivalent definitions for $\exp(x)$.
\begin{align}
1. & f(x) = \sum_{k=0}^{\infty} \dfrac{x^k}{k!}\\
2. & \dfrac{d f(x)}{dx} = f(x) \text{  with } f(0) = 1\\
3. & f(x) = \lim_{n \to \infty} \left(1+\dfrac{x}n\right)^n\\
4. & f(x+y) = f(x) \cdot f(y) \text{ with }f(x) >0 \text{ being continuous at one point and } f(1) = e
\end{align}
If you start with any one, you can derive/prove the others.
EDIT
The important thing is that you can start with anyone and derive the others as property. If a statement $A$ implies a statement $B$ and vice-versa, both are equivalent statements. We may, hence, use any one of them as a definition.
For instance, if you choose $(1)$ to define $\exp(x)$ as $\exp(x) = \displaystyle \sum_{k=0}^{\infty} \dfrac{x^k}{k!}$, the rest from $(2)$ to $(4)$ become properties.

A: To address the comment below your question, and your assertion that something must have "one real" definition:
"Equivalent definitions" simply mean that there are many ways to define/describe $e^x$, all of which define/describe the unique function: $f(x) = e^x$. When definitions are equivalent, we can choose any one of them to derive the others. So we are free to choose which, among equivalent defintions, will serve our purpose best, depending on when and how we need to use it.
That is true of many mathematical entities: e.g., there is no *ONE* true definition of $\pi$: there are many ways to define the unique number $\pi$.

A: Another Wikipedia article of relevance is Characterizations of the exponential function.
Which characterization is most appropriate to take to be the definition depends on the context.


text:
Q: custom post template not getting picked for posts with Unicode title We have a custom post type called support.
And we have created a template for it as single-support.php.
The problem is when we crate a new post with English slug it works fine:
eg. www.mywebsite.com/support/a-new-article/
But when we create a new page with a Unicode title(slug), the template hierarchy is not working like the English slug:
eg. www.mywebsite.com/support/සාමන්ය-පිටුවක්/


text:
Q: Handle onClick event with Databinding and MVVM I want to set an onClickListener on an ImageView using Databinding and control it from ViewModel(MVVM).
In the xml layout all things that I've implemented with Databinding works. But onClick event is not working.
I get this error:

error:cannot find symbol

XML:
<data>
    <variable
        name="photo"
        type="learn.app.papewall.model.Photo" />
    <variable
        name="viewModelDetail"
        type="learn.app.papewall.view.detail.DetailViewModel" />
</data>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.detail.DetailFragment">

    <ImageView android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
        android:scaleType="center"
        android:onClick="@{viewModelDetail.save()}"
        app:imageUrl="@{photo.urls.regular}"/>
    <TextView
        android:id="@+id/detailUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/padding_large"
        android:textColor="#000"
        android:layout_alignBottom="@+id/image"
        android:text="@{photo.user.name}"/>
</RelativeLayout>

ViewModel
fun save(photo: Photo){
    setWallpaper(photo, false)
}

Fragment:
viewModel.save(photoObj!!)

I don't know what is this error. I tried solutions from stackoverflow but none of them solved my  problem.
I want to set onClick Listener using Databinding and MVVM any solutions would be appreciate I don't know what is the problem.

A: You could also try modifying your onClickListener as follows:
android:onClick="@{() -> viewModelDetail.save(photo)}"

A: you need to pass the photo to the save function, like that
android:onClick="@{() -> viewModelDetail.save(photo)}"


text:
Q: Awk, or similar command, to get the last column and do some action with it in Bash I'm writing a script to grab the last update/patch date on a few hundred servers. Lacking another tool due to various reasons, I've decided to write a script. At the moment I'm using the following command:
sudo yum history | grep [0-9] | grep -E 'Update|Install|U|I' | awk 'NR==1'

Which gives me the first line with an action on it. But it only gives me the first line, I toyed with the idea of grabbing the first 5 rows but that may not be applicable to every situation.
sudo yum history | grep [0-9] | grep -E 'Update|Install|U|I' | awk 'NR>=1&&NR<=5'

So I would like to check the last column or two and if more than x packages have been updated or installed then to grab that row.
Generically speaking the output of yum history is:
18 | first last <username>      | 2018-08-30 19:41 | E, I, U        |   43 ss
17 | first last <username>      | 2018-07-10 15:28 | E, I, U        |  230 EE
16 | first last <username>      | 2018-04-25 20:08 | E, I, U        |   44 ss
15 | first last <username>      | 2018-01-30 20:57 | E, I, O, U     |  108 EE
14 | first last <username>      | 2018-01-30 20:39 | Install        |    4

The issue I'm running into is the last two columns can differ in their column position and the last column may just be numeric or it may contain letters or special characters. I want to ignore any last column that has any character that is not numeric, and to evaluate whether the last column has more than 20 packages installed or updated. If the last column is more than 20 packages to then grab that row and only that row.

A: Use a regular expression, matching for the number in the last column. To print all history records with >=20 alterations:
sudo yum history | \
    perl -ne '/\| *(\d+)[^\|]*$/ and $1>=20 and print($_)'

Of - if you only want the time stamp from matching history records:
sudo yum history | \
    perl -ne '
        @col=split(/\|/);
        $col[4]=~/^ *(\d+)/ and $1>=20 and print($col[2],"\n")'

A: use awk:
sudo yum history | awk -F ' *\\| *' '$4 ~ /\<(Install|Update|U|I)\>/ && $5 > 20'


text:
Q: SQL-запрос для обновления текущих значений Начну с того, что в SQL и вообще таблицах я полный валенок. Нужен вроде бы простой совет как обновить текущие значения в строках таблицы. Структура следующая: есть таблица strings в ней следующая структура полей: id, locale, value.
Например:
'text1', 'ru', 'text 1'
'text1', 'en', 'text 1'

Мне нужен пример SQL запроса, в котором будет поиск по id с учетом locale и замена текущего value на мое значение - так же этот запрос нужен быть рассчитан на одновременную замену в нескольких значениях.

A: Обновление записи по id и locale
UPDATE strings SET value = 'yourvalue'
WHERE id='yourId' and locale = 'yourlocale'

P.s. очень странно, что у тебя id является строкой.


text:
Q: Why could a function works fine in main() but not inside a class? I have to move a function which call from my main to a class constructor. However while the function works fine in the main, when moved to the class constructor it generates an error on compile time:
cannot convert 'Tile**' to 'Tile*' for argument '1' to 'bool set_tiles(Tile*)'
In function 'void moveObjects(Tile**)'

I don't understand how this could happen since both functions are called identiacally. This is my main() and my class constructor:
int main(){
    Tile *tiles[ TOTAL_TILES ];
    if( set_tiles( tiles ) == false ) return 1; // SETEAR LOS TILES
    currentState = new OverWorld();
    update_game(tiles);
}

OverWorld::OverWorld()
{
    Tile *tiles[ TOTAL_TILES ];
    if( set_tiles( tiles ) == false ) exit(1); // ERROR
}

bool set_tiles( Tile *tiles[] ){
}

void update_game(Tile *tiles[]){
    moveObjects(tiles);
}

Also I noticed the error mentions another function, I'm not sure how it's related to this but I'll copy it's code:
What am I doing wrong?


text:
Q: i need to redirect multiple domains to the same static web URL in azure in case of a full site down....can anyone advise first off i want to thank you all for the amazing information on here, i have learnt so much!
so the issue i have is i need to create a static web page for when we have a whole site down, as we host general maintenance pages on word press.i need to have multiple domains redirected to this web site when this issue occurs. the way i was thinking of doing it , is create a storage account then add to a static website to that storage container. then place the web page in a CDN adding multiple domains. then adding a cname record in DNS pointing to that endpoint? would this work?
many thanks in advance

A: Unfortunately map multiple custom domains directly to storage accounts website is not currently supported
https://feedback.azure.com/forums/217298-storage/suggestions/955579-enable-multiple-custom-domains-for-storage-account
You can integrate a Storage Account static website with Azure CDN and map a custom domains.
https://learn.microsoft.com/en-us/azure/cdn/cdn-map-content-to-custom-domain?tabs=azure-dns%2Cazure-portal%2Cazure-portal-cleanup


text:
Q: Delay turn ON circuit using 555 I want to set a delay of around 5s between power supply turning ON and my circuit getting power.

Here is the circuit I have come up with:

Datasheet of mosfet
I am using a 555 timer to set the startup delay and N-channel mosfet to supply power to the load. Most of the through hole mosfets have Rds minimum at around 10 V. Luckily I had 12V supply readily available so I am using 12 V to switch the 5V line as shown above. P4 is input and P3 is load.
Is my circuit correct?
Besides initial turn ON delay, I want the circuit to reset when power is disconnected (in half a min or so. if it happens within 1-2 seconds, it will be even better). To achieve this, I have put R7 (100K) discharge resistor on the capacitor which will discharge it and get the circuit in working state again. Is there a better way to do this?

A: The circuit looks good.
If you want faster reset of the circuit move R7 to between 12V and GND and reduce its resistance... when the 12V is turned off C3 will discharge through D1 and the new R7


text:
Q: Java - War Game - Getting an object from an array I'm new to Java and I am having trouble wrapping my mind around one of the concepts.
The assignment I am currently working on is the card game War. The current instructions is for me to remove a random card from a a deck of cards.
I have created an array, but it is an array of class Card. The class creates the card by basically adding an int and a String together. I then created the array from that class. In my mind, I neither have an int or a String in my array, is that correct?
Now I need to remove one of the random cards from the deck and give it to a player. This is where I am getting lost. I would think I can just use Random to remove a random card, but I always seem to get an error.
I'm not asking for you to do the assignment for me, but if you would please point me in the right direction and possibly correct me if I am confused.
Current Class I am working on:
import java.util.Random;
import java.util.*;

public class War3
{

    Random ran = new Random();

    public FullDeck randomCard()
    {
        ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);

        int index = ran.nextInt(randCard.size());
        FullDeck x = randCard.remove(index);
        return x;
    }

    public void display()
    {
         System.out.println("Your card is" + randomCard());

    }
}

Entire project for clarification Java - War Game - Gist
Many thanks in advance.

A: Two issues that I see:

*

*You're creating an ArrayList that can hold a reference to 52 instances of the FullDeck class, but you're not adding anything to it. You need to do something like randCard.add(new FullDeck()) 52 times/in a loop**. Then likely you'll want to "shuffle" the deck, see this question for how to do that.

*You're naming is a little weird...the FullDeck class in actuality seems like it should be renamed to just Card, and the randCard variable should be renamed to something like fullDeck...after you've added 52 Cards.

**EDIT: actually, the generation of a deck of cards will be more complicated to make sure you don't have any duplicate cards.

A: ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
This creates an ArrayList. You do not need to specify the number 52, since ArrayLists grow dynamically, as opposed to Arrays. The call is similar to
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> ();, the difference being that the constructor you used sets the initial capacity of the ArrayList to 52. That in no way restricts the size of the ArrayList though.
Anyway, you are creating a new, empty ArrayList. Then you want the size, but since you didn't put anything into the list, it is still empty, to the size is zero. You then try to call ran.nextInt(0)... nextInt(int n) expects a number greater than zero. From the javadoc:
public int nextInt(int n) {
 if (n <= 0)
  throw new IllegalArgumentException("n must be positive");


text:
Q: NativeScript Service exited due to Trace/BPT trap: 5 I'm trying to run the Groceries app for the first time, and it seems to be exiting with the system.log message below. Can anyone help?
I've tried both the angular-start and master branch. Same error.
tns 2.2.1
Simulator Version 10.0 (SimulatorApp-700.5.3
Xcode Version 8.0 (8A218a)
Sep 13 19:05:44 CHRISTOPHERs-MacBook-Pro com.apple.CoreSimulator.SimDevice.499CBAD2-C487-495B-A343-DFB9A16D127D.launchd_sim[25503] (UIKitApplication:org.nativescript.groceries[0x5f5][25953]): Service exited due to Trace/BPT trap: 5

A: Same thing for me since upgrading to ios 10, xcode 8.  Anyway, I went to Simulator > Hardware > Device > Manage Devices.  Then I installed ios 9 and it works again. Need to figure out problem with 10, but at least in 9 I got some error messages that helped me get it up again.

A: There is some discussion here:
https://github.com/j3k0/cordova-plugin-purchase/issues/501
One suggestion is to add this to the www/index.html file:
<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">

I have a Cordova/Ionic app that runs fine on iOS 8 and 9 and throws the same error (also uses Angular).
Maybe something else security related is blocking something?
Please share if you find a solution.


text:
Q: Is it possible to observe changes in presentingViewController? Is there any equivalent in Swift to RACObserve(self, presentingViewController)?
Or any other why to imitate this behaviour?

*

*My issue is that I want to be notified whenever a view controller is "hidden" by another view controller. In objc what I'd do is to check if self.presentingViewController is nil.

*Note that in this scenario there's no knowledge of which view controller is presented, so it's impossible to notify from within its viewDidAppear/viewDidDisappear.

A: As I understand your question: you need to to know which view controller is presented now and you need notification inviewDidAppear/viewDidDisappear.
So we can get this in several way.
The simple way is:

*

*Get information of which is the top ViewController right now.

2.Call this method in your viewDidAppear/viewDidDisappear
Like this :
Get Which is The Top ViewController
func getTopViewController() -> UIViewController? {

        if var topVC = UIApplication.shared.keyWindow?.rootViewController {

            while let presentedViewController = topVC.presentedViewController {
                topVC = presentedViewController
                return topVC
            }
            return topVC
        }

        return nil
    }

Call in viewDidAppear:
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        if let top = getTopViewController() {
            print("topView Controller name \(top.title)")
            top.view.backgroundColor = .red
        }
    }

Hope it will help you !


text:
Q: Parameter is not passing to controller in Laravel Let's take an example.
https://www.example.net/xyz?page=2
Route File
Route::get('/xyz', 'controller@getpages');

Controller
public function getpages(Request $request) {
 dd($request->all());
}

Showing result as
array:1 [▼
 "/xyz" => null
]

instead of
 array:1 [▼
  "page" => "2"
  ]

A: try:
public function getpages(Request $request) {
 print_r($request->page);
}

Also make sure you use : use Illuminate\Http\Request;

A: try
$query = $request->query();

$page = $request->query('page');

In your code there is a mistake. you missed $ symbol
public function getpages(Request $request) {
 dd($request->all());
}

A: use Illuminate\Http\Request;
use App\Http\Requests;

public function getpages(Request $request) {
  $request = $request->only('page');
  dd($request);
}

There is no array. just only one parameter "$page"

A: Try below code:
This is user register controller:
use Illuminate\Http\Request;

use App\User;

public function register(Request $request){

        $data = $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required'
        ]);

        $data['password'] = app('hash')->make($data['password']);

        User::create($data);

        $credentials = $request->only('email', 'password');

        if ($token = $this->guard()->attempt($credentials)) {

            return $this->respondWithToken($token);
        }

        return response()->json(['error' => 'Unauthorized'], 401);

     }

A: The Problem was in .htaccess file, so i retrieve the old .htaccess and putted it.


text:
Q: Workflow In Production Code Hi I would like to know how many of you have used Workflow in your production environment and Was it good idea? I mean we can create the same thing using DB and scheduler service

A: We use WF in our production enviorments. We have 6 different workflows that can be run. These split into 3 statemachine and 3 sequences. I would use it again in some circumstances, but I would not in others. I would claim that the statemachine part of the workflow was tacked on the end quickly, I'm not sure it a core part of the workflow all the way through design.
I would use workflow again for short running processes like quotes or transforming things before sending them to supliers that kind of thing.
I would not want to do it again for a long running statemachine - mainly because there is not a built in WF upgrade process so we ended up writing our own. There are also a lot of concepts to get your head around (affectionalty known as gypsy curses with in our development team).
I would also be slightly concerned about performance: our App server is currently running flat out (ok I am restarting 8000 workflows at the moment). This is especially a problem if you integrate it directly into WCF using the (.NET 3.5) send and recieve activities - there are some properly crazy config settings you have to set to allow it run multiple workflows at once.
Anyway, as I said: it is useful, I would use it again, but not for another statemachine.
Also see Please confirm: Is Windows Workflow Foundation a good horse to be backing right now?

A: We use Sharepoint, which uses WF for its workflows. It works pretty well and is fairly easy to customize. If you need an advanced workflow, WF can support it but it will take some training to learn the ins and outs.
You could roll your own workflow, but why reinvent the wheel? WF is built into the .NET 3.0+ framework and is pretty robust, so you might as well take advantage of it.

A: Most people say all the good things about Workflows but I have observed that they introduce unnecessary code complexity and maintenance problems. They are suitable for a particular class of problems. other then that they need a lot of code plumbing and maintenance nightmares.


text:
Q: facing issue with nginx.conf for my php application I am trying to configure http server for my php application in nginx but getting this error when i tring to start the service if someone can help it would be really great.
follow error i am getting when i use command to start the service
-- Subject: Unit nginx-rtmp.service has begun reloading its configuration
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit nginx-rtmp.service has begun reloading its configuration
Nov 22 15:54:43 chandu nginx[19339]: nginx: [emerg] pattern "^(.+\.php)(/.*)chr(36)" must have 2 captures in /opt/nginx-rtmp/conf/nginx.conf:38
Nov 22 15:54:43 chandu systemd[1]: nginx-rtmp.service: Control process exited, code=exited status=1
Nov 22 15:54:43 chandu systemd[1]: Reload failed for Nginx RTMP.
-- Subject: Unit nginx-rtmp.service has finished reloading its configuration
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit nginx-rtmp.service has finished reloading its configuration
--
-- The result is failed.
lines 1256-1284/1284 (END)

My nginx.conf file
following is my nginx.conf file  fastcgi_split_path_info ^(.+.php)(/.*)chr(36); is at line 38 where error points to above.
user nginx;
worker_processes 2;
pid /run/nginx-rtmp.pid;
error_log logs/error.log;

events {
    worker_connections 1024;
}

rtmp {
    server {
        listen 1935;
    }
}

http {
    access_log logs/access.log;
    include mime.types;

    server {
        listen 26765;
        location /stat {
            rtmp_stat all;
        }
    }

    server {
        listen 80;

        root /opt/panel/public;

        location / {
            try_files chr(36)uri /index.phpchr(36)is_argschr(36)args;
        }

        location ~ ^/index\.php(/|chr(36)) {
            fastcgi_pass 127.0.0.1:9000;
                fastcgi_split_path_info ^(.+\.php)(/.*)chr(36);
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME chr(36)realpath_rootchr(36)fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT chr(36)realpath_root;
                internal;
            }
        location ~ \.phpchr(36) {
            return 404;
        }
    }
}

nginx-rtmp.service file
this is my service that is created to start nginx server
[Unit]
Description=Nginx RTMP
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx-rtmp.pid
ExecStartPre=/opt/nginx-rtmp/sbin/nginx -t
ExecStart=/opt/nginx-rtmp/sbin/nginx
ExecReload=/opt/nginx-rtmp/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Updated nginx.config service started but getting 502 bad gateway error upon opening application on browser
user nginx;
worker_processes 2;
pid /run/nginx-rtmp.pid;
error_log logs/error.log;

events {
    worker_connections 1024;
}

rtmp {
    server {
        listen 1935;
    }
}

http {
    access_log logs/access.log;
    include mime.types;

    server {
        listen 26765;
        location /stat {
            rtmp_stat all;
        }
    }

    server {
        listen 80;

        root /opt/panel/public;

        location / {
            try_files $uri /index.php$is_args$args;
        }

        location ~ ^/index\.php(/|$) {
            fastcgi_pass 127.0.0.1:9000;
                fastcgi_split_path_info ^(.+\.php)(/.*)$;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root;
                internal;
            }
        location ~ \.php$ {
            return 404;
        }
    }
}

php-fpm.conf data
[global]
pid = /www/server/php/74/var/run/php-fpm.pid
error_log = /www/server/php/74/var/log/php-fpm.log
log_level = notice

[www]
listen = /tmp/php-cgi-74.sock
listen.backlog = 8192
listen.allowed_clients = 127.0.0.1
listen.owner = www
listen.group = www
listen.mode = 0666
user = www
group = www
pm = dynamic
pm.status_path = /phpfpm_74_status
pm.max_children = 150
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
request_terminate_timeout = 100
request_slowlog_timeout = 30
slowlog = var/log/slow.log


text:
Q: How can I specify the exact folder IN STREAMLIT for the uploaded file to be saved to? I am trying to create a simple GUI with streamlit and python for my aspect-based sentiment analysis project, the user should be able to upload a .txt file so that I can run the model on that file. I already created the widget for uploading a file. My question is:
The uploaded file should be added to a specific folder, how can I specify an exact location for the uploaded file to be saved?
uploaded_file = st.file_uploader('FILE UPLOAD')

(This is the code for the upload widget)

A: The file_uploader function does not save the file to disk, it writes to a BytesIO buffer.

The UploadedFile class is a subclass of BytesIO, and therefore it is "file-like". This means you can pass them anywhere where a file is expected.

https://docs.streamlit.io/en/stable/api.html?highlight=file_uploader#streamlit.file_uploader
If you want to save the result as a file, use the standard Python file io capabilities:
with open(filename, "wb") as f:
    f.write(buf.getbuffer())

A: To add to what @RandyZwitch said you can use this function to save to a directory of your choice (directory/folder "tempDir")
def save_uploaded_file(uploadedfile):
  with open(os.path.join("tempDir",uploadedfile.name),"wb") as f:
     f.write(uploadedfile.getbuffer())
  return st.success("Saved file :{} in tempDir".format(uploadedfile.name))

And apply the function below your uploaded file like below
datafile = st.file_uploader("Upload CSV",type=['csv'])
if datafile is not None:
    file_details = {"FileName":datafile.name,"FileType":datafile.type}
    df  = pd.read_csv(datafile)
    st.dataframe(df)
    # Apply Function here
    save_uploaded_file(datafile)

A: You can define path like this:
from pathlib import Path
path = "C:/Projects/ex1/your_file"
file_path = Path(path)

uploaded_file = st.file_uploader(file_path)


text:
Q: Delphi XE4 or XE5: how to open Google Chrome in popup format? Problem: I need to open Google Chrome by Delphi XE5 or XE4 on a given url but I need to open in popup format, without the menus and toolbars. How do?

A: silent mode;
ShellExecute(Application.Handle,'Open', 'chrome.exe',PChar(' -incognito '+URLText), 0, SW_SHOWNORMAL);

A: Create a new Chrome process with argument --app and your url


text:
Q: Proper way to update HTML5 offline application cache I use offline caching in my website and have the following event handler setup to handle updates
applicationCache.addEventListener('updateready', function () {
                    if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
                        window.applicationCache.swapCache();
                        window.applicationCache.update();
                        window.location.reload();
                    }
                });

It works but seems redundant to me. Do I need to call the swapCache() and update() functions or will a simple window.location.reload() suffice since the browser will use the new files on a refresh?

A: Actually according to MSDN documentation about Application Cache API you should use both.
From the documentation:

In order to swap an old cache out for a new one, call update first.
  When the status is in the UPDATEREADY state, calling swapCache will
  make the swap.
Calling swapCache will not update any content on your page. It will
  simply allow your webpage to be able to access any further dynamic
  content from the new cache instead of the old one. After the page is
  refreshed, the newly created cache will be used for all in-page and
  dynamic requests.
The swapCache method is provided for convenience but is not necessary
  for basic functionality. Loading or refreshing the page is sufficient.
  For example, refreshing the page after an UpdateReady event will
  reload the page from the new cache without a call to swapCache.
swapCache does not cause previously-loaded resources to be reloaded;
  for example, images do not suddenly get reloaded, and style sheets and
  scripts do not get reparsed or reevaluated. The only change is that
  subsequent requests for cached resources will obtain the newer copies.


text:
Q: Why do these two expressions produce the same value? I try to split a string to an array of equal-length substrings and the first thing I do is to calculate how many substrings there would be. While I wrote it myself I used the first expression down below. When I checked an answer given by someone else I saw the second one, which is not very obvious to me. Actually I couldn't figure out why they produce the same result though I could verify with concrete examples. So how do you prove they are equivalent in terms of generating the same result?
int groups = s.length() % subLen == 0 ? s.length() / subLen : s.length() / subLen + 1;
int groups = (s.length() + subLen - 1) / subLen;

A: Try to substitute s.length() with different values and see how the two calculations arrive at their respective result.
In essence, your version considers two cases that are handled differently and is doing the 'rounding up' explicitly in its second code branch.
The second version adds sublen-1 to the original string length so that the rounding down / truncation of the integer division arrives at the desired result for all given values of s.length().

A: First let's think about the actual context of the problem, that is , dividing a string, suppose its length is a, into a group of substrings whose lengths are equal, suppose that length is b, and then we know the range of a and b should be a >= b >= 1. If c is the result of the integer division a / b, which always rounds down, and if d is the result of the normal division a / b, and if d is an integer, a + (b - 1) would have no effect on making c bigger because only a + b can increase c by 1. But why does it have to be b - 1 instead of b - 2 or b - 3 etc? Because the minimum of b is 1 and if in b - ? the ? is bigger than 1 there's a chance that b - ? is negative, which means there's a chance that c would be reduced at least by 1 because a could be reduced at least by 1. If d is not an integer, then we know d == c * b + r where r is the remainder and (1) 1 <= r <= b - 1. So (a + b - 1) / b could be written as (c * b + r + b - 1) / b. According to (1) we have b <= r + b - 1 <= 2 * (b - 1), and then have b <= r + b - 1 < 2 * b, and then have (c + 1) * b <= a + b - 1 < (c + 2) * b, and then c + 1 <= (a + b - 1) / b < c + 2, which means c would be increased by 1 exactly when normal division a / b is not an integer.


text:
Q: error while running the WCF application Hello all when i am trying to run the application i am getting error like this one..

The service.svc file has the following code..
<%@ ServiceHost Language="C#" Debug="true" Service="prodcuts.ProductServiceImpl" CodeBehind="~/App_Code/ProductsService.cs" %>

Please help me..
Thankyou

A: WCF is trying to load a type from your application that doesnt exist. On first look it looks like a typo - did you mean to use the name "Products" rather than "prodcuts"?


text:
Q: Kotlin/Android selecting all elements in listView getchildat(i) I am currently making something on kotlin.
I was trying to make it so that when you click on individual items on the listView, it would become highlighted and "checked" as im using "CheckableLinearLayout" implementation.
However, unlike what I expected, this following code only selects the items currently within the view (~8, but there are 12 total).
Also, if I scroll up or down, the items that leave the window are automatically unselected... Thanks in advance.
    fun selectAll()
    {
        for (i in 0..rootView!!.list.childCount-1){
            var test = list.getChildAt(i) as CheckableLinearLayout
            test.setChecked(true)
        }

    }

A: You can set list items as selected after a scroll event by setting up an OnScrollListener in the listview. What do you mean by "the items currently within the view"?


text:
Q: рассчитать рост месячных продаж по стране в процентах по данному датафрейму Прошу помощи с решением интересной задачи, к которой мне не удается найти решение. Если кратко переходить к сути, то задача следующая:

*

*Некое предприятие продает товары покупающим из различных стран. Выяснить, в какой из них был самый большой процентный рост месячных продаж. Выяснить, сколько процентов составляет данный рост. В расчет следует брать именно те страны, в которых были ненулевые продажи в обоих этих месяцах.

Датафрейм выглядит соответственно:
( берутся два месяца - 9 и 3 месяца 2011 года )

InvoiceNo
StockCode
Quantity
InvoiceDate
UnitPrice
CustomerID
Country
Price
Year
Month

536365
85123A
6
2010-12-01 08:26:00
2.55
17850
United Kingdom
15.30
2011
9

536365
71053
6
2010-12-01 08:26:00
3.39
17850
United Kingdom
20.34
2011
9

581587
23254
4
2011-12-09 12:50:00
4.15
12860
France
16.60
2011
9

...
...
...
...
...
...
...
...
...
...

581587
23255
4
2011-12-09 12:50:00
4.15
12860
France
16.60
2011
3

581587
22138
3
2011-12-09 12:50:00
4.95
12860
France
14.85
2011
3

581588
22380
9
2011-12-09 12:52:00
2.10
12594
Italy
18.90
2011
3

581588
22381
9
2011-12-09 12:52:00
2.10
12594
Italy
18.90
2011
3

Примерное решение данной задачи в моей голове примерно такое - по каждой из стран рассчитать количество покупок в одном из каждых месяцев и затем просчитать, насколько за эти месяца увеличилось или уменьшилось количество покупок, т.е. измерить в процентах.
( к примеру, в 3 месяце в стране Norway было совершено 10 покупок, а в 9 месяце уже 100, прирост составил 400 и так посчитать к каждой стране и вывести страну с самым большим приростом )
Возможно, мое решение к данной задаче неверно, и так же я не знаю как превратить это решение в код, поэтому я прошу вашей помощи с решением данной задачи.
мой код к задаче неверен:
months_march = purchases.loc[(purchases['Year'] == 2011) & (purchases['Month'] == 3)]
months_september = purchases.loc[(purchases['Year'] == 2011) & (purchases['Month'] == 9)]
months = months_september.append(months_march)
months['Percent'] = months['Price'].pct_change().mul(100).round(0).map(lambda x: '{0:g}'.format(x) if x==x else x)
first = months.sort_values('Percent', ascending=False)[['Country', 'Percent']]
first = first.values.tolist()
first[0]

как ответ, должно получиться что то в роде этого:

Norway, 586

A: попробуйте примерно так (это решение не тестировалось):
(df.groupby(['Country','Year','Month'])
     .agg({'Price':'sum'})
     .reset_index()
     .groupby(['Country','Year'])
     .apply(
         lambda x: x['Price']
         .pct_change()
         .mul(100)
         .round()
         .max()
     ).sort_values(ascending=False)
     .head(1))