text:
Q: How do I solve this error, "error while trying to deserialize parameter" I have a web service that is working fine in one environment but not in another.
The web service gets document meta data from SharePoint, it running on a server where I cant debug but with logging I confirmed that the method enters and exits successfully.
What could be the reason for the errors?
The error message is,
The formatter threw an exception while trying to deserialize the message:

There was an error while trying to deserialize parameter http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse.

The InnerException message was 'Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected.

Expecting element 'Id'.'.  Please see InnerException for more details.

The InnerException was
System.ServiceModel.Dispatcher.NetDispatcherFaultException was caught
  Message="The formatter threw an exception while trying to deserialize the message:
There was an error while trying to deserialize parameter http://CompanyName.com.au/ProjectName:GetDocumentMetaDataResponse.
The InnerException message was
'Error in line 1 position 388.
'Element' 'CustomFields'
from namespace 'http://CompanyName.com.au/ProjectName' is not expected.
Expecting element 'Id'.'.  Please see InnerException for more details."

  Source="mscorlib"
  Action="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault"
  StackTrace:
    Server stack trace:
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameter(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeReply(Message message, Object[] parameters)
       at System.ServiceModel.Dispatcher.ProxyOperationRuntime.AfterReply(ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request)
       at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoap.GetDocumentMetaData(GetDocumentMetaDataRequest request) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2141
       at CompanyName.ProjectName.External.Sharepoint.WebServiceProxies.SharepointProjectNameSiteService.ProjectNameSiteSoapClient.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\External\CompanyName.ProjectName.External.Sharepoint.WebServiceProxies\Service References\SharepointProjectNameSiteService\Reference.cs:line 2150
       at CompanyName.ProjectName.Services.Shared.SharepointAdapter.GetDocumentMetaData(ListSummaryDto listSummary, FileCriteriaDto criteria, List`1 customFields) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Shared\SharepointAdapter.cs:line 260
       at CompanyName.ProjectName.Services.Project.ProjectDocumentService.SetSharepointDocumentData(List`1 sourceDocuments) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 1963
       at CompanyName.ProjectName.Services.Project.ProjectDocumentService.GetProjectConversionDocumentsImplementation(Int32 projectId) in D:\Source\TFSRoot\ProjectName\trunk\CodeBase\Services\CompanyName.ProjectName.Services\Project\ProjectDocumentService.cs:line 3212
  InnerException: System.Runtime.Serialization.SerializationException
       Message="Error in line 1 position 388. 'Element' 'CustomFields' from namespace 'http://CompanyName.com.au/ProjectName' is not expected. Expecting element 'Id'."
       Source="System.Runtime.Serialization"
       StackTrace:
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, Int32 memberIndex, Int32 requiredIndex, XmlDictionaryString[] memberNames)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, Int32 memberIndex, Int32 requiredIndex, ExtensionDataObject extensionData)
            at ReadFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
            at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
            at ReadArrayOfFileMetaDataDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
            at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
            at ReadMetaDataSearchResultsDtoFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
            at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
            at ReadGetDocumentMetaDataResponseBodyFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
            at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract)
            at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
            at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
            at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName)
            at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
            at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
       InnerException:

A: Are you sure your web service is deployed correctly to the enviornment that is NOT working.  Looks like the type is out of date.

A: This is happening because the web-service relies on using XmlSerializer to convert the wsdl among other things to XML, which doesn't support mixed-mode properties, like these:
public string strThing { get; private set; }

See: http://msdn.microsoft.com/en-us/library/ms978420.aspx
More information: http://www.geekscrapbook.com/2010/03/06/serializing-data-with-system-runtime-serialization-datacontractserializer/

A: I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.
To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"
Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.
The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..
[Serializable]
public class FileMetaDataDto
{
    .
    . a constructor...   etc and several other properties edited for brevity
    .

    public int Id { get; private set; }
    public string Version { get; private set; }
    public List<MetaDataValueDto> CustomFields { get; set; }

}

On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.
So the wsdl before update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
  </s:sequence>
  </s:complexType>

The wsdl after update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" />
  <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" />
  <s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" />
  <s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" />
  <s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" />
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
  <s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" />
  </s:sequence>
  </s:complexType>

A: Do you have this namespace setup?  You will have to ensure that this namespace matches the message namespace.  If you can update your question with the xml input and possibly your data object that would be helpful.
[DataContract(Namespace = "http://CompanyName.com.au/ProjectName")]
public class CustomFields
{
  // ...
}

A: Make sure that the table you are returning has a schema. If not, then create a default schema (i.e. add a column in that table).

A: In my case; my WCF service function was using List<byte> Types parameter and i was getting this exception in the client side. Then i changed it to byte[] Types, updated service reference and problem is solved.

A: I found the actual solution...There is a problem in invoking your service from the client.. check the following things.

*

*Make sure all [datacontract], [datamember] attribute are placed properly
i.e. make sure WCF is error free

*The WCF client, either web.config or any window app config, make sure config entries are properly pointing to the right ones.. binding info, url of the service..etc..etc
Then above problem : tempuri issue is resolved.. it has nothing to do with namespace.. though you are sure you lived with default,
Hope it saves your  number of hours!

A: In our case the problem was that we change the default root namespace name.

This is the Project Configuration screen
We finally decided to back to the original name and the problem was solved.
The problem actually was the dots in the Root namespace. With two dots (Name.Child.Child) it doesnt work. But with one (Name.ChidChild) works.


text:
Q: User in AzureAD has the role as User, but gets admin role on surface I do AzureAD just for ActiveDirectory in combination with Office365 for access to the computers via the cloud.
Now I have two problems which can't be solved by the Office365 team who pointed me to the AzureAD team.
User XYZ has the role of a normal user in Azure AD and in Office 365, but after I had set up his Surface Pro 3 with his AzureAD login, he is a full admin on the machine and I can't change this. He is the only user on the Surface Pro 3. How can I force this that is only a User and not an Admin?
And secondly I want to remove the pin to login to Windows 10, I can remove it, but next time he logs in, the pin is required again, and I can't find any place to switch this login option off in AzureAD.
Anybody able to point me in the right direction?
Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change selection properties in Jetbrains IDE(s)? Several times, while working with Jetbrains' IDE(s), I have faced the following issue:

The natural selection type is changed to this kind of a selection. When I reload the IDE, it gets back to its normal position. Is it a bug, or a feature of the IDE? How do I fix it?

A: From Jetbrains:
Toggling between line and column selection modes
To toggle between the line and the column selection modes, do one of the following:
On the main menu, choose Edit | Column Selection Mode.
On the context menu of the editor, choose Column Selection Mode.
Press Shift+Alt+Insert.
P.S. My guess would be you by accident used the wrong key combination. (I currently use PHPStorm & C-Lion and have not seen this issue)

A: Here is the documentation for selecting text in Jetbrains' editors.


text:
Q: On SQL Server, how to find the MAX or MIN value out of a couple of variables I just found out that the MAX() function in SQL only works on columns.
Is there a similar function I can use to find the max value out of e.g. these four variables?
SET @return = MAX(@alpha1, @alpha2, @alpha3, @alpha4)

Or do I have to put them in a column first (and thus create a table first...;-(    )?
Regards
Lumpi

A: There is no built-in function in T-SQL for this but you can use following
SELECT @result = MAX(alpha)
FROM   (SELECT @alpha1
        UNION ALL
        SELECT @alpha2
        UNION ALL
        SELECT @alpha3) T(alpha);

or (SQL Server 2008+)
SELECT @result = MAX(alpha)
FROM  (VALUES(@alpha1),
             (@alpha2),
             (@alpha3)) T(alpha);


text:
Q: Previous expression in clojure repl In the python repl, getting the result of the previously input expression is easy:
>>> 1+2
3
>>> _
3
>>>

Is there a way to do this in the clojure repl?

A: *1

Should do it! Similarly, you have access to *2 and *3 as well.


text:
Q: Change the apex:commandButton value from 'Return to Uploader' to 'Done' from Javascript (Jquery) I have a requirement to change the value of apex:commandButton from 'return to uploader' to 'Done' using Javascript(Jquery).
Below is my VF Page code:
<apex:commandButton style="float: right;" id="buttonId" value="Return to uploader" action="{!goToTypeSelection}" rendered="{!showAutoMatchUpload}" />

Below is my Javascript code that I am trying to change:
$upload = $(".upload[data-status='pending']").filter(":first"); //There is a HTML tag with data-status='Pending' in my HTML component that I have not shown.
if($upload.length == 0){
   $('#buttonId').attr('value', 'Done');
   console.log($("[id$=buttonId]").val());
}

Though I changed the attribute value to done from Javascript as shown above, the button is not getting changed.
I possibly see I am doing something wrong but not sure what is going wrong:

*

*I am changing the attribute value the wrong way. If yes, can you please suggest on how to change the value of the apex:commandbutton from JS.

*I have to rerender the button again after changing the attribute value from Javascript. If yes, can you please let me know on how to rerender the button from the Javascript.

A: First, the <button> that's generated here does have a value property, but that's actually just the value submitted to the server, and not the actual label of the button. The value is actually just the innerHTML/innerText of the button, so you need to use .html() or .text() to set the value:
$("[data-submit-button]").text("Done");

Second, Visualforce does some kind of transformation on the id property for <apex:*> elements, which ends up looking like j_id0:j_id1:buttonId; the exact format will depend on the page, if any parent elements have id values, and whether or not the button is in an <apex:pageBlockButtons> element, which will cause two buttons to appear with slightly different ID values, such as idForm:idPageBlock:idPageBlockButtons:buttonId and idForm:idPageBlock:idPageBlockButtons:bottom:buttonId.
Use either a data- property or a CSS class to target the button, or use the $Component variable to get the correct Id.
Examples:
$("#{!$Component.idForm.idPageBlock.idPageBlockButtons.buttonId}")

Or:
$("[data-submit-button]")

Where the button is changed to:
<apex:commandButton html-data-submit-button="submit" ...

Or:
$(".submitButton")

And setting a style class:
<apex:commandButton styleClass="submitButton" ...


text:
Q: NuGet pack looking for dependency in wrong folder I have multiple solutions, that may share packages with each other via NuGet feed (driven by TeamCity, 2018.1.3 (build 58658)). SolutionA exposes few projects to NuGet feed, projects from SolutionB reference some of those packages. Some of projects from SolutionB also should be packed and published to NuGet feed.
For SolutionA packaging and publishing goes perfectly. For SolutionB, packaging of projects, that depend on packages published to NuGet from SolutionA failing because of strange issue. When TeamCity executes NuGet package restore step, packages being downloaded to packages\Project.From.SolutionA.3.181.181\ folder. Then build step completing successfully, but packaging step failing because of NuGet pack command looks for package in folder packages\Project.From.SolutionA\3.181.181\!
Below is build log from pack command (NuGet version is 4.8.1)
Missing <TeamCityDir>\buildAgent\work\fbb25b8e9614747\packages\Project.From.SolutionA\3.181.181\Project.From.SolutionA.3.181.181.nupkg
    Error NU5012: Unable to find 'Project.From.SolutionA.3.181.181.nupkg'. Make sure the project has been built.
    NuGet.Packaging.Core.PackagingException: Unable to find 'Project.From.SolutionA.3.181.181.nupkg'. Make sure the project has been built.
    at NuGet.CommandLine.ProjectFactory.AddDependencies(Dictionary`2 packagesAndDependencies)
    at NuGet.CommandLine.ProjectFactory.ProcessDependencies(PackageBuilder builder)
    at NuGet.CommandLine.ProjectFactory.CreateBuilder(String basePath, NuGetVersion version, String suffix, Boolean buildIfNeeded, PackageBuilder builder)
    at NuGet.Commands.PackCommandRunner.BuildFromProjectFile(String path)
    at NuGet.Commands.PackCommandRunner.BuildPackage()
    at NuGet.CommandLine.PackCommand.ExecuteCommand()
    at NuGet.CommandLine.Command.ExecuteCommandAsync()
    at NuGet.CommandLine.Command.Execute()
    at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)

The only thing that replaced is real paths and names of projects

A: Have you made sure that there aren't more than one solution file (.sln) in your solution?  I was working with an older project that had the main solution file and then some of the sub-projects had their own solution files.  When I ran the build in TeamCity it would fail while trying to find the first nuget package and report the error:
Error NU5012: Unable to find 'package.version.nupkg'. Make sure the project has been built.

It took a while but I realized that the projects which failed all had their own solution files which was confusing TeamCity.  Once the files were removed the builds worked.


text:
Q: SceneKit - make SCNNode rotate horizontally but not spin multiple times? Ok, having a weird time rotating a SCNNode based off a joystick, just rotate to an angle defined by the joystick. Im mimicking Apple's Fox WWDC demo, so I get the angle of my joystick and transform it as they did to a CGFloat -
I am just trying to rotate my node on the horizontal axis (not in y direction only x) so that it
faces the camera point of view when joystick is DOWN and
faces forward when joystick is UP
I have this working to a degree but not all the way. Don't know why - problem is I need the same SIDE of my node (its a cube) to face say the left if joystick is down - right now this may or MAY NOT happen depending on how many spins the cube has undergone in getting to this back facing (DOWN) angle.
For example if I have a dot on the back face of node, I need that dot to ALWAYS face user/camera if the joystick is pointed down and cube has spun to point to user.
So far I get the angle from joystick (all from Apple) in float2 - look at cameraDirection:
func padOverlayVirtualStickInteractionDidStart(_ padNode: PadOverlay) {
        //control char
        if padNode == overlay!.controlOverlay!.leftPad {
            characterDirection = float2(Float(padNode.stickPosition.x), -Float(padNode.stickPosition.y))
        }

        //control world
        if padNode == overlay!.controlOverlay!.rightPad {
            cameraDirection = float2(Float(padNode.stickPosition.x), -Float(padNode.stickPosition.y))
        }
    }

    func padOverlayVirtualStickInteractionDidChange(_ padNode: PadOverlay) {
        //control char
        if padNode == overlay!.controlOverlay!.leftPad {
            characterDirection = float2(Float(padNode.stickPosition.x), -Float(padNode.stickPosition.y))
        }

        //control world
        if padNode == overlay!.controlOverlay!.rightPad {
            cameraDirection = float2( -Float(padNode.stickPosition.x), Float(padNode.stickPosition.y))
        }
    }

Convert this again:
var worldDirection = float2()
public var cameraDirection: vector_float2 {
        get {
            return self.worldDirection
        }
        set {
            var direction = newValue
            let l = simd_length(direction)
            if l > 1.0 {
                direction *= 1 / l
            }
            self.worldDirection = direction
        }
    }

Then:
func updateWorldRot() //called in update
    {
        if(overallWorldNode != nil)
        {
            let newDir = worldDirection(withPointOfView: sceneRenderer?.pointOfView)
            if !newDir.allZero() {

               worldDirectionAngle = CGFloat(atan2f(newDir.x, newDir.z))
            }
                //print("NODE: ", platformsSpawned[currentLevel]?.first?.node.rotation)
                //print("ANGLE: ", worldDirectionAngle)
        }
    }
 func worldDirection(withPointOfView pointOfView: SCNNode?) -> float3 {
        let controllerDir = self.cameraDirection
        if controllerDir.allZero() {
            return float3.zero
        }

        var directionWorld = float3.zero
        if let pov = pointOfView {
            let p1 = pov.presentation.simdConvertPosition(float3(controllerDir.x, 0.0, controllerDir.y), to: nil)
            let p0 = pov.presentation.simdConvertPosition(float3.zero, to: nil)
            directionWorld = p1 - p0
            directionWorld.y = 0
            if simd_any(directionWorld != float3.zero) {
                let minControllerSpeedFactor = Float(0.2)
                let maxControllerSpeedFactor = Float(1.0)
                let speed = simd_length(controllerDir) * (maxControllerSpeedFactor - minControllerSpeedFactor) + minControllerSpeedFactor
                directionWorld = speed * simd_normalize(directionWorld)
            }
        }
        return directionWorld
    }

Then I apply to the node:
 public var worldDirectionAngle: CGFloat = 0.0 {
        didSet {
            overallWorldNode.runAction(
                SCNAction.rotateTo(x: 0.0, y: worldDirectionAngle, z: 0.0, duration: 0.2, usesShortestUnitArc:true))
        }
    }

What can I do to stop multiple rotations?


text:
Q: Maintain Drag & Dropped items position when restarting I have a RecyclerView - Grid, with drag & drop, using this code I've manage to achieve that, And made a lot of changes, only one problem, i can't save the dragged items position on restarting ( the app not the phone ).
What i thought about is adding " int position " to my item.java constructor, but what i can't do is getting the changed position .
I'm using the same drag & drop codes provided in the link.
    ItemTouchHelper.Callback _ithCallback = new ItemTouchHelper.Callback() {
    //and in your imlpementaion of
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        // get the viewHolder's and target's positions in your adapter data, swap them
        Collections.swap(AllItems, viewHolder.getAdapterPosition(), target.getAdapterPosition());
        // and notify the adapter that its dataset has changed

        rcAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        //TODO
    }

    //defines the enabled move directions in each state (idle, swiping, dragging).
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
    }
};

Here's the code in onCreate :
    ItemTouchHelper ith = new ItemTouchHelper(_ithCallback);
    ith.attachToRecyclerView(RcView);

Getting Duplicated items after position changing, Code :
    @Override
public void onStop()
{
    super.onStop();
    SharedPreferencesTools.setOrderedItems(this, AllItems);
}

getAllItemList :
private List<Item> getAllItemList(){
AllItems = SharedPreferencesTools.getOrderedItems(this);
//Add item .. etc
//return items

}

A: Just keep your modified collection AllItems in SharedPreferences and load it on the app start & store it back, once you get out of the app.
To do this, you need to serialize your collection to json by Gson and store as a String. And then deserialize it afterwards:
public final class SharedPreferencesTools {
    private static final String USER_SETTINGS_PREFERENCES_NAME = "UserSettings";
    private static final String ALL_ITEMS_LIST = "AllItemsList";
    private static Gson gson = new GsonBuilder().create();

    public static List<Item> getOrderedItems(Context context) {
        String stringValue = getUserSettings(context).getString(ALL_ITEMS_LIST, "");
        Type collectionType = new TypeToken<List<Item>>() {
        }.getType();
        List<Item> result = gson.fromJson(stringValue, collectionType);
        return (result == null) ? new ArrayList<Item>() : result;
    }

    public static void setOrderedItems(Context context, List<Item> items) {
        String stringValue = gson.toJson(items);

        SharedPreferences sharedPreferences = getUserSettings(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(ALL_ITEMS_LIST, stringValue);
        editor.apply();
    }

    static SharedPreferences getUserSettings(Context context) {
        return context.getSharedPreferences(USER_SETTINGS_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }
}

The usage of these two methods:
 SharedPreferencesTools.setOrderedItems(getActivity(), AllItems);
 ...
 List<Item> AllItems = SharedPreferencesTools.getOrderedItems(getActivity());


text:
Q: Webscraping-Python loop stuck This is just a normal program to scrape top 250 movies on imdb. But when I try to go to the links of each individual movie to get more info, the loop gets stuck.
import requests
from bs4 import BeautifulSoup

website="https://www.imdb.com/chart/top/"
d={}
r=requests.get(website, headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"})
c=r.content
soup=BeautifulSoup(c, "html.parser")

all=soup.find_all("td",{"class": "titleColumn"})

for item in all:
    d["Name"]=item.find("a").text
    #print(d["Name"])
    d["Links"]="https://www.imdb.com"+item.find("a").get("href")
    #print(d["Links"])
    r2=requests.get(d["Links"], headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac
    OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97
    Safari/537.36"})
    c2=r2.content
    soup2=BeautifulSoup(c2, "html.parser")
    d["Info"]=soup2.find("div", class=False)
    print(d["Info"])

Can we not scrape multiple web pages at once?
I am using jupyter notebooks.
I was trying to get movie summary. but then realised that the loop is stuck at this statement (used the print statement to find this)

A: I'm not really sure why your loop gets stuck but it looks like you have a syntax error with class=False, at least this is what my IDE says. Anyhow, you can scrape multiple pages but in order to do that you need to get the urls first.
Here's a working example that builds a list of dictionaries that looks like this:
[{url: movie_url, title: movie_title, summary: movie_summary}]
The code:
import csv

import requests
import unicodedata

from bs4 import BeautifulSoup

def get_movie_urls(main_url = "https://www.imdb.com/chart/top/") -> list:
    r = requests.get(main_url).content
    soup = BeautifulSoup(r, "html.parser")
    titles = soup.find_all("td", {"class": "titleColumn"})
    return [f"https://imdb.com{title.find('a').get('href')}" for title in titles]

def get_movie_info(url: str) -> dict:
    s = BeautifulSoup(requests.get(url).content, "html.parser")
    title_wrapper = s.find("div", {"class": "title_wrapper"}).find("h1")
    summary = s.find("div", {"class": "summary_text"})
    title = title_wrapper.text.strip().split('(')[0].rstrip()
    return {
        "url": url,
        "title": unicodedata.normalize("NFKD", title),
        "summary": summary.text.strip(),
    }

def scrape_imdb(limit: int = 0) -> list:
    return [get_movie_info(url) for url in get_movie_urls()[:limit]]

def dump_to_csv(imdb_data: list):
    keys = imdb_data[0].keys()
    with open('imdb_top250.csv', 'w', newline='') as f:
        w = csv.DictWriter(f, keys)
        w.writeheader()
        w.writerows(imdb_data)

data = scrape_imdb(limit=2)
print(data)
dump_to_csv(data)

This outputs:
[{'url': 'https://imdb.com/title/tt0111161/', 'title': 'The Shawshank Redemption', 'summary': 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.'}, {'url': 'https://imdb.com/title/tt0068646/', 'title': 'The Godfather', 'summary': 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.'}]

To scrape all 250 top movies, just remove the limit argument from scrape_imdb(limit=2) to have just scrape_imdb().
As a bonus, I've added dumping the results to a .csv file.


text:
Q: Как передать instace объекта в функцию? Проститите за тупой вопрос просто приходится учить ts походу дела. Как предать instance объекта в функцию?
Вот в одном файле експротирую инстанс класса вот так  export default new ApiError();
и в другом использую:
import { Request, Response, NextFunction } from "express";
import ApiError from '../errors/ApiError';

const errorHandler = function (err: ApiError, req: Request, res: Response, next: NextFunction): Response {
    if (err instanceof ApiError) {
        return res.status(err.status).json({message: err.message});
    }
    return res.status(500).json({message: "Непредвиденная ошибка!"})
}

И мне высвечивает ошибка типа это не тип
: ⨯ Unable to compile TypeScript:
src/middlewares/ErrorHandlingMiddleware.ts:4:37 - error TS2749: 'ApiError' refers to a value, but is being used as a type here. Did you mean 'typeof ApiError'?

4 const errorHandler = function (err: ApiError, req: Request, res: Response, next: NextFunction): Response {
                                     ~~~~~~~~
src/middlewares/ErrorHandlingMiddleware.ts:5:24 - error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

5     if (err instanceof ApiError) {
                        ~~~~~~~~

   at createTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587:12)
   at reportTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:591:19)
   at getOutput (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:921:36)
   at Object.compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1189:32)
   at Module.m._compile (/home/ihor/T^: команда не найдена
est Task by Komah Ihor/node_modules/ts-node/src/inihor@ihor-GF65-Thin-9SEXR:~/Test Task by Komah Ihor$ TSError: ⨯ Unable to compile TypeScript:
dex.ts:1295:42)
   at Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
   at Object.require.extensions.<computed> [as .ts] (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1298:12)
   at Module.load (internal/modules/cjs/loader.js:933:32)
   at Function.Module._load (internal/modules/cjs/loader.js:774:14)
   at Module.require (internal/modules/cjs/loader.js:957:19)
[nodemon] app crashed - waiting for file changes before starting...
^CTSError:: команда не найдена

как использовать тип  ApiError в єтом файле


text:
Q: How to find the lowest value from maximum values via has_many relationship Product.all.map { |p| p.reviews.maximum(:created_at) }.min

I would like to find the lowest values from maximum values.
Is it doable in one database query without using map and min methods?

A: Yes, it could be achieved in one query. You could select from Review and group_by product_id, then calculate max created_at in each group, for example:
Review
  .select("MAX(created_at) OVER (PARTITION BY product_id) AS max_created_at")
  .order(max_created_at: :asc)
  .first
  .max_created_at


text:
Q: Pop up calendar for date selection in selenium java how to select date from calendar pop up? There's a text field which is in disabled mode. When you click on the calendar icon at the corner of the text field the calendar pops up which displays the current date. I need to select the date which is two years back. How do i go about doing that in selenium java?
below is the html code:

    February 2009

    Su
    Mo
    Tu
    We
    Th
    Fr
    Sa

     Jan
     Feb
     Mar
     Apr
     May
     Jun
     Jul
     Aug
     Sep
     Oct
     Nov
     Dec

A: use try catch statement
In try u can search for the element to be present in the page (any unique element related to the date to be selected)
In catch block you can click on the back button .
so in this case it will keep clicking on back/previous button in the calender to go to the previuos year .


text:
Q: Do I have a true rms meter I bought an Excel XL 830L multimeter with the understanding that it was a RMS voltmeter.
I also have UEI ElectroMate DM 200.
When I checked the output of my APC unit with both meters, the readings were about the same.
Is there a way to tell if a meter is an RMS type?

A: Please see this link :http://www.testequipmentdepot.com/uei/digital-multimeters/dm200.htm
The meter is a discontinued model also available from Ebay. It is NOT a true RMS meter so non-sine waves will give a ambiguous reading at best. Usually a non-RMS meter will see only the most peak voltage present and not the true average.
If you want an excellent true RMS DVM stay with a known good manufacture like Fluke. The Fluke 87 III series is $400 USD, but it is top dog for accuracy.


text:
Q: Tensorflow: Batching whole dataset (MNIST Tutorial) Following this tutorial: https://www.tensorflow.org/versions/r1.3/get_started/mnist/pros
I wanted to solve a classification problem with labeled images by myself. Since I'm not using the MNIST database, I spent days creating my own dataset inside tensorflow. It looks like this:
#variables
batch_size = 50
dimension = 784
stages = 10

#step 1 read Dataset
filenames = tf.constant(filenamesList)
labels = tf.constant(labelsList)

#step 2 create Dataset
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

#step 3: parse every image in the dataset using `map`
def _parse_function(filename, label):
    #convert label to one-hot encoding
    one_hot = tf.one_hot(label, stages)

    #read image file
    image_string = tf.read_file(filename)
    image_decoded = tf.image.decode_image(image_string, channels=3)
    image = tf.cast(image_decoded, tf.float32)

    return image, one_hot

#step 4 final input tensor
dataset = dataset.map(_parse_function)
dataset = dataset.batch(batch_size) #batch_size = 100

iterator = dataset.make_one_shot_iterator()
images, labels = iterator.get_next()

images = tf.reshape(images, [batch_size,dimension]).eval()
labels = tf.reshape(labels, [batch_size,stages]).eval()

for _ in range(10):
    dataset = dataset.shuffle(buffer_size = 100)
    dataset = dataset.batch(batch_size)
    iterator = dataset.make_one_shot_iterator()
    images, labels = iterator.get_next()

    images = tf.reshape(images, [batch_size,dimension]).eval()
    labels = tf.reshape(labels, [batch_size,stages]).eval()

    train_step.run(feed_dict={x: images, y_:labels})

Somehow using a higher batch_sizes will break python. What I'm trying to do is to train my neural network with new batches on each iteration. That's why Im also using dataset.shuffle(...). Using dataset.shuffle also breaks my Python.
What I wanted to do (because shuffle breaks) is to batch the whole dataset. By evaluating ('.eval()') I will get a numpy array. I will then shuffle the array with numpy.random.shuffle(images) and then pick up some the first elements to train it.
e.g.
for _ in range(1000):
    images = tf.reshape(images, [batch_size,dimension]).eval()
    labels = tf.reshape(labels, [batch_size,stages]).eval()

    #shuffle
    np.random.shuffle(images)
    np.random.shuffle(labels)

    train_step.run(feed_dict={x: images[0:train_size], y_:labels[0:train_size]})

But then here comes the problem that I can't batch the my whole dataset. It looks like that the data is too big for python to work with.
How should I solve this differently?
Since I'm not using the MNIST database there isn't a function like mnist.train.next_batch(100) which comes handy for me.

A: Notice how you call shuffle and batch inside your for loop? This is wrong. Datasets in TF work in the style of functional programming, so you are actually defining a pipeline for preprocessing the data to feed into your model. In a way, you give a recipe that answers the question "given this raw data, which operations (map, etc.) should I do to get batches that I can feed into my neural network?"
Now you are modifying that pipeline for every batch! What happens is that the first iteration, the batch size is, say [32 3600]. The next iteration, the elements of this shape are batched again, to [32 32 3600], and so on.
There's a great tutorial on the TF website where you can find out more how Datasets work, but here are a few suggestions how you can resolve your problem.

*

*Move the shuffling to right after "Step 2" in your code. Then you are shuffling the whole dataset so your batches will have a good mixture of examples. Also increase the buffer_size argument, this works in a different way than you probably assume. It's usually a good idea to shuffle as early as possible, as it can be a slow operation if you have a large dataset -- the shuffled part of dataset will have to be read into memory. Here it does not really matter whether you shuffle the filenames and labels, or the read images and labels -- but the latter will have more work to do since the dataset is larger by that time.

*Move batching and the iterator generator to be the last steps, just before starting your training loop.

*Don't use feed_dict with Dataset iterators to input data into your model. Instead, define your model in terms of the outputs of iterator.get_next() and omit the feed_dict argument. See more details from this Q&A: Tensorflow: create minibatch from numpy array > 2 GB

A: Ive been getting through a lot of problems with creating tensorflow datasets. So I decided to use OpenCV to import images.
import opencv as cv
imgDataset = []
for i in range(len(files)):
    imgDataset.append(cv2.imread(files[i]))
imgDataset = np.asarray(imgDataset)

the shape of imgDataset is (num_img, height, width, col_channels). Getting the i-th image should be imgDataset[i].
shuffling the dataset and getting only batches of it can be done like this:
from sklearn.utils import shuffle
X,y = shuffle(X, y)
X_feed = X[batch_size]
y_feed = y[batch_size]

Then you feed X_feed and y_feed into your model


text:
Q: Why does the variable (line 6) get a space in white? (Nivel: Beginner Workflow Runestone)  1. '''  x = 1    '''      # initialize x print(x)
 2. '''  x = x + 1    # update x    '''
 3. '''  print(x) for n in range(4):    '''
 4. '''  n= n+1    '''
 5. '''  print("nmap -n -Pe 10.0.2 ",n)    ''' # Why the variable get a space in white ?
 6. '''  print("nmap -n -PE 10.0.2.",n)    ''' Why this line is equal than previous line?
 7. '''  print("Range imprime :", x,"el número exacto") #con respecto al anterior lista    '''

Why does the variable (line 6) get a space in white? (Nivel: Beginner Workflow Runestone)
Thanks All!

A: You get a white space for variable for line 6 because the default separator for print is ' '.

Here's the function definition for print():

print(object(s), separator=separator, end=end, file=file, flush=flush)

Let me describe what the function definition says:

*

*object(s): Any object, and as many as you like. Will be converted to string before printed

*sep='separator'  Optional. Specify how to separate the objects, if there is more than one.

Default is ' '(this is why we get a white space)

*

*end='end'    Optional. Specify what to print at the end. Default is '\n' (line feed)

*file     Optional. An object with a write method. Default is sys.stdout

*flush    Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
If you want to add any-other separator like '*', then:
print('Hello','world!',sep='*')
Which will output: Hello*world!
As for your other question: Why this line is equal than previous line?
Answer: It is same because it is being passed as an object param and hence will be treated as a simple string, if you want to print variables then I'll suggest you use str.format().
Demo for str.format():
import math as m
print(str.format('Value of PI: {0}, Value of e:{1}',m.pi,m.e))

Output: Value of PI: 3.141592653589793, Value of e: 2.718281828459045
Hope this helps you. Cheers!


text:
Q: Webview , loadData method on Android 4.0.4 does not work I am using Webview and loadData method like this :
                    try {
                    htmlEncode = URLEncoder.encode(html, "UTF-8").replaceAll("\\+", " ");
                } catch (UnsupportedEncodingException e) {
                    htmlEncode = html;
                    e.printStackTrace();
                }
                webView.loadData( htmlEncode,"text/html; charset=UTF-8", "UTF-8");

html is "html string". Those of code is work fine in all android version except android 4.0.4. The webView don't understand \n character. It can't break to new line.
I and my partner searching for hours but can't find any solution for this.
There are some reason we can't use loadDataWithBaseURL() method.
Have you ever faced this problem ? or do you have any idea for us to find out what the wrong ?

A: I resoled my problem. I use webview by this way:  Add webview to layout at runtime. So, when I use loadDataWithBaseURL() on Android 4.0.4. It can't show html string so I used loadData() method instead. But when I used loadData() method some time the webview can't show the content too, or have many problem with html string encode. But now I have solution.
        webView.postDelayed(new Runnable() {
        @Override
        public void run() {
            webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", "UTF-8");
        }
    }, 100);

I dont' know why we have to delay a little time before calling loadDataWithBaseURL method.
But as my guess, maybe because the webview need time to init before load the html string.
Hope it help someone have this problem in future.

A: webView.loadData(HtmlEncode, "text/html; charset=UTF-8", null);

Above should work in Android 4.0. Tested on Android 4.0.
Edit:
Works fine on 4.0.3

A: Have a look at this issue.
In short, the workaround is to replace \r\n with


text:
Q: How to Add time in SharePoint List? I am wondering how to add time field in sharepoint list which will allow users to enter time.
Is this possible in SharePoint? If Yes, How can I achieve this?

A: This is not possible by OOTB. But there are many possible ways to achieve it. Along with the link shared by @ganesh in the comment above, you can try these couple of ways mentioned below:
Using Date & Time field and Calculated Column
Create a Date & Time column and a Calculated column with the formula:
=TEXT([Date column name],"hh:mm AM/PM")

Use time picket ui on your page which can allow user to enter time. In you code behind (js code), while entering data into SharePoint, you can append the time to a date and then add this data to the Date Column. The time which user added will be seen in the Calculated column.
Using number fields and Calculated column
Create 2 number fields (1 for hours and other for minutes) and specify min and max value according to the field (0-24 for hours and 0-60 for minutes). Create a calculated field with the formula:
=[Hours Column]&":"&[Minutes Column]


text:
Q: Setting the initial window size of an app on OS X? I'm using Xcode 7 on Yosemite. I created a new OS X application, and it came with a storyboard. When I launch the app, the app window is tiny.
What is the easiest way to set the default window size when the app launches?
Ideally I'm looking for a storyboard solution, not a programatic solution. However, if one does not exist, then a programatic solution will suffice. I don't want to set the minimum/maximum size of the window; the user should be able to size it as they see fit.

A: Upon the view loading, so in the viewDidLoad method you can place either a call to a function or a line of code that looks like this :
self.view.window?.setFrame(NSRect(x:0,y:0,width: 1440,height: 790), display: true)

This will set your initial view to the NSRect you specify and display it.

A: I figured it out...
You need to change the initial View Controller's View (NSView) size to whatever you want in the Size Inspector. You do not need to touch the Window Controller nor the Window.
Important: Don't forget to delete Xcode's derived data; otherwise it will remember the previous value that was used the first time the app was run.


text:
Q: How to find comment count and review count of a given Article in SQL..? I have 2 tables :

*

*review (including content_type_id , object_id )

*comments (including content_type_id , object_id )

The combination of "content_type_id and object_id" uniquely defines an entity (like article etc)

Now i want to write a single SQL Query to :
"list all the articles with their 'review_count' and 'comment_count' ".
I mean in final result , what i want is :
content_type_id  | object_id | review_count | comment_count
How can i acheive this..??

A: (Edited after question changed and I found a data-bug)
Try this one:
select
    content_type_id, object_id,
    sum(review_count) review_count,
    sum(comment_count) comment_count
from
    (
        select
            content_type_id, object_id, count(*) review_count
        from jc_reviews
        group by 1, 2
    ) as r_count
    full outer join
    (
        select content_type_id, object_id, count(*) comment_count
        from jc_comments
        group by 1, 2
    ) as c_count
    using (content_type_id, object_id)
group by 1, 2

It does not use a central table (formerly called article). This means, that items without any comment and without any review will not show up in the result. Items where at least one comment or one review is there will show up.

A: SELECT article_id, article_name,
(
    select count(review_id)
    from review
    where article_id = a.articles
) review_count,
(
   select count(comments _id)
    from comments
    where article_id = a.articles
) comment_count
FROM articles a

A: Off the top of my head but I think it would work:

SELECT
article_id,
article_name,
count(review_id) as review_count,
count(comment_id) as comment_count
FROM articles a, reviews b, comments c
WHERE
a.article_id = b.article_id OR
a.article_id = c.article_id

This would go only for articles with reviews and/or comments. To get ones without use a left join.

A: select a.article_id,
    coalesce(rc.review_count, 0) as review_count,
    coalesce(cc.comment_count, 0) as comment_count
from articles a
left outer join (
    select article_id, count(*) as review_count
    from review
    group by article_id
) rc on a.article_id = rc.article_id
left outer join (
    select article_id, count(*) as comment_count
    from comments
    group by article_id
) cc on a.article_id = cc.article_id

A: I would begin by keeping a consistent naming convention on my tables and keep them all named in the singular
SELECT article_id = a.article_id
       ,review_count = COUNT(DISTINCT(r.review_id))
       ,comment_count = COUNT(DISTINCT(c.comment_id))
  FROM article a
  LEFT OUTER JOIN review r
    ON a.article_id = r.article_id
  LEFT OUTER JOIN comment c
    ON a.article_id = c.article_id
 GROUP BY a.article_id

Here's some test data to play with:
-- Create tables
CREATE TABLE article(article_id INT)
CREATE TABLE review(review_id INT, article_id INT)
CREATE TABLE comment(comment_id INT, article_id INT)

-- Create some test data
INSERT INTO article SELECT 1
INSERT INTO article SELECT 2
INSERT INTO article SELECT 3

INSERT INTO review SELECT 10, 1
INSERT INTO review SELECT 20, 2
INSERT INTO review SELECT 30, 2
INSERT INTO review SELECT 40, 3
INSERT INTO review SELECT 50, 3
INSERT INTO review SELECT 60, 3

INSERT INTO comment SELECT 200, 1
INSERT INTO comment SELECT 300, 1
INSERT INTO comment SELECT 400, 2
INSERT INTO comment SELECT 500, 2
INSERT INTO comment SELECT 600, 3

After you significantly changed your question, I believe this query will provide you an answer:
SELECT u.content_type_id
       ,u.object_id
       ,review_count = SUM(u.review_count)
       ,comment_count = SUM(u.comment_count)
  FROM
    (
    SELECT content_type_id
           ,object_id
           ,review_count = COUNT(*)
           ,comment_count = 0
      FROM review
     GROUP BY content_type_id, object_id
     UNION
    SELECT content_type_id
           ,object_id
           ,review_count = 0
           ,comment_count = COUNT(*)
      FROM comment
     GROUP BY content_type_id, object_id
    ) u
GROUP BY u.content_type_id, u.object_id

And here is some test data to work with:
CREATE TABLE review(review_id INT, content_type_id INT, object_id INT)
CREATE TABLE comment(comment_id INT, content_type_id INT, object_id INT)

INSERT INTO review SELECT 11, 10, 100
INSERT INTO review SELECT 12, 10, 100
INSERT INTO review SELECT 13, 20, 100
INSERT INTO review SELECT 13, 10, 200
INSERT INTO review SELECT 13, 30, 100
INSERT INTO comment SELECT 21, 10, 100
INSERT INTO comment SELECT 22, 20, 100
INSERT INTO comment SELECT 23, 20, 100
INSERT INTO comment SELECT 24, 20, 100
INSERT INTO comment SELECT 25, 10, 200
INSERT INTO comment SELECT 26, 10, 200

A: try this:
SELECT  a.Article_ID,
        COUNT(b.Article_ID) as ReviewCount,
        COUNT(c.Article_ID) as CommentCount
FROM Articles a JOIN Review b ON
        a.Article_ID = b.Article_ID
    LEFT JOIN Comments c ON
        a.Article_ID = c.Article_ID
GROUP BY a.Article_ID


text:
Q: Reactjs Concat with prev state I have this simple react code

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      textarea: 'Hello World! \n \nTry to press Shift enter after Hello \n \nShould be like this \nHello \nWorld! '
    };
  }
  onChange = (e) => {
    this.setState({ textarea: e.target.value })
  }
  handlePress = e => {
    if (e.keyCode === 13 && e.shiftKey) {
      e.preventDefault();
      this.setState(prevState => ({ textarea: prevState.textarea.concat('\n why here') }))
    } else if (e.keyCode === 13) {
      e.preventDefault();

    }
  }
  render() {
    return (

        <textarea style={{ height: 200, width: 200 }} value={this.state.textarea} onKeyDown={this.handlePress} onChange={this.onChange} />

    );
  }
}

ReactDOM.render(<App />, document.getElementById('code'));

Should Be like this

Can anyone help me please or just guide me to correct way I'm stack in this problem even I don't know how to explain it to make a research

A: In this fragment of your code:
this.setState(prevState => ({ textarea: prevState.textarea.concat('\n why here') }))

you concat the previous textarea state with some string - in your case "\n why here". It joins the end of the former string with the beginning of the latter - nothing more, nothing less.
As you see, there is no notion of a cursor in your code - you don't specify correctly where "\n why here" should be put.
Please have a look at selectionStart (and maybe selectionEnd) to get cursor's position.
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Property/selectionStart
Then, change the concat part of your logic to insert your string in desired position.

A: You can make use of selectionStart value to get cursor position and break the text at that position and use .slice method to set the value back to state after appending \n;

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      textarea: 'Hello World! \n \nTry to press Shift enter after Hello \n \nShould be like this \nHello \nWorld! '
    };
  }
  onChange = (e) => {
    this.setState({ textarea: e.target.value })
  }
  handlePress = e => {
    e.persist();
    if (e.keyCode === 13 && e.shiftKey) {
      e.preventDefault();
      const pos = e.target.selectionStart;
      console.log(this.state.textarea)
      this.setState(prevState => ({ textarea: prevState.textarea.slice(0, pos) + " \n " + prevState.textarea.slice(pos) }))
    } else if (e.keyCode === 13) {
      e.preventDefault();

    }
  }
  render() {
    return (

        <textarea style={{ height: 200, width: 200 }} value={this.state.textarea} onKeyDown={this.handlePress} onChange={this.onChange} />

    );
  }
}

ReactDOM.render(<App />, document.getElementById('code'));


text:
Q: implement my own strip method in Python I am trying to implement my own strip method in Python, so without using the built-in method, I'd like my function to strip out all the whitespace from the left and the right.
Here, what I am trying to do is create a list, remove all the blank character before the first non-space character, then do it reverse way, finally return the list to a string. But with what I wrote, it doesn't even remove one whitespace.
I know what I am trying to do might not even work, so I would also like to see the best way to do this. I am really new to programming, so I would take any piece of advise that makes my program better. Thanks!
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))

def my_strip(inputString):
    newString = []
    for ch in inputString:
        newString.append(ch)
    print(newString)
    i = 0
    while i < len(newString):
        if i == " ":
            del newString[i]
        elif i != " ":
            return newString
        i += 1
    print(newString)

A: Instead of doing a bunch of string operations, let's just get the beginning and ending indices of the non-whitespace portion and return a string slice.
def strip_2(s):
    start = 0
    end = -1
    while s[start].isspace():
        start += 1
    while s[end].isspace():
        end -= 1
    end += 1
    return s[start:end or None]

A: How about using regular expression?
import re

def my_strip(s):
   return re.sub(r'\s+$', '', re.sub(r'^\s+', '', s))

>>> my_strip('   a c d    ')
'a c d'

A: What you seem to be doing is an ltrim for spaces, since you return from the function when you get a non-space character.
Some changes are needed:
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))

def my_strip(inputString):
    newString = []
    for ch in inputString:
        newString.append(ch)
    print(newString)
    i = 0
    while i < len(newString):
        if i == " ": # <== this should be newString[i] == " "
            del newString[i]
        elif i != " ": # <== this should be newString[i] == " "
            return newString
        i += 1 # <== this is not needed as the char is deleted, so the next char has the same index
    print(newString)

So the updated code will be:
# main function
inputString = input("Enter here: ")
print(my_strip(inputString))

def my_strip(inputString):
    newString = []
    for ch in inputString:
        newString.append(ch)
    print(newString)
    i = 0
    while i < len(newString):
        if newString[i] == " ":
            del newString[i]
        elif newString[i] != " ":
            return newString
    print(newString)

Good luck with the rest of the exercise (implementation of rtrim).


text:
Q: CSS .wf-inactive Will adding the following code to my CSS work in providing an alternative font whilst the webfont from Google is inactive? All I have done is add the following link to my HTML:
<link href="https://fonts.googleapis.com/css?family=Playfair+Display|Shrikhand" rel="stylesheet">

I've added this to the CSS:
.wf-inactive body {

font-family: serif;
font-size: 1em;
line-height: 1.4em;
letter-spacing: 0;
word-spacing: 0.035em;
margin-top: 0.65em;
margin-bottom: 0.55em;

/* To match body, p, section, etc's active content */

}

Is there anymore to it than this?

A: I recommend using a font stack, which is specifically designed so that if one font fails, your browser will fall to the next one in line.
font-family: 'Playfair Display', Arial, sans-serif;

What this tells your browser is to prioritize Playfair, and if that doesn't work, switch to Arial. If your user doesn't have Arial, it'll switch to the default san-serif on their computer.


text:
Q: Does Android app need to sign in release mode before distribute to the clients I've develop an app (thesis) to be used by 10 people (geologists). My question is, do i need to sign my app in release mode or just give them the apk file from bin through flash drive?

A: According to android developer guide  you application must digitally signed to install or run Android system. This may help you in signing the apk.

A: An android phone will refuse to install an apk that is not signed at all, so the question is really between signing with a debug certificate vs. signing with a release one.
While you can distribute a debug signed apk outside of a marketplace, debug certificates tend to have short validity periods on the order of a year.  This will, at minimum, cause problems with providing upgrades in the future, as after the certificate expires you would have to create a new one, and changing the certificate would require wiping out the private data of the old version on each phone.
(According to the docs, an already-installed app will continue to work after its certificate expires, but there could still be problems if a user gets a new device, etc)
There is also a security concern, in that (except on the version where it was broken) the run-as debug tool allows anyone with adb to execute programs as the userid of a debug-cerficate app.  This would expose all the private data in the app, much like running on a rooted phone potentially does.
For these reasons, as well as general "that's not what it is for!" distribution channels tend to refuse to accept debug-signed apk's.

A: You can distribute your APK after signing with debug certificate if you are not going to upload it on Google Play and only looking for testing purpose or distribute to client for just testing purpose.
APK won't install/update once your debug certificate expire and debug certificate validity is almost one year.
Upon installation, the Android SDK generates a "debug" signing certificate for you in a keystore called debug.keystore. A debug certificate is only valid for 365 days.
If you are looking to release updates it is good if you sign your application with own release certificate and in this you can set your expire validity.


text:
Q: REST call in vb.net: how to pass the key "file" that works in cURL I have been struggling with this issue for almost a month now, and I read everything I could find online, with no solution. Here's my problem: I'm implementing a client for a RESTful API service that has to send an XML file through a POST call, in vb.net. I am able to make it working when it comes to GET some data, in xml format, but when it comes to send this Xml file, I always get the "400 bad request error".
I already figured it out that it has to be a matter of the key that has to be passed to the server (that apparently accepts only file uploading for POST, I cannot send it as a string).
Basically this call works with cURL, but I am struggling for implementing my own call in vb.net, passing the right value.
Working cURL call: (that successfully transmits the XML)
  c:>curl -u username:password -F "file=@filename.xml" -X POST http://hostname.com/URI?parameters

Not working Vb.net code: (that gives me 400 Bad Request)
Dim ss As String = "" 'server says...
Dim S As String = txb_username.Text & ":" & txb_password.Text
Dim EncodedString As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(S))
Dim req As HttpWebRequest = Nothing
Dim res As HttpWebResponse = Nothing

Try
    Dim xmlDoc As System.Xml.XmlDocument = New System.Xml.XmlDocument
    xmlDoc.XmlResolver = Nothing

    xmlDoc.Load("c:\path\file4.xml")

    Dim sXML As String = "file" & xmlDoc.InnerXml '<- This is where I try to put the "KEY"

    Dim url As String = "http:/host.com+URI"

    req = CType(WebRequest.Create(url), Net.HttpWebRequest) 'or Directcast ...
    req.Method = "POST"
    req.Headers.Add("Authorization: Basic " & EncodedString)
    req.ContentType = "multipart/form-data"
    req.ContentLength = sXML.Length
    req.Accept = "*/*"

    System.Windows.Forms.Application.DoEvents()

    Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(req.GetRequestStream)
    StatusUpdate(sXML)
    sw.Write(sXML)
    sw.Close()
    ss = "server says: "
    res = CType(req.GetResponse, HttpWebResponse)
     StatusUpdate(req.ToString)
    Catch ex As Exception
        StatusUpdate(ss & ex.Message)
    Finally

End Try

Is it because I am trying to send it as a string? (but how else can I send it as a file?)
For this I made another procedure that sends the bytes of data, but this one also gives me "400" because (I assume) I did not put the "file" key.
    Dim requestStream As Stream = Nothing
    Dim fileStream As FileStream = Nothing
    Dim uploadResponse As Net.HttpWebResponse = Nothing

    Try

        Dim uploadRequest As Net.HttpWebRequest = CType(Net.HttpWebRequest.Create(URI.Text & Uri_part2.text), Net.HttpWebRequest)

        uploadRequest.Method = Net.WebRequestMethods.Http.Post
        uploadRequest.ContentType = "text/xml; charset=utf-8"
        uploadRequest.Credentials = New NetworkCredential("user", "pass")
        uploadRequest.KeepAlive = True
        uploadRequest.UserAgent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10"
        uploadRequest.Accept = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
        uploadRequest.Headers.Add("Accept-Language: en-us,en;q=0.5")
        uploadRequest.Headers.Add("Accept-Encoding: gzip,deflate")
        uploadRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
        uploadRequest.Headers.Add("Content-Disposition: form-data; name=""file"";")
        uploadRequest.ContentType = "application/xml; charset=utf-8"

        requestStream = uploadRequest.GetRequestStream()
        fileStream = File.Open("C:\example.xml", FileMode.Open)

        Dim a As Integer

        Dim buffer(1024) As Byte
        Dim bytesRead As Integer
        While True
            a = a + 1
            bytesRead = fileStream.Read(buffer, 0, buffer.Length)
            StatusUpdate(buffer(a))

            If bytesRead = 0 Then
                Exit While
            End If
            requestStream.Write(buffer, 0, bytesRead)

        End While

       requestStream.Close()

        uploadResponse = uploadRequest.GetResponse()
        Dim responseReader As StreamReader = New StreamReader(uploadRequest.GetResponse.GetResponseStream())
        Dim x As String = responseReader.ReadToEnd()
        responseReader.Close()
        StatusUpdate(x)

    Catch ex As UriFormatException
        StatusUpdate("UriFormatException: " & ex.Message)
    Catch ex As IOException
        StatusUpdate("IOException: " & ex.Message)
    Catch ex As Net.WebException
        StatusUpdate("Net.WebException: " & ex.Message)

    Finally

        If uploadResponse IsNot Nothing Then
            uploadResponse.Close()
        End If

        If fileStream IsNot Nothing Then
            fileStream.Close()
        End If

        If requestStream IsNot Nothing Then
            requestStream.Close()
        End If

    End Try

In any case, I tried also other 2 clients (POSTMAN and REST Console, 2 extensions for Google Chrome) and I can get it working only if I add the value "file" into the "key" field. I have to insert the specific 4 chars "file" to get it working. So, the question is: how do I add the same value in a Vb.net call? How can I translate the code of the cURL call in working Vb.net code? Thank you very much for your time and help!!!
find image of the thing I want to add here,
P.S. I cannot use PUT, I have to use POST (server restriction)
I also add HTML code that is working for my purpose, with the server from my pc (see the "file" key, again)

<form enctype="multipart/form-data" action="http://URI" method="POST">

File
<input type="FILE" name="file">

<input type="submit">

</form>

Also I paste a script in PERL that is working, too, with the server, from my computer.
  #!perl

use strict;
use LWP; # Loads all important LWP classes

my $client_id         = 1234;
my $filename          = "new_file.xml";

### Prepare to make a request

my $browser = LWP::UserAgent->new;

my $url = "http://uri.com?&xx=$client_id";

my @post_pairs = (
    #'client_id_in' => $client_id,
    'file' => [$filename],
);

my @ns_headers = (
    'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10',
    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language' => 'en-us,en;q=0.5',
    'Accept-Encoding' => 'gzip,deflate',
    'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'Authorization' => 'Basic base64EncodedCredentialsHere',
    'Content_Type' => 'form-data',
);

### Make a request
my $response = $browser->post($url, \@post_pairs, @ns_headers);
die "Can't get $url -- ", $response->status_line
        unless $response->is_success;

### Display the response
print STDOUT $response->content;

A: I think your problem is that you don't really know how the request should look like, please use fiddler to take a look to the request sent by cURL and try to implement the same using vb.net. In my opinion your secons piece of code (with the buffer, not with the xml serializers) should work... but only if this structure can be understood at the server side.


text:
Q: Alertify alert confirm dialogs not working with Ruby on Rails This is alertifyJS and I need to implement this with rails.
I have downloaded this JS and CSS file and put into that assets/javascripts/modules/alertify.js assets/stylsheets/modules/alertify.css
assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require modules/alertify

assets/stylsheets/application.css
 *= require modules/alertify

View
<%= link_to "Go!", new_employer_session_path, data: {confirm: "Are you sure? "} %>

But confirm dialogs not working.
What can I do now.
Thanks

A: Ok Try the following if your JS and CSS working correctly
You need to declare method what method you need to action like below
I think this is a GET method then see this, you can change to anything that's your method
<%= link_to "Go!", new_employer_session_path, method: :get, data: {confirm: "Are you sure? "} %>
#=> declare a method :get, :post or :delete

Without declaring a method it's won't work
And add some JS code to your JS file application.js
$.rails.allowAction = function(element){
    if( undefined === element.attr('data-confirm') ){
        return true;
    }

    $.rails.showConfirmDialog(element);
    return false;
};

$.rails.confirmed = function(element){
    element.removeAttr('data-confirm');
    element.trigger('click.rails');
};

$.rails.showConfirmDialog = function(element){
    var msg = element.data('confirm');
    alertify.confirm(msg, function(e){
        if(e){
            $.rails.confirmed(element);
            return true;
        }
    })
};

Hope it helps

A: This is what you need to do, STEP BY STEP:
1) Add this to the gem file:
gem 'alertifyjs-rails'

2) Add this to /app/assets/javascripts/application.js
//= require alertify

3) Add this to /app/assets/stylesheets/application.css
 *= require alertify
 *= require alertify/default
 *= require alertify/bootstrap

4) Add this at the end of /app/assets/javascripts/application.js
It is necessary to make alertify work with the existing code.
$.rails.allowAction = function(element){
    if( undefined === element.attr('data-confirm') ){
        return true;
    }

    $.rails.showConfirmDialog(element);
    return false;
};

$.rails.confirmed = function(element){
    element.removeAttr('data-confirm');
    element.trigger('click.rails');
};

$.rails.showConfirmDialog = function(element){
    var company_name = "Your Company Name Security Confirmation";
    var msg = element.data('confirm');

    alertify.confirm(msg, function(e){
        if(e){
            $.rails.confirmed(element);
            return true;
        }
    }).set({title: company_name}).set('onfocus', function(){
        document.activeElement.blur();
    });

};

The last set (.set('onfocus',...) makes possible to avoid the focus in
  any of the buttons of the dialog. It looks prettier this way, but you
  don't need to use it if you don't like it.

5) Go to the root of the project and run in the terminal:
bundle
6) Go to the terminal with the server running and stop the sever with: CTRL + C
7) Run the server again with:
rails server
8) Refresh the page in the web browser. It should work with your already existing code.
I hope this help!


text:
Q: Can't install enterprise app on device with iOS 9 GM seed I'm trying to install an enterprise app over the air on ipad 2 device with iOS 9 GM seed. iOS shows download progress, after downloading there is an error "Can't install".
It worked with the last iOS 9 beta
There is a log from console:
Sep 10 04:12:25 iPad-Dashboard ondemandd[145] <Error>: Application with ID: M3KJ3WBD2L.com.boardmaps.boardmaps was installed, but it doesn't appear to have a bundle URL, we are taking no action on this.
Sep 10 04:12:27 iPad-Dashboard ondemandd[145] <Error>: An object with ID [0x15e74230 <x-coredata:///AssetDownloads/t7E19FE36-172C-43EF-90EC-1B069309CF8B16>] has already registered.
Sep 10 04:12:27 iPad-Dashboard itunesstored[116] <Warning>: LaunchServices: Creating installProgressForApplication:<LSApplicationProxy: 0x14deb5f0> M3KJ3WBD2L.com.boardmaps.boardmaps (Placeholder) <file:///private/var/mobile/Containers/Bundle/Application/7312DC34-DF53-43BA-AE3E-DEA05EBF014D/-4088318364755750305.app> withPhase:0
Sep 10 04:12:27 iPad-Dashboard lsd[74] <Warning>: LaunchServices: Updating installPhase for parent <NSProgress: 0x16586090> : Parent: 0x0 / Fraction completed: 0.6000 / Completed: 60 of 100   to 0
Sep 10 04:12:27 iPad-Dashboard SpringBoard[47] <Warning>: HW kbd: Failed to set (null) as keyboard focus
Sep 10 04:12:28 iPad-Dashboard MobileSafari[137] <Warning>: Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.
Sep 10 04:12:47 iPad-Dashboard itunesstored[116] <Warning>: [Download]: Download task did finish: 5 for download: -4088318364755750305
Sep 10 04:12:47 iPad-Dashboard itunesstored[116] <Warning>: [ApplicationWorkspace] Installing download: -4088318364755750305 with step(s): Install
Sep 10 04:12:47 iPad-Dashboard itunesstored[116] <Warning>: [ApplicationWorkspace]: Installing software package with bundleID: M3KJ3WBD2L.com.boardmaps.boardmaps: bundleVersion: 1.1.18.1100 path: /var/mobile/Media/Downloads/-4088318364755750305/8091709402150391677
Sep 10 04:12:50 iPad-Dashboard itunesstored[116] <Warning>: BundleValidator: Failed bundleIdentifier: M3KJ3WBD2L.com.boardmaps.boardmaps does not match expected bundleIdentifier: com.boardmaps.boardmaps
Sep 10 04:12:50 iPad-Dashboard itunesstored[116] <Warning>: [ApplicationWorkspace]: Bundle validated for bundleIdentifier: M3KJ3WBD2L.com.boardmaps.boardmaps success: 0
Sep 10 04:12:50 iPad-Dashboard itunesstored[116] <Warning>: LaunchServices: Uninstalling placeholder for app <LSApplicationProxy: 0x16095af0> M3KJ3WBD2L.com.boardmaps.boardmaps (Placeholder) <file:///private/var/mobile/Containers/Bundle/Application/7312DC34-DF53-43BA-AE3E-DEA05EBF014D/-4088318364755750305.app>
Sep 10 04:12:50 iPad-Dashboard itunesstored[116] <Warning>: LaunchServices: Uninstalling app <LSApplicationProxy: 0x16095af0> M3KJ3WBD2L.com.boardmaps.boardmaps (Placeholder) <file:///private/var/mobile/Containers/Bundle/Application/7312DC34-DF53-43BA-AE3E-DEA05EBF014D/-4088318364755750305.app>
Sep 10 04:12:50 iPad-Dashboard installd[42] <Notice>: 0x1f081000 -[MIClientConnection uninstallIdentifiers:withOptions:completion:]: Uninstall requested by itunesstored (pid 116) with options: {
    }
Sep 10 04:12:50 iPad-Dashboard installd[42] <Notice>: 0x1f081000 -[MIUninstaller _uninstallBundleWithIdentifier:error:]: Uninstalling identifier M3KJ3WBD2L.com.boardmaps.boardmaps
Sep 10 04:12:50 iPad-Dashboard installd[42] <Notice>: 0x1f081000 -[MIUninstallNotifier performRemovalWithCompletionBlock:]: Destroying container with identifier M3KJ3WBD2L.com.boardmaps.boardmaps at /private/var/mobile/Containers/Bundle/Application/7312DC34-DF53-43BA-AE3E-DEA05EBF014D
Sep 10 04:12:50 iPad-Dashboard installd[42] <Notice>: 0x1f081000 -[MIUninstallNotifier performRemovalWithCompletionBlock:]: Destroying container with identifier M3KJ3WBD2L.com.boardmaps.boardmaps at /private/var/mobile/Containers/Data/Application/B7AD1744-EB1F-42D3-8690-F1FB4B2DA526
Sep 10 04:12:51 iPad-Dashboard itunesstored[116] <Warning>: LaunchServies: No app bundle to remove for M3KJ3WBD2L.com.boardmaps.boardmaps
Sep 10 04:12:51 iPad-Dashboard lsd[74] <Warning>: LaunchServices: Updating identifier store
Sep 10 04:12:51 iPad-Dashboard itunesstored[116] <Warning>: LaunchServices: clearing created progress for M3KJ3WBD2L.com.boardmaps.boardmaps
Sep 10 04:12:51 iPad-Dashboard itunesstored[116] <Warning>: [ApplicationWorkspace]: Uninstalling application placeholder for bundleIdentifier: M3KJ3WBD2L.com.boardmaps.boardmaps; success: 1
Sep 10 04:12:51 iPad-Dashboard itunesstored[116] <Warning>: [ApplicationWorkspace]: Failed to install application: M3KJ3WBD2L.com.boardmaps.boardmaps; /var/mobile/Media/Downloads/-4088318364755750305/8091709402150391677; Error Domain=SSErrorDomain Code=143 "(null)"

A: Also seeing this with TestFairy. TestFairy adds ".download" to the end of your bundle identifier, causing the install to fail on devices that have iOS 9 GM pre-seed installed. This wasn't a problem with iOS 8 nor with the iOS 9 betas...

A: We found that removing the team prefix from the bundle-id helped with some downloads, but for others we had to rebuild the .ipa in XCode 7.

A: You might have had the same issue with OTA installations with iOS8 and implemented the workaround on server side: You changed the bundle ID in the plist manifest file and added board maps to it. We added .dummy to make it working with iOS 8.1
BundleValidator: Failed bundleIdentifier: M3KJ3WBD2L.com.boardmaps.boardmaps does not match expected bundleIdentifier: com.boardmaps.boardmaps
Unfortunately, it does not work with iOS 9 anymore. We ned to change the logic on server side again to differentiate between iOS 8 and 9 while the plist file is being generated.
Cheers!

A: In a nutshell, go back to the way things were done pre 8.1.3.  As soon as I rebuilt our (non-downloading) enterprise apps using the 'old' techniques, they all started being downloadable OTA on 9.0
It's a bit of a PITA in as much as we now need an 8.1.3 >= < 9.0 build as well as a >= 9.0 build, but hey ho, that's Apple...

A:
iOS 9 became more strict with the manifest information:the tag,the
  value,or something else.

I have met the similar problem these days:
I find the problem is that I mistake the bundle-identifier value.

I find if you mistake the bundle-identifier value,the iOS 9 will not allow you to install the app,but iOS 8 or lower version will not check bundle-identifier value.

A: I noticed the same issue with iOS 9 GM. I eventually find out that the problem was caused by the zip version of the ipa.
I was using a Java library to generate the ipa. Now I use /usr/bin/zip to generate the ipa and it solves my problem.
Using file command I can see that both zip tools are not generating the same zip version :
$ file working_with_ios9gm.ipa
working_with_ios9gm.ipa: Zip archive data, at least v1.0 to extract

$ file not_working_with_ios9gm.ipa
not_working_with_ios9gm.ipa: Zip archive data, at least v2.0 to extract

A: I got the same error, sat until maybe 4 AM. Some sleep and coffee, and I spotted it:
in the manifest.plist, there are 3 assets dictionary entries:
"software-package","full-size-image","display-image".
The "full-size-image" entry had a comma instead of a point in the URL:
<string>https://www.myserver,com/AppIcon512.png</string>
Changed to a point and now adhoc downloading works again :-)

A: I had the same problem. Fixed it by setting the bundler-identifier value to the exact value that is set in the xcode build settings.

A: In my case, I was using a special character in the ipa file name. Finally I removed the special character (é) and I deployed again, and it worked fine.


text:
Q: C++ Error: Line 1440 Expression: string subscript out of range The program builds and runs, however after entering the first integer and pressing enter then the error pop up box appears, then after pressing ignore and entering the second integer and pressing enter the pop up box appears and after pressing ignore it returns the correct answer. I am at my wits end with this can somebody help me fix the pop up box thing.
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
#define numbers 100

class largeintegers {
public:
    largeintegers();
    void
    Input();
    void
    Output();
    largeintegers
    operator+(largeintegers);
    largeintegers
    operator-(largeintegers);
    largeintegers
    operator*(largeintegers);
    int
    operator==(largeintegers);
private:
    int integer[numbers];
    int len;
};

void largeintegers::Output() {
    int i;
    for (i = len - 1; i >= 0; i--)
        cout << integer[i];
}

void largeintegers::Input() {
    string in;
    int i, j, k;
    cout << "Enter any number:";
    cin >> in;
    for (i = 0; in[i] != '\0'; i++)
        ;
    len = i;
    k = 0;
    for (j = i - 1; j >= 0; j--)
        integer[j] = in[k++] - 48;
}

largeintegers::largeintegers() {
    for (int i = 0; i < numbers; i++)
        integer[i] = 0;
    len = numbers - 1;
}

int largeintegers::operator==(largeintegers op2) {
    int i;
    if (len < op2.len) return -1;
    if (op2.len < len) return 1;
    for (i = len - 1; i >= 0; i--)
        if (integer[i] < op2.integer[i])
            return -1;
        else if (op2.integer[i] < integer[i]) return 1;
    return 0;
}

largeintegers largeintegers::operator+(largeintegers op2) {
    largeintegers temp;
    int carry = 0;
    int c, i;
    if (len > op2.len)
        c = len;
    else
        c = op2.len;

    for (i = 0; i < c; i++) {
        temp.integer[i] = integer[i] + op2.integer[i] + carry;
        if (temp.integer[i] > 9) {
            temp.integer[i] %= 10;
            carry = 1;
        } else
            carry = 0;
    }
    if (carry == 1) {
        temp.len = c + 1;
        if (temp.len >= numbers)
            cout << "***OVERFLOW*****\n";
        else
            temp.integer[i] = carry;

    } else
        temp.len = c;
    return temp;
}
largeintegers largeintegers::operator-(largeintegers op2) {
    largeintegers temp;
    int c;
    if (len > op2.len)
        c = len;
    else
        c = op2.len;
    int borrow = 0;
    for (int i = c; i >= 0; i--)
        if (borrow == 0) {
            if (integer[i] >= op2.integer[i])
                temp.integer[i] = integer[i] - op2.integer[i];
            else {
                borrow = 1;
                temp.integer[i] = integer[i] + 10 - op2.integer[i];
            }
        } else {
            borrow = 0;
            if (integer[i] - 1 >= op2.integer[i])
                temp.integer[i] = integer[i] - 1 - op2.integer[i];
            else {
                borrow = 1;
                temp.integer[i] = integer[i] - 1 + 10 - op2.integer[i];
            }
        }
    temp.len = c;
    return temp;
}
largeintegers largeintegers::operator*(largeintegers op2) {
    largeintegers temp;
    int i, j, k, tmp, m = 0;
    for (i = 0; i < op2.len; i++) {
        k = i;
        for (j = 0; j < len; j++) {
            tmp = integer[j] * op2.integer[i];
            temp.integer[k] = temp.integer[k] + tmp;
            temp.integer[k + 1] = temp.integer[k + 1] + temp.integer[k] / 10;
            temp.integer[k] %= 10;
            k++;
            if (k > m) m = k;
        }
    }
    temp.len = m;
    if (temp.len > numbers) cout << "***OVERFLOW*****\n";
    return temp;
}

using namespace std;
int main() {
    int c;
    largeintegers num1, num2, result;
    num1.Input();
    num2.Input();
    num1.Output();
    cout << " + ";
    num2.Output();
    result = num1 + num2;
    cout << " = ";
    result.Output();
    cout << "\n\n";
    num1.Output();
    cout << " - ";
    num2.Output();
    result = num1 - num2;
    cout << " = ";
    result.Output();
    cout << "\n\n";
    num1.Output();
    cout << " * ";
    num2.Output();
    result = num1 * num2;
    cout << " = ";
    result.Output();
    cout << "\n\n";
    c = num1 == num2;
    num1.Output();
    switch (c) {
    case -1:
        cout << " is less than ";
        break;
    case 0:
        cout << " is equal to ";
        break;
    case 1:
        cout << " is greater than ";
        break;
    }
    num2.Output();
    cout << "\n\n";
    system("pause");
}

A: It seems you are falling victim to the difference between C-style strings and C++ strings.  C-style strings are a series of chars followed by a zero (or null) byte.  C++ strings are objects that contain a series of characters (usually char, but eventually this will be an assumption you should break) and that know their own length.  C++ strings can contain null bytes in the middle of themselves without problem.
To loop through all of the characters of a C++-style string, you can do one of a number of things:

*

*You can use the .size() or .length() members of a string variable to find the number of characters in it, as in for (int i=0; i<str.size(); i++) { char c = str[i];

*You can use .begin() and .end() to get iterators to the beginning and end of the string, respectively.  A for loop in the form for (std::string::iterator it=str.begin(); it!=str.end(); ++it) will loop you through the members of the string by accessing *it.

*If you're using C++11, you can use the for loop construct as follows: for (auto c: str) where c will be of the type of a character of the string str.

In the future, to solve problems like these, you can try using the debugger to see what happens when your program crashes or hits an exception.  You likely would find that inside of largeintegers::Input() you running into either a memory access violation or some other problem.
Finally, as a future-looking criticism, you should not use C-style arrays (where you say int integer[ numbers ];) in favor of using C++-style containers, such as vector.  A vector is a series of objects (such as ints) that can expand as needed.


text:
Q: Wireless not connecting on Ubuntu 13.10, Toshiba Satellite pro L 650 I have just installed Ubuntu 13.10 on my Toshiba Satellite Pro L650. After several reboots, installing/ uninstalling the broadcom driver  I still can't connect.
It detects the wi fi signals and the icon flashes as if it's trying to connect but never actually does.
I'm really  quite rubbish with code and stuff, but I really like Ubuntu as an OS and would really appreciate any suggestions anyone can offer!
02:00.0 Ethernet controller: Qualcomm Atheros AR8151 v1.0 Gigabit Ethernet (rev c0)
03:00.0 Network controller: Broadcom Corporation BCM4313 802.11bgn Wireless Network Adapter (rev 01)

A: Please try:
sudo apt-get purge bcmwl-kernel-source
sudo modprobe -rv wl
sudo modprobe -v brcmsmac

if there are any errors please continue with the commands then reboot. If you have not installed any other drivers but the wl driver then your wireless should be working.


text:
Q: How to use bg in grDevices::pdf to cover the entire page when paper != special? When I change the value of paper parameter in pdf() from default value 'special' to something else (for example a4 or a4r), bg color does not cover the entire page.
I have tries changing the width, height and pagecentre parameters, but it doesn't work as expected.
grDevices::pdf("test.pdf", pagecentre = T, bg = "grey", onefile=TRUE, paper = "a4r", height = 12, width = 18)
plot(1:5,1:5)
dev.off()

Background color when paper style is 'special':
Img1
Background color when paper style is not 'special':
Img2


text:
Q: How can I format Date range to "MMM, d"? I am trying to display the week number of current date, and the date range of the week number. Right now the date range format is DateTime, I would like to change it to "Jan 13"instead. Any recommendations on how I can fix this?
override func viewDidLoad() {
    super.viewDidLoad()

    let dateToday = Date()
    let weekNumber = NSCalendar.current.component(.weekOfYear, from: dateToday)
    let weekRange = dayRangeOf(weekOfYear: weekNumber, for: dateToday)

    weekLabel.text = String("Week #\(weekNumber): \(weekRange)")
}

func dayRangeOf(weekOfYear: Int, for date: Date) -> Range<Date>
{
    let calendar = Calendar.current
    let year = calendar.component(.yearForWeekOfYear, from: date)
    let startComponents = DateComponents(weekOfYear: weekOfYear, yearForWeekOfYear: year)
    let startDate = calendar.date(from: startComponents)!
    let endComponents = DateComponents(day:7, second: -1)
    let endDate = calendar.date(byAdding: endComponents, to: startDate)!
    return startDate..<endDate
}

A: There is a dedicated API to display date intervals: DateIntervalFormatter
let intervalForatter = DateIntervalFormatter()
intervalFormatter.timeStyle = .none
intervalFormatter.dateStyle = .medium
weekLabel.text = String("Week #\(weekNumber): \(intervalFormatter.string(from: weekRange.lowerBound, to: weekRange.upperBound))")

You can also use a custom date format (by the way Jan 13 is MMM d)
let intervalFormatter = DateIntervalFormatter()
intervalFormatter.dateTemplate = "MMM d"
let text = String("Week #\(weekNumber): \(intervalFormatter.string(from: weekRange.lowerBound, to: weekRange.upperBound))")

A: You can user answer from:
Date Format in Swift
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MM d"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}


text:
Q: Talend Open Studio on Mac OS X - Failed to create JVM I want to start the Talend Open Studio (ESB or DI) on my Mac Pro.
But I get an error: "Failed to create the Java Virtual Machine".
TOS Version is V5.6.0 and I have installed Java SDK 1.7.0_45 64-Bit.
I have also changed some values in TOS_ESB-macosx-cocoa.ini:
--launcher.XXMaxPermSize
512m
-vmargs
-Xms64m
-Xmx768m
-Xdock:icon=../Resources/talend.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dosgi.instance.area.default=../../../workspace
-Dfile.encoding=UTF-8

But I still get the same error.
I found that TOS use the wrong java version
    JavaVM: Failed to load JVM: /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/bundle/Libraries/libserver.dylib
My JAVA_HOME is set to /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
How do I resolve this?

A: It depend on that Problem https://code.google.com/p/android/issues/detail?id=65730.
I set the the link to libjvm.dylib in jre home and than TOS is starting.


text:
Q: How do I compact a VMWare virtual hard drive? I'm using VMWare ESX to host some VMs, and have allocated 60Gb to one Windows Server 2008 VM.  It's not using close to that and is unlikely to.
How can I reduce the amount of space that this virtual disk takes up on the physical disk?  I've heard words like Thin Disk and compact bandied about, but haven't had a chance to look properly yet (running out of room is not yet a pressing concern).

A: Thin\Thick format are generally the terms VMware uses for the VMDK formats - thin will dynamically grow (up to the limit) as space is actually consumed, thick is pre-allocated. Compact is usually used to describe a thin storage format used for Templates.
To convert an existing thick format VMDK to thin format your options are:
1. If you have vCenter and a license that includes Storage VMotion you can convert from thick format to thin format without downtime using that.
2. Use VMware Converter - this will allow you to create a new VM that is a copy of the original but with thin disks rather than thick\fully allocated ones. This will incur some downtime.
3. Use vmkfstools from the command line. This requires the most downtime of all of the solutions. Shut the VM down and from the ESX Console navigate to the relevant VM directory and use the following command:
vmkfstools -i yourthickdisk.vmdk -d thin yourthindisk.vmdk

This clones the original vmdk (the -i flag) but the -d flag specifies that the clone should be a thin format disk.
Once the clone is complete edit the VM config to point the new thin disk vmdk. If everything starts up OK you can safely remove the old (thick) VMDK.
4. There is a variation on the vmkfstools option detailed in this blog post using a snapshot to allow you to make the conversion on a running VM. I'm pretty sure that wouldn't be supported by VMware but it's a neat hack.


text:
Q: Android socket programing I am trying to make a simple Android app to send strings over WiFi to a microcontroller that will later on be used as commands to turn an led on and off.
Below is the code that I have and I am having issues with understanding why it doesn't work.
Basically an exception is thrown and the "connection failed" toast is envoked.
     String hostname = "192.168.50.1";
     int port = 5001;
     PrintWriter out = null;

     //access_point.connect(new InetSocketAddress(hostname, port));

    public void command() throws Exception {

        try{
             Socket access_point = new Socket(hostname,port);
            out = new PrintWriter(access_point.getOutputStream(), true);
            out.println("Turn on");
            Toast.makeText(getBaseContext(), "Connection successful", Toast.LENGTH_LONG).show();
        //  BufferedReader in = new BufferedReader(new InputStreamReader(access_point.getInputStream()));
        }
        catch(Exception e){

            Toast.makeText(getBaseContext(), "Connection failed", Toast.LENGTH_LONG).show();

        }

    }

     ToggleButton tbutton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);

        // code for toggle button
        tbutton = (ToggleButton) findViewById(R.id.toggleButton1);
        tbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(((ToggleButton)v).isChecked())
                {
                    try{
                        command();
                        Toast.makeText(getBaseContext(), "Communication ON string sent", Toast.LENGTH_SHORT).show();
                    }

                    catch(Exception e)
                    {
                        Toast.makeText(getBaseContext(), "Communication failed", Toast.LENGTH_LONG).show();
                    }

                }
                else
                {
                    Toast.makeText(getBaseContext(), "Communication OFF string sent", Toast.LENGTH_LONG).show();
                }
              }
            });
        }
}

A: Rather than just throwing a toast, you should use
    Log.d(getClass().getSimpleName(), "Connection failed", exception);

The likely problem you have is that you are running a network connection on the main thread, which can freeze the application on a timeout, hence why the Android OS does not allow it.
Check out this question for more information on how to run the network connection on a different thread, and fix your problem: Using AsyncTask for android network connection