text:
Q: PowerShell's pipe adds linefeed I'm trying to pipe a string into a program's STDIN without any trailing linefeeds (unless that string itself actually ends in a linefeed). I tried googling around, but I only found people trying to print to the console without a trailing linefeed, in which case Write-Host takes a parameter -NoNewLine. However, to pipe it on to another program, I need Write-Output or similar which doesn't have such a parameter. Now it seems like Write-Output isn't even the problem:
Z:\> (Write-Output "abc").Length
3

But as soon as I pipe it to another program and read the string there, I get an additional linefeed. For instance, I tried this Ruby snippet:
Z:\> Write-Output "abc" | ruby -e "p ARGF.read"
"abc\n"

I checked that the actual string received is abc\n. The same happens in several other languages (at least C#, Java and Python), so I believe it's an issue with PowerShell, not the language doing the reading.
As a further test, I replaced Write-Output itself with another Ruby script:
Z:\> ruby -e "$> << 'abc'"
abcZ:\>

(That is, there is definitely no \n on the script's STDOUT.)
But again, when I pipe it into another script:
Z:\> ruby -e "$> << 'abc'" | ruby -e "p ARGF.read"
"abc\n"

I'm fairly convinced that it's the pipe which adds the linefeed. How do I avoid that? I actually want to be able to control whether the input ends in a linefeed or not (by including it in the input or omitting it).
(For reference, I also tested strings which already contain a trailing linefeed, and in that case the pipe doesn't add another one, so I guess it just ensures a trailing linefeed.)
I originally encountered this in PowerShell v3, but I'm now using v5 and still have the same issue.

A: Bruteforce approach: feed binary data to process' stdin. I've tested this code on the cat.exe from UnixUtils and it seems to do what you want:
# Text to send
$InputVar = "No Newline, No NewLine,`nNewLine, No NewLine,`nNewLine, No NewLine"

# Buffer & initial size of MemoryStream
$BufferSize = 4096

# Convert text to bytes and write to MemoryStream
[byte[]]$InputBytes = [Text.Encoding]::UTF8.GetBytes($InputVar)
$MemStream = New-Object -TypeName System.IO.MemoryStream -ArgumentList $BufferSize
$MemStream.Write($InputBytes, 0, $InputBytes.Length)
[Void]$MemStream.Seek(0, 'Begin')

# Setup stdin\stdout redirection for our process
$StartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo -Property @{
                FileName = 'MyLittle.exe'
                UseShellExecute = $false
                RedirectStandardInput = $true
            }

# Create new process
$Process = New-Object -TypeName System.Diagnostics.Process

# Assign previously created StartInfo properties
$Process.StartInfo = $StartInfo
# Start process
[void]$Process.Start()

# Pipe data
$Buffer = New-Object -TypeName byte[] -ArgumentList $BufferSize
$StdinStream = $Process.StandardInput.BaseStream

try
{
    do
    {
        $ReadCount = $MemStream.Read($Buffer, 0, $Buffer.Length)
        $StdinStream.Write($Buffer, 0, $ReadCount)
        $StdinStream.Flush()
    }
    while($ReadCount -gt 0)
}
catch
{
    throw 'Houston, we have a problem!'
}
finally
{
    # Close streams
    $StdinStream.Close()
    $MemStream.Close()
}

# Cleanup
'Process', 'StdinStream', 'MemStream' |
    ForEach-Object {
        (Get-Variable $_ -ValueOnly).Dispose()
        Remove-Variable $_ -Force
    }

A: Do it a simple way create a cmd process and execute it
$cmdArgs = @('/c','something.exe','arg1', .. , 'arg2' , $anotherArg , '<', '$somefile.txt' )
&'cmd.exe' $cmdArgs

Worked perfect for piping information into stdin that I wanted,

A: To clear up a fundamental misconception in some of the comments: the "powershell commands" in a pipeline are cmdlets and each one runs within the process space of the single powershell. Thus, objects are being passed as is within the same process (on multiple threads) UNLESS you invoke an external command. Then the passed objects are converted to strings by the appropriate formatting cmdlet (if not already string objects). These strings are then converted to a stream of characters with each string having an appended \n. So it is not "the pipeline" adding the \n but the implicit conversion to text for input to the "legacy" command.
The basic problem in the question is that the asker is trying to get object like behaviour (e.g. a string with no trailing \n) on a character (byte) stream input. The standard input stream of a (console) process supplies characters (bytes) one at a time. The input routines collect these individual characters into a single string (typically) terminated when a \n is received. Whether the \n is returned as part of the string is up to the input routine. When the standard input stream is redirected to a file or pipe, the input routines mostly have no knowledge of this. So there is no way to determine the difference between a complete string with no \n and an incomplete string with more characters and the \n still to come.
Possible solutions (to the string delimiting problem, not the powershell added \n problem) would be to have some sort of time-out on the standard input reads. The end of a string could be signaled by no received characters for a certain time. Alternatively, if you had low enough level access to the pipe you could try to have atomic reads and writes. In this way a blocked read would return exactly what was written. Unfortunately, both of these methods have timing problems when running within a multitasking environment. If the delay is long then efficiency falls but if it is too short then it can be fooled by delays caused by process priority scheduling. Scheduling priorities can also interfere with atomic reads and writes if the writing process writes another line before the reading process has read the current one. It would need some sort of synchronizing system.
The only other way to signal that there are no more characters coming on the current line would be to close the pipe (EOF) but this is a once only method so you can only send one string (trailing \n or not). (This is how Ruby knows when the input is finished both in the initial example and in the Invoke-RawPipeline example.) It is possible that this is actually your intention (send only one string with or without trailing \n) in which case you could simply concatenate all the input (retaining or re-inserting any embedded \n) and throw away the last \n.
A possible solution to the powershell added \n problem for multiple strings would be to redefine your encoding of "a string" by terminating each string object with an otherwise invalid character sequence. \0 could be used if you had per character input (no good for C-like line input) otherwise maybe \377 (0xff). This would allow the input routines of your legacy command to "know" when a string ended. The sequence \0\n (or \377\n) would be the "end" of the string and everything before that (including a trailing \n or not, possibly using multiple reads) would be the string. I am assuming that you have some control over the input routines (e.g. you wrote the program) since any off the shelf program reading from standard input would typically be expecting a \n (or EOF) to delimit its input.

A: Introduction
Here is my Invoke-RawPipeline function (get latest version from this Gist).
Use it to pipe binary data between processes' Standard Output and Standard Input streams. It can read input stream from file/pipeline and save resulting output stream to file.
It requires PsAsync module to be able to launch and pipe data in multiple processes.
In case of issues use -Verbose switch to see debug output.
Examples
Redirecting to file

*

*Batch:
findstr.exe /C:"Warning" /I C:\Windows\WindowsUpdate.log > C:\WU_Warnings.txt

*PowerShell:
Invoke-RawPipeline -Command @{Path = 'findstr.exe' ; Arguments = '/C:"Warning" /I C:\Windows\WindowsUpdate.log'} -OutFile 'C:\WU_Warnings.txt'
Redirecting from file

*

*Batch:
svnadmin load < C:\RepoDumps\MyRepo.dump

*PowerShell:
Invoke-RawPipeline -InFile 'C:\RepoDumps\MyRepo.dump' -Command @{Path = 'svnadmin.exe' ; Arguments = 'load'}
Piping strings

*

*Batch:
echo TestString | find /I "test" > C:\SearchResult.log

*PowerShell:
'TestString' | Invoke-RawPipeline -Command @{Path = 'find.exe' ; Arguments = '/I "test"'} -OutFile 'C:\SearchResult.log'
Piping between multiple processes

*

*Batch:
ipconfig | findstr /C:"IPv4 Address" /I

*PowerShell:
Invoke-RawPipeline -Command @{Path = 'ipconfig'}, @{Path = 'findstr' ; Arguments = '/C:"IPv4 Address" /I'} -RawData
Code:
<#
.Synopsis
    Pipe binary data between processes' Standard Output and Standard Input streams.
    Can read input stream from file and save resulting output stream to file.

.Description
    Pipe binary data between processes' Standard Output and Standard Input streams.
    Can read input stream from file/pipeline and save resulting output stream to file.
    Requires PsAsync module: http://psasync.codeplex.com

.Notes
    Author: beatcracker (https://beatcracker.wordpress.com, https://github.com/beatcracker)
    License: Microsoft Public License (http://opensource.org/licenses/MS-PL)

.Component
    Requires PsAsync module: http://psasync.codeplex.com

.Parameter Command
    An array of hashtables, each containing Command Name, Working Directory and Arguments

.Parameter InFile
    This parameter is optional.

    A string representing path to file, to read input stream from.

.Parameter OutFile
    This parameter is optional.

    A string representing path to file, to save resulting output stream to.

.Parameter Append
    This parameter is optional. Default is false.

    A switch controlling wheither ovewrite or append output file if it already exists. Default is to overwrite.

.Parameter IoTimeout
    This parameter is optional. Default is 0.

    A number of seconds to wait if Input/Output streams are blocked. Default is to wait indefinetely.

.Parameter ProcessTimeout
    This parameter is optional. Default is 0.

    A number of seconds to wait for process to exit after finishing all pipeline operations. Default is to wait indefinetely.
    Details: https://msdn.microsoft.com/en-us/library/ty0d8k56.aspx

.Parameter BufferSize
    This parameter is optional. Default is 4096.

    Size of buffer in bytes for read\write operations. Supports standard Powershell multipliers: KB, MB, GB, TB, and PB.
    Total number of buffers is: Command.Count * 2 + InFile + OutFile.

.Parameter ForceGC
    This parameter is optional.

    A switch, that if specified will force .Net garbage collection.
    Use to immediately release memory on function exit, if large buffer size was used.

.Parameter RawData
    This parameter is optional.

    By default function returns object with StdOut/StdErr streams and process' exit codes.
    If this switch is specified, function will return raw Standard Output stream.

.Example
    Invoke-RawPipeline -Command @{Path = 'findstr.exe' ; Arguments = '/C:"Warning" /I C:\Windows\WindowsUpdate.log'} -OutFile 'C:\WU_Warnings.txt'

    Batch analog: findstr.exe /C:"Warning" /I C:\Windows\WindowsUpdate.log' > C:\WU_Warnings.txt

.Example
    Invoke-RawPipeline -Command @{Path = 'findstr.exe' ; WorkingDirectory = 'C:\Windows' ; Arguments = '/C:"Warning" /I .\WindowsUpdate.log'} -RawData

    Batch analog: cd /D C:\Windows && findstr.exe /C:"Warning" /I .\WindowsUpdate.log

.Example
    'TestString' | Invoke-RawPipeline -Command @{Path = 'find.exe' ; Arguments = '/I "test"'} -OutFile 'C:\SearchResult.log'

    Batch analog: echo TestString | find /I "test" > C:\SearchResult.log

.Example
    Invoke-RawPipeline -Command @{Path = 'ipconfig'}, @{Path = 'findstr' ; Arguments = '/C:"IPv4 Address" /I'} -RawData

    Batch analog: ipconfig | findstr /C:"IPv4 Address" /I

.Example
    Invoke-RawPipeline -InFile 'C:\RepoDumps\Repo.svn' -Command @{Path = 'svnadmin.exe' ; Arguments = 'load'}

    Batch analog: svnadmin load < C:\RepoDumps\MyRepo.dump
#>

function Invoke-RawPipeline
{
    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({
            if($_.psobject.Methods.Match.('ToString'))
            {
                $true
            }
            else
            {
                throw 'Can''t convert pipeline object to string!'
            }
        })]
        $InVariable,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript({
            $_ | ForEach-Object {
                $Path = $_.Path
                $WorkingDirectory = $_.WorkingDirectory

                if(!(Get-Command -Name $Path -CommandType Application -ErrorAction SilentlyContinue))
                {
                    throw "Command not found: $Path"
                }

                if($WorkingDirectory)
                {
                    if(!(Test-Path -LiteralPath $WorkingDirectory -PathType Container -ErrorAction SilentlyContinue))
                    {
                        throw "Working directory not found: $WorkingDirectory"
                    }
                }
            }
            $true
        })]
        [ValidateNotNullOrEmpty()]
        [array]$Command,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript({
            if(!(Test-Path -LiteralPath $_))
            {
                throw "File not found: $_"
            }
            $true
        })]
        [ValidateNotNullOrEmpty()]
        [string]$InFile,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateScript({
            if(!(Test-Path -LiteralPath (Split-Path $_)))
            {
                throw "Folder not found: $_"
            }
            $true
        })]
        [ValidateNotNullOrEmpty()]
        [string]$OutFile,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$Append,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateRange(0, 2147483)]
        [int]$IoTimeout = 0,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [ValidateRange(0, 2147483)]
        [int]$ProcessTimeout = 0,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [long]$BufferSize = 4096,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$RawData,

        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [switch]$ForceGC
    )

    Begin
    {

        $Modules = @{PsAsync = 'http://psasync.codeplex.com'}

        'Loading modules:', ($Modules | Format-Table -HideTableHeaders -AutoSize | Out-String) | Write-Verbose

        foreach($module in $Modules.GetEnumerator())
        {
            if(!(Get-Module -Name $module.Key))
            {
                Try
                {
                    Import-Module -Name $module.Key -ErrorAction Stop
                }
                Catch
                {
                    throw "$($module.Key) module not available. Get it here: $($module.Value)"
                }
            }
        }

        function New-ConsoleProcess
        {
            Param
            (
                [string]$Path,
                [string]$Arguments,
                [string]$WorkingDirectory,
                [switch]$CreateNoWindow = $true,
                [switch]$RedirectStdIn = $true,
                [switch]$RedirectStdOut = $true,
                [switch]$RedirectStdErr = $true
            )

            if(!$WorkingDirectory)
            {
                if(!$script:MyInvocation.MyCommand.Path)
                {
                    $WorkingDirectory = [System.AppDomain]::CurrentDomain.BaseDirectory
                }
                else
                {
                    $WorkingDirectory = Split-Path $script:MyInvocation.MyCommand.Path
                }
            }

            Try
            {
                $ps = New-Object -TypeName System.Diagnostics.Process -ErrorAction Stop
                $ps.StartInfo.Filename = $Path
                $ps.StartInfo.Arguments = $Arguments
                $ps.StartInfo.UseShellExecute = $false
                $ps.StartInfo.RedirectStandardInput = $RedirectStdIn
                $ps.StartInfo.RedirectStandardOutput = $RedirectStdOut
                $ps.StartInfo.RedirectStandardError = $RedirectStdErr
                $ps.StartInfo.CreateNoWindow = $CreateNoWindow
                $ps.StartInfo.WorkingDirectory = $WorkingDirectory
            }
            Catch
            {
                throw $_
            }

            return $ps
        }

        function Invoke-GarbageCollection
        {
            [gc]::Collect()
            [gc]::WaitForPendingFinalizers()
        }

        $CleanUp = {
            $IoWorkers + $StdErrWorkers |
            ForEach-Object {
                $_.Src, $_.Dst |
                ForEach-Object {
                    if(!($_ -is [System.Diagnostics.Process]))
                    {
                        Try
                        {
                            $_.Close()
                        }
                        Catch
                        {
                            Write-Error "Failed to close $_"
                        }
                        $_.Dispose()
                    }

                }
            }
        }

        $PumpData = {
            Param
            (
                [hashtable]$Cfg
            )
            # Fail hard, we don't want stuck threads
            $Private:ErrorActionPreference = 'Stop'

            $Src = $Cfg.Src
            $SrcEndpoint = $Cfg.SrcEndpoint
            $Dst = $Cfg.Dst
            $DstEndpoint = $Cfg.DstEndpoint
            $BufferSize = $Cfg.BufferSize
            $SyncHash = $Cfg.SyncHash
            $RunspaceId = $Cfg.Id

            # Setup Input and Output streams
            if($Src -is [System.Diagnostics.Process])
            {
                switch ($SrcEndpoint)
                {
                    'StdOut' {$InStream = $Src.StandardOutput.BaseStream}
                    'StdIn' {$InStream = $Src.StandardInput.BaseStream}
                    'StdErr' {$InStream = $Src.StandardError.BaseStream}
                    default {throw "Not valid source endpoint: $_"}
                }
            }
            else
            {
                $InStream = $Src
            }

            if($Dst -is [System.Diagnostics.Process])
            {
                switch ($DstEndpoint)
                {
                    'StdOut' {$OutStream = $Dst.StandardOutput.BaseStream}
                    'StdIn' {$OutStream = $Dst.StandardInput.BaseStream}
                    'StdErr' {$OutStream = $Dst.StandardError.BaseStream}
                    default {throw "Not valid destination endpoint: $_"}
                }
            }
            else
            {
                $OutStream = $Dst
            }

            $InStream | Out-String | ForEach-Object {$SyncHash.$RunspaceId.Status += "InStream: $_"}
            $OutStream | Out-String | ForEach-Object {$SyncHash.$RunspaceId.Status += "OutStream: $_"}

            # Main data copy loop
            $Buffer = New-Object -TypeName byte[] $BufferSize
            $BytesThru = 0

            Try
            {
                Do
                {
                    $SyncHash.$RunspaceId.IoStartTime = [DateTime]::UtcNow.Ticks
                    $ReadCount = $InStream.Read($Buffer, 0, $Buffer.Length)
                    $OutStream.Write($Buffer, 0, $ReadCount)
                    $OutStream.Flush()
                    $BytesThru += $ReadCount
                }
                While($readCount -gt 0)
            }
            Catch
            {
                $SyncHash.$RunspaceId.Status += $_

            }
            Finally
            {
                $OutStream.Close()
                $InStream.Close()
            }
        }
    }

    Process
    {
        $PsCommand = @()
        if($Command.Length)
        {
            Write-Verbose 'Creating new process objects'
            $i = 0
            foreach($cmd in $Command.GetEnumerator())
            {
                $PsCommand += New-ConsoleProcess @cmd
                $i++
            }
        }

        Write-Verbose 'Building I\O pipeline'
        $PipeLine = @()
        if($InVariable)
        {
                [Byte[]]$InVarBytes = [Text.Encoding]::UTF8.GetBytes($InVariable.ToString())
                $PipeLine += New-Object -TypeName System.IO.MemoryStream -ArgumentList $BufferSize -ErrorAction Stop
                $PipeLine[-1].Write($InVarBytes, 0, $InVarBytes.Length)
                [Void]$PipeLine[-1].Seek(0, 'Begin')
        }
        elseif($InFile)
        {
            $PipeLine += New-Object -TypeName System.IO.FileStream -ArgumentList ($InFile, [IO.FileMode]::Open) -ErrorAction Stop
            if($PsCommand.Length)
            {
                $PsCommand[0].StartInfo.RedirectStandardInput = $true
            }
        }
        else
        {
            if($PsCommand.Length)
            {
                $PsCommand[0].StartInfo.RedirectStandardInput = $false
            }
        }

        $PipeLine += $PsCommand

        if($OutFile)
        {
            if($PsCommand.Length)
            {
                $PsCommand[-1].StartInfo.RedirectStandardOutput = $true
            }

            if($Append)
            {
                $FileMode = [System.IO.FileMode]::Append
            }
            else
            {
                $FileMode = [System.IO.FileMode]::Create
            }

            $PipeLine += New-Object -TypeName System.IO.FileStream -ArgumentList ($OutFile, $FileMode, [System.IO.FileAccess]::Write) -ErrorAction Stop
        }
        else
        {
            if($PsCommand.Length)
            {
                $PipeLine += New-Object -TypeName System.IO.MemoryStream -ArgumentList $BufferSize -ErrorAction Stop
            }
        }

        Write-Verbose 'Creating I\O threads'
        $IoWorkers = @()
        for($i=0 ; $i -lt ($PipeLine.Length-1) ; $i++)
        {
            $SrcEndpoint = $DstEndpoint = $null
            if($PipeLine[$i] -is [System.Diagnostics.Process])
            {
                $SrcEndpoint = 'StdOut'
            }
            if($PipeLine[$i+1] -is [System.Diagnostics.Process])
            {
                $DstEndpoint = 'StdIn'
            }

            $IoWorkers += @{
                Src = $PipeLine[$i]
                SrcEndpoint = $SrcEndpoint
                Dst = $PipeLine[$i+1]
                DstEndpoint = $DstEndpoint
            }
        }
        Write-Verbose "Created $($IoWorkers.Length) I\O worker objects"

        Write-Verbose 'Creating StdErr readers'
        $StdErrWorkers = @()
        for($i=0 ; $i -lt $PsCommand.Length ; $i++)
        {
            $StdErrWorkers += @{
                Src = $PsCommand[$i]
                SrcEndpoint = 'StdErr'
                Dst = New-Object -TypeName System.IO.MemoryStream -ArgumentList $BufferSize -ErrorAction Stop
            }
        }
        Write-Verbose "Created $($StdErrWorkers.Length) StdErr reader objects"

        Write-Verbose 'Starting processes'
        $PsCommand |
            ForEach-Object {
                $ps = $_
                Try
                {
                    [void]$ps.Start()
                }
                Catch
                {
                    Write-Error "Failed to start process: $($ps.StartInfo.FileName)"
                    Write-Verbose "Can't launch process, killing and disposing all"

                    if($PsCommand)
                    {
                        $PsCommand |
                            ForEach-Object {
                                Try{$_.Kill()}Catch{} # Can't do much if kill fails...
                                $_.Dispose()
                            }
                    }

                        Write-Verbose 'Closing and disposing I\O streams'
                    . $CleanUp
                }
                Write-Verbose "Started new process: Name=$($ps.Name), Id=$($ps.Id)"
            }

        $WorkersCount = $IoWorkers.Length + $StdErrWorkers.Length
        Write-Verbose 'Creating sync hashtable'
        $sync = @{}
        for($i=0 ; $i -lt $WorkersCount ; $i++)
        {
            $sync += @{$i = @{IoStartTime = $nul ; Status = $null}}
        }
        $SyncHash = [hashtable]::Synchronized($sync)

        Write-Verbose 'Creating runspace pool'
        $RunspacePool = Get-RunspacePool $WorkersCount

        Write-Verbose 'Loading workers on the runspace pool'
        $AsyncPipelines = @()
        $i = 0
        $IoWorkers + $StdErrWorkers |
        ForEach-Object {
            $Param = @{
                BufferSize = $BufferSize
                Id = $i
                SyncHash = $SyncHash
            } + $_

            $AsyncPipelines += Invoke-Async -RunspacePool $RunspacePool -ScriptBlock $PumpData -Parameters $Param
            $i++

            Write-Verbose 'Started working thread'
            $Param | Format-Table -HideTableHeaders -AutoSize | Out-String | Write-Debug
        }

        Write-Verbose 'Waiting for I\O to complete...'
        if($IoTimeout){Write-Verbose "Timeout is $IoTimeout seconds"}

        Do
        {
            # Check for pipelines with errors
            [array]$FailedPipelines = Receive-AsyncStatus -Pipelines $AsyncPipelines | Where-Object {$_.Completed -and $_.Error}
            if($FailedPipelines)
            {
                "$($FailedPipelines.Length) pipeline(s) failed!",
                ($FailedPipelines | Select-Object -ExpandProperty Error | Format-Table -AutoSize | Out-String) | Write-Debug
            }

            if($IoTimeout)
            {
                # Compare I\O start time of thread with current time
                [array]$LockedReaders = $SyncHash.Keys | Where-Object {[TimeSpan]::FromTicks([DateTime]::UtcNow.Ticks - $SyncHash.$_.IoStartTime).TotalSeconds -gt $IoTimeout}
                if($LockedReaders)
                {
                    # Yikes, someone is stuck
                    "$($LockedReaders.Length) I\O operations reached timeout!" | Write-Verbose
                    $SyncHash.GetEnumerator() | ForEach-Object {"$($_.Key) = $($_.Value.Status)"} | Sort-Object | Out-String | Write-Debug
                    $PsCommand | ForEach-Object {
                        Write-Verbose "Killing process: Name=$($_.Name), Id=$($_.Id)"
                        Try
                        {
                            $_.Kill()
                        }
                        Catch
                        {
                            Write-Error 'Failed to kill process!'
                        }
                    }
                    break
                }
            }
            Start-Sleep 1
        }
        While(Receive-AsyncStatus -Pipelines $AsyncPipelines | Where-Object {!$_.Completed}) # Loop until all pipelines are finished

        Write-Verbose 'Waiting for all pipelines to finish...'
        $IoStats = Receive-AsyncResults -Pipelines $AsyncPipelines
        Write-Verbose 'All pipelines are finished'

        Write-Verbose 'Collecting StdErr for all processes'
        $PipeStdErr = $StdErrWorkers |
            ForEach-Object {
                $Encoding = $_.Src.StartInfo.StandardOutputEncoding
                if(!$Encoding)
                {
                    $Encoding = [System.Text.Encoding]::Default
                }
                @{
                    FileName = $_.Src.StartInfo.FileName
                    StdErr = $Encoding.GetString($_.Dst.ToArray())
                    ExitCode = $_.Src.ExitCode
                }
            } |
                Select-Object   @{Name = 'FileName' ; Expression = {$_.FileName}},
                                @{Name = 'StdErr' ; Expression = {$_.StdErr}},
                                @{Name = 'ExitCode' ; Expression = {$_.ExitCode}}

        if($IoWorkers[-1].Dst -is [System.IO.MemoryStream])
        {
            Write-Verbose 'Collecting final pipeline output'
                if($IoWorkers[-1].Src -is [System.Diagnostics.Process])
                {
                    $Encoding = $IoWorkers[-1].Src.StartInfo.StandardOutputEncoding
                }
                if(!$Encoding)
                {
                    $Encoding = [System.Text.Encoding]::Default
                }
                $PipeResult = $Encoding.GetString($IoWorkers[-1].Dst.ToArray())
        }

        Write-Verbose 'Closing and disposing I\O streams'
        . $CleanUp

        $PsCommand |
            ForEach-Object {
                $_.Refresh()
                if(!$_.HasExited)
                {
                    Write-Verbose "Process is still active: Name=$($_.Name), Id=$($_.Id)"
                    if(!$ProcessTimeout)
                    {
                        $ProcessTimeout = -1
                    }
                    else
                    {
                        $WaitForExitProcessTimeout = $ProcessTimeout * 1000
                    }
                    Write-Verbose "Waiting for process to exit (Process Timeout = $ProcessTimeout)"
                    if(!$_.WaitForExit($WaitForExitProcessTimeout))
                    {
                        Try
                        {
                            Write-Verbose 'Trying to kill it'
                            $_.Kill()
                        }
                        Catch
                        {
                            Write-Error "Failed to kill process $_"
                        }
                    }
                }
                Write-Verbose "Disposing process object: Name=$($_.StartInfo.FileName)"
                $_.Dispose()
            }

        Write-Verbose 'Disposing runspace pool'
        # http://stackoverflow.com/questions/21454252/how-to-cleanup-resources-in-a-dll-when-powershell-ise-exits-like-new-pssession
        $RunspacePool.Dispose()

        if($ForceGC)
        {
            Write-Verbose 'Forcing garbage collection'
            Invoke-GarbageCollection
        }

        if(!$RawData)
        {
            New-Object -TypeName psobject -Property @{Result = $PipeResult ; Status = $PipeStdErr}
        }
        else
        {
            $PipeResult
        }
    }
}

A: I will admit to having zero experience with the ruby -e "puts ARGF.read" command you are using after the pipe, but I think I can prove that the pipe doesn't adding a newline.
# check length of string without newline after pipe
Write-Output "abc" | %{Write-Host "$_ has a length of: $($_.Length)"  }

#check of string with newline length after pipe
Write-Output "def`n" | %{Write-Host "$($_.Length) is the length of $_" -NoNewline }

#write a string without newline (suppressing newline on Write-Host)
Write-Output 'abc' | %{ Write-Host $_ -NoNewline; }

#write a string with newline (suppressing newline on Write-Host)
Write-Output "def`n" | %{ Write-Host $_ -NoNewline; }

#write a final string without newline (suppressing newline on Write-Host)
Write-Output 'ghi' | %{ Write-Host $_ -NoNewline; }

This gives me an output of:
abc has a length of: 3
4 is the length of def
abcdef
ghi

I think you might want to start looking at the ruby -e "put AGRF.read" command and see if it is adding a newline after each read.


text:
Q: How to calculate the sum of integer values of an attributes in XSLT version 1 I want to calculate the sum of attributes using xslt 1.0. below is the xml file as an input.
<?xml version="1.0" encoding="UTF-8"?>
 <alltestsuites>
   <testsuite tests="2" failures="0" disabled="1" errors="0" pass="1">
     <testcase name="test1" file="abc.cpp" status="pass" />
     <testcase name="test2" file="def.cpp" status="disabled" />
   </testsuite>
   <testsuite tests="2" failures="1" disabled="1" errors="0" pass="0">
     <testcase name="test1" file="ghi.cpp" status="disabled" />
     <testcase name="test2" file="jkl.cpp" status="failure" />
   </testsuite>
   <testsuite tests="2" failures="0" disabled="2" errors="0" time="0">
     <testcase name="test1" file="jkl.cpp" status="disabled" />
     <testcase name="test2" file="mno.cpp" status="disabled" />
   </testsuite>
 </alltestsuites>

Basically I am trying to calculate the sum of tests, failure, disabled and error from each testsuite.
Thank you for the help.

A: Try
<xsl:value-of select="sum(/alltestsuites/testsuite/@tests)"/>

AFAICT, the same result could be obtained by:
<xsl:value-of select="count(/alltestsuites/testsuite/testcase)" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to setup Play!2.5 with ReactiveMongo I connect to MongoDB with Scala using :
val driver = new MongoDriver
val connection = driver.connection(List("myhost"))
val db = connection.database("mydb")

This works fine but how to integrate this with a Play controller :
@Singleton
class ReactiveController @Inject() (implicit system: ActorSystem, materializer: Materializer, val reactiveMongoApi: ReactiveMongoApi)
    extends Controller with MongoController with ReactiveMongoComponents {

Do I need to inject a custom ReactiveMongoApi with my DB configuration ?
Or do I need to modify application.conf with my DB settings ?
I'm using play 2.5 and http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html provides this code :
package api

import reactivemongo.api.{ DB, MongoConnection, MongoDriver }

trait ReactiveMongoApi {
  def driver: MongoDriver
  def connection: MongoConnection
  def db: DB
}

But I'm unsure how to integrate it with my Play application ?
I think I'm not aware of some standard method of configuring DB sources with a Play! application ?

A: Make sure you have correct configs in application.conf
play.modules.enabled += "play.modules.reactivemongo.ReactiveMongoModule"
mongodb.uri = "mongodb://localhost:27017/demodb"

You need to inject and change mongo code as below
class MongoUserDao @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends UserDao {
//  val users = reactiveMongoApi.db.collection[JSONCollection]("users") -- old API
//   def find(userId:UUID):Future[Option[User]] =
//    users.find(Json.obj("id" -> userId)).one[User]  -- old code

  def usersF = reactiveMongoApi.database.map(_.collection[JSONCollection]("users"))  //new API

  def find(userId:UUID):Future[Option[User]] = for {
    users <- usersF
    user <- users.find(Json.obj("id" -> userId)).one[User]
  } yield user     // new code
}

If you compare new api code with old api code, reactiveMongoApi.database.map returns Future[Collection].


text:
Q: zabbix 3.0 + pg_monz 2.0 + PostgreSQL streaming replication I have a Zabbix 3.0 instance on CentOS 7.2, I've added the pg_monz extension for monitoring my PostgreSQL streaming replication.
I currently have this in my Zabbix interface;

*

*DB1

*

*host_groups

*

*PostgreSQL

*Linux Servers

*templates

*

*Template OS Linux

*Template App PostgreSQL SR

*Template App PostgreSQL SR Cluster

*DB2

*

*host_groups;

*

*PostgreSQL

*Linux Servers

*templates;

*

*Template OS Linux

*Template App PostgreSQL SR

On the 'latest data' tab, filtered to host_group PostgreSQL

*

*DB1

*

*pg.cluster.status

*

*all items greyed out

*DB2

*

*pg.cluster.status

*

*Number of primary server      1

*Number of running PostgreSQL server   1

*Number of standby server      0

Can someone please clarify the setup for monitoring streaming
replication, I'm sure I've mixed something up in my templates.
I would expect DB1 to show one primary, two running postgresql server
and one standby server. The documentation is a little vague for pg_monz.


text:
Q: Show that $f \in \mathbb{Z}_{5}[x]$ is irreducible The question is specifically asking: Consider $f(x) = [1]x^{3} - [1]x + [2] \in \mathbb{Z}_{5}[x]$. Prove that $f$ is irreducible.

Attempt at a proof
A previously completed exercise states that a $3^{rd}$ degree polynomial is irreducible in $\mathbb{F}[x]$ if it does not have any roots in $\mathbb{F}$. So we will show that $f$ has no roots in $\mathbb{Z}_{5}[x]$.
A corollary states that any polynomial $f \in \mathbb{F}[x]$ and $a \in \mathbb{F}$ can be written in the following form:

*

*$f = (x - a)q + f(a)$ where $q \in \mathbb{F}[x]$
Given this, we can rewrite $f = [1]x^{3} - [1]x + [2] = (x)([1]x^{2} - [1]) + [2] = (x - [0])([1]x^{2} - [1]) + [2]$ where $q = ([1]x^{2} - [1]) \in \mathbb{Z}_{5}[x]$. Then by that same corollary we can say $a$ is a root of $f$ iff $(x-a) \mid f$ but we see that $(x-[0]) \nmid f$ thus $f$ has no root in $\mathbb{Z}_{5}[x]$ and consequently is irreducible in $\mathbb{Z}_{5}[x]$. $\square$

I'm unconvinced that this is a sufficient proof for the question. Namely, I'm wondering about the fact that I've expressed $f$ as a product of polynomials $deg(k) = deg(x-[0]) = 1$ and $deg(q) = deg([1]x^{2} - [1]) = 2$ with a constant $deg(f([0])) = deg([2]) = 0$ so that the degrees work out $3 = deg(f) = deg((x-a)q + f(a)) = deg(x-a) + deg(q) + deg(f(a)) = 1 + 2 + 0$
However, an irreducible polynomial is one for which when expressed as a factor of $2$ polynomials ($f = kq$, where $k,q \in \mathbb{F}[x]$) either $k$ or $q$ has degree $0$, i.e., $f$ is comprised of a constant times a polynomial of the same degree as $f$. So it would seem that I've shown, using the corollary and facts given to me through the texts and exercises that $f$ is irreduicble, however I've expressed it as a product of $2$ polynomials with neither being a constant.
Is it the case that the definition of 'irreducibility' that I'm working with only applies when there isn't an extra constant summed on to the product? Or am I missing something else entirely?

A: Literally all you have to do to show a cubic or quadratic is irreducible in a finite field is to plug in all the field elements and show that none are roots,   due to the fact that any way of writing a cubic or less would have to have a linear factor and as you noted,  you have a linear factor if and only if you have a  root.  So plug in the numbers 0 through 4, show that none are 0, and you are done

A: Another fun way to prove this: put $f=x^3-x+2 \in \mathbb{F}_5[x]$. From
$$f=x^3+x^2-2x-x^2+x+2=x(x-1)(x+2)-(x-2)(x+1)$$
one sees that $f$ can be written as the sum of two polynomials with the property that each element of $\mathbb{F}_5=\{0,1,-2,2,-1\}$ is a zero of one of them but not of the other. Hence $f$ has no zero in $\mathbb{F}_5$, and since its degree is $3$ it must be irreducible.
In fact, it can be shown (a theorem of H.W. Lenstra (2010)) that any irreducible cubic in $\mathbb{F}_5[x]$ admits an irreducibility proof as above. See here.


text:
Q: Does Haskell support anonymous instances of typeclass? I have the following code in F# (it's from a book)
open System.Collections.Generic

type Table<'T, 'U> =
   abstract Item : 'T -> 'U with get
   abstract Discard : unit -> unit

let memoizeAndPermitDiscard f =
     let lookasideTable = new Dictionary<_, _>(HashIdentity.Structural)
     {new Table<'T, 'U> with
      member t.Item
         with get(n) =
             if lookasideTable.ContainsKey(n) then
                 lookasideTable.[n]
             else
                 let res = f n
                 lookasideTable.Add(n, res)
                 res
      member t.Discard() =
           lookasideTable.Clear()}
let rec fibFast =
     memoizeAndPermitDiscard (fun n ->
     printfn "computing fibFast %d" n
     if n <= 2 then 1 else fibFast.[n - 1] + fibFast.[n - 2])

As we can see the abstract type Table take it's implementation in the function memoizeAndPermitDiscard. Can Haskell do the same?

A: Apologies in advance: I'm not an F# expert, so I may be misreading the F# code. But if I'm reading it right it's fairly straightforward to translate to Haskell:
data Table t u = Table { get :: t -> IO u, discard :: IO () }

memoize :: Hashable t => (t -> u) -> IO (Table t u)
memoize f = do
    tbl <- newHashTable
    return Table
        { get = \t -> do
            result <- lookupHashTable t tbl
            case result of
                Nothing -> let u = f t in writeHashTable t u tbl >> return u
                Just u -> return u
        , discard = clearHashTable tbl
        }

I'm assuming some suitable hash table implementation here that offers newHashTable, lookupHashTable, writeHashTable, and clearHashTable. Implementing these (or suggesting a library that offers them) is sort of beside the point of the question, I think.

A: I'm not an F# expert either, but I believe what you're describing is where you create a anonymous single-use subclass, by declaring in at the point where you create an object how it implements the methods of a superclass or interface? So it's really an anonymous class, not an anonymous instance (or rather, it's no more anonymous than any other object-oriented instance, which typically don't have names inherently, only variable names storing references to them).
It doesn't really make sense to do that with Haskell type classes/instances. The reason is that a Haskell instance represents something very different from an OO instance.
The instances of OO classes are objects (even the instances of interfaces are objects). All of a class' methods will always be invoked on an instance of that class. So it makes sense to create an anonymous subclass of an existing class or interface at the time you create a new object. You basically say how that object implements the required methods, as an alternative to declaring a whole named class of objects that implement the methods the same way, which you could instantiate in multiple places.
The instances of Haskell classes are types (which is why the're called type classes). All of the methods of a class must involve the type somehow, but there is no guarantee that they take an input of the type. For example, consider the class1:
class Monoid' a
  where mempty' :: a
        mappend' :: a -> a -> a

It doesn't really make sense to say an object is an instance of Monoid'; if I were to create a new object and I wanted to anonymously instantiate Monoid', how would I define mempty'? mempty' isn't an operation I could invoke on my new object, it's an operation that receives no inputs at all (not even an implicit "this") and produces a value2.
And then there's things like:
class Functor' f
  where fmap :: (a -> b) -> (f a -> f b)

Nothing ever takes an input of a type f that is an instance of Functor'; it doesn't even make sense to talk about something that might, since the instances of the class Functor' are type constructors that need a type parameter to result in a type, not types that actually contain values. So again, it just makes no sense at the point that I'm creating a new object to say "and here's how this object implements Functor'").
It could potentially make sense to declare a new anonymous type locally, and declare how it implements some type classes at the same time. But Haskell has no syntax for it, no.
Fortunately, you also don't need to create anonymous classes/instances in order to have a one-off collection of functions that conforms to a known interface. Functions are first-class values too, so you can just have type whose fields are functions. Then anywhere you like you can create a new value of that type by providing a definition for all of the function fields. For example:
data MyInterface = MyInterface
  { foo :: Int -> Bool
  , bar :: Int -> String
  }

example :: MyInterface -> Int -> (Bool, String)
example impl x
  = (foo impl x, bar impl x)

main = do
  let impl = MyInterface { foo = even, bar = show }
  print $ example impl 7

The above program prints (False,"7").

1 I'm using Monoid' rather than Monoid (and similarly Functor') because I'm using simplifications of the real classes. You can see the real definition with :info Monoid in ghci (or look up the documentation) if you're interested.
2 Or alternatively, the class Monoid' mandates that there simply exists a value of each type that instantiates it, and mempty' just is a reference to it.


text:
Q: What is the relationship between ZFC and Turing machine? I did not learn Logic properly but so far I understand that proof systems can be viewed as a kind of machine. For proof system, ZFC seems to be the most powerful one that we use so far. Similarly, for computation model, Turing machine seems to be the most powerful one.
So I want to ask what is the relationship between these two ?
I did try to formulate the question but if it contains some misunderstanding please point it out.

Let $L$ be a language which contains all statements that can be proven in ZFC.
  Is $L$ decidable by Turing machine, or in other words, is $L$ computable  ?

If this is true, then Turing machine is at least as powerful as ZFC proof system in the sense that, If $a \in L$, that is, $a$ can be proven in ZFC, then Turing machine can decide whether $a \in L$ as well.
For another direction, to say that ZFC system is at least as powerful as Turing machine:

Is ZFC proof system Turing-complete ?

I tried to look up for the answer, and what confuses me the most is the followings.

*

*ZFC is first order.

*From descriptive complexity theory, $FO=AC^0$ which is very limited.

Could you please clarify my confusion ? Thank you very much.

A: $L$ is not computable.  But it is recursively enumerable. If $\varphi$ is a theorem of ZFC, then $\varphi$ can certainly be proved by Turing machine. Just start enumerating all proofs. The problem is with sentences $\varphi$ that are not theorems of ZFC.
In the other direction, a universal Turing machine can be encoded in ZFC, indeed in far weaker theories, such as relatively small fragments of number theory.

A: Suppose, for reductio, that a Turing machine could decide whether the sentence with Gödel number $n$ is a theorem of ZFC. Then the property $Prov(n)$ which $n$ has when $n$ numbers a ZFC-theorem would be recursive. So there would be a ZFC wff which represents that property (since even PA can represent all recursive properties). That means there would be a wff $\mathsf{Prov}()$ such that for any $\varphi$

If ZFC $\vdash \varphi$, then ZFC $\vdash  \mathsf{Prov(\ulcorner\varphi\urcorner)}$
If ZFC $\nvdash \varphi$, then ZFC $\vdash  \neg\mathsf{Prov(\ulcorner\varphi\urcorner)}$

where $\ulcorner\varphi\urcorner$ is the numeral for the Gödel number of $\varphi$.
Now, by the diagonalization lemma, there would be a Gödel-style sentence $\gamma$ such that

ZFC $\vdash \gamma \leftrightarrow \neg\mathsf{Prov(\ulcorner\gamma\urcorner)}$

But we also have, by our supposition,

If ZFC $\vdash \gamma$, then ZFC $\vdash  \mathsf{Prov(\ulcorner\gamma\urcorner)}$
If ZFC $\nvdash \gamma$, then ZFC $\vdash  \neg\mathsf{Prov(\ulcorner\gamma\urcorner)}$

Contradiction is immediate.


text:
Q: When running two functions simultaneously how to return the first result and use it for further processes So I have two webscrapers that collect data from two different sources. I am running them both simultaneously to collect a specific piece of data (e.g. covid numbers).
When one of the functions finds data I want to use that data without waiting for the other one to finish.
So far I tried the multiprocessing - pool module and to return the results with get() but by definition I have to wait for both get() to finish before I can continue with my code. My goal is to have the code as simple and as short as possible.
My webscraper functions can be run with arguments and return a result if found. It is also possible to modify them.
The code I have so far which waits for both get() to finish.
from multiprocessing import Pool
from scraper1 import main_1
from scraper2 import main_2
from twitter import post_tweet

if __name__ == '__main__':
    with Pool(processes=2) as pool:
        r1 = pool.apply_async(main_1, ('www.website1.com','June'))
        r2 = pool.apply_async(main_2, ())

        data = r1.get()
        data2 = r2.get()

    post_tweet("New data is {}".format(data))
    post_tweet("New data is {}".format(data2))

From here I have seen that threading might be a better option since webscraping involves a lot of waiting and only little parsing but I am not sure how I would implement this.
I think the solution is fairly easy but I have been searching and trying different things all day without much success so I think I will just ask here. (I only started programming 2 months ago)

A: As always there are many ways to accomplish this task.
you have already mentioned using a Queue:
from multiprocessing import Process, Queue
from scraper1 import main_1
from scraper2 import main_2

def simple_worker(target, args, ret_q):
    ret_q.put(target(*args)) # mp.Queue has it's own mutex so we don't need to worry about concurrent read/write

if __name__ == "__main__":
    q = Queue()
    p1 = Process(target=simple_worker, args=(main_1, ('www.website1.com','June'), q))
    p2 = Process(target=simple_worker, args=(main_2, ('www.website2.com','July'), q))
    p1.start()
    p2.start()
    first_result = q.get()
    do_stuff(first_result)
    #don't forget to get() the second result before you quit. It's not a good idea to
    #leave things in a Queue and just assume it will be properly cleaned up at exit.
    second_result = q.get()
    p1.join()
    p2.join()

You could also still use a Pool by using imap_unordered and just taking the first result:
from multiprocessing import Pool
from scraper1 import main_1
from scraper2 import main_2

def simple_worker2(args):
    target, arglist = args #unpack args
    return target(*arglist)

if __name__ == "__main__":
    tasks = ((main_1, ('www.website1.com','June')),
             (main_2, ('www.website2.com','July')))
    with Pool() as p:  #Pool context manager handles worker cleanup (your target function may however be interrupted at any point if the pool exits before a task is complete
        for result in p.imap_unordered(simple_worker2, tasks, chunksize=1):
            do_stuff(result)
            break #don't bother with further results

A: I've seen people use queues in such cases: create one and pass it to both parsers so that they put their results in queue instead of returning them. Then do a blocking pop on the queue to retrieve the first available result.

I have seen that threading might be a better option

Almost true but not quite. I'd say that asyncio and async-based libraries is much better than both threading and multiprocessing when we're talking about code with a lot of blocking I/O. If it's applicable in your case, I'd recommend rewriting both your parsers in async.


text:
Q: How many Persistent context can be possible in ejb How many transaction & Persistent Context are possible in ejb ?

A: As many as you want. There is no limit. If you look at the javadoc here, you'll notice the optional parameters that you can use. one of them is the unit name. this tells you which persistence-unit in the persistence.xml file you're pointing to.


text:
Q: C++ ofstream: Can't find output file I have created the a default DirectX12 application (the spinning 3D cube) and within my void DX::DeviceResources::Present() I am trying to write the backbuffer to a file:
// Present the contents of the swap chain to the screen.
void DX::DeviceResources::Present()
{
    // The first argument instructs DXGI to block until VSync, putting the application
    // to sleep until the next VSync. This ensures we don't waste any cycles rendering
    // frames that will never be displayed to the screen.
    HRESULT hr = m_swapChain->Present(1, 0);

    UINT backBufferIndex = m_swapChain->GetCurrentBackBufferIndex();
    ComPtr<ID3D12Resource>         spBackBuffer;
    m_swapChain->GetBuffer(backBufferIndex, IID_PPV_ARGS(&spBackBuffer));

    //before writing the buffer, I want to check that the file is being
    //created
    ofstream myfile;
    myfile.open("WHEREISTHEFILE.txt");
    myfile << "Writing this to a file.\n";
    myfile.close();

    // If the device was removed either by a disconnection or a driver upgrade, we
    // must recreate all device resources.
    if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
    {
        m_deviceRemoved = true;
    }
    else
    {
        DX::ThrowIfFailed(hr);

        MoveToNextFrame();
    }
}

The problem occurs here:
ofstream myfile;
myfile.open("WHEREISTHEFILE.txt");
myfile << "Writing this to a file.\n";
myfile.close();

I just want to write a file first (as illustrated how here), before trying to write the contents of the back buffer. Now, for some reason, I cannot find the output file... I have searched everywhere, all directories in my project and even in the Microsoft DirectX SDK folder.
There are no exceptions thrown and I can step through each line while debugging without error.
Where could it be?

A: It should be in the directory of your project. If you are using Visual Studio, you can right-click your solution and click Open folder in File explorer.
Image: Open folder in File explorer
(I embedded it like this because I need 10 reputation to post an image directly)
Also with your code now, there is no way to determine whether your program is actually able to open the output file or not. I suggest you use something like this:
std::ofstream outputFile("./myOutput.txt");
if (outputFile.fail())
{
    std::cout << "Failed to open outputfile.\n";
}
outputFile << "I like trains.";
outputFile.close();

The first line is an initialisation that does the same as .open(). Also mind the "./" in front of the path, this should not be mandatory but it can't hurt to do this (this means your current directory).
The important part about this piece of code is the .fail() check, if your program failed to open the outputfile, you will ofcourse not be able to find it anywhere. Hope this helped!

A:
Where could it be?

Usually the file location is relative to your current working directory, i.e. WHEREISTHEFILE.txt should be located in whatever directory you were in when you started the program.
You can determine that directory inside your program via GetCurrentDirectory(), and change it to something else via SetCurrentDirectory().
But you did not check if the .open() was successful, so the writing could have failed altogether, for example due to insufficient permissions...?!


text:
Q: Displaying a popup when user enters a page I want to display a little disclaimer when a user goes onto a certain webpage. I am currently using window.addEventListener load but this only displays the popup when the website is refreshed on the page.
import React, { Component } from 'react';
import DisclaimerPopup from "./DisclaimerPopup";

export class LearnTheBasics extends Component {
    static displayName = LearnTheBasics.name;

    constructor(props) {
        super(props);
        this.state = {
            ShowDisclaimerPopup: false,
            profileData: [],
            error: null
        };
    }

    toggleDisclaimerPopup() {
        this.setState({
            showDisclaimerPopup: !this.state.showDisclaimerPopup
        });
    }

    componentDidMount() {
        window.addEventListener('load', this.toggleDisclaimerPopup.bind(this))
    }
    render() {

        return (

                {this.state.showDisclaimerPopup ?
                    <DisclaimerPopup
                        closePopup={this.toggleDisclaimerPopup.bind(this)}
                    /> : null
                }

Learn The Basics

 Add pop up disclaimer

ADD list here of different basics hacks to learn. (css, SQLi etc)

        );
    }
}

This is the code for the page. DisclaimerPopup is just the content that is displayed. I did tinker with useEffect and useState but I couldn't get this to work.
Updated code to useEffect
import React, { useEffect, useState, Component } from 'react';
import DisclaimerPopup from "./DisclaimerPopup";

export class LearnTheBasics extends Component {
    static displayName = LearnTheBasics.name;

    constructor(props) {
        super(props);
        this.state = {
            ShowDisclaimerPopup: false,
            profileData: [],
            error: null
        };
    }

    toggleDisclaimerPopup() {
        this.setState({
            showDisclaimerPopup: !this.state.showDisclaimerPopup
        });
    }

    render() {
        function LearnTheBasics() {
            let [setPopup] = React.useState(false);

            useEffect(() => {
                setPopup(true);
            }, [])
        }
        return (

                {this.state.showDisclaimerPopup ?
                    <DisclaimerPopup
                        closePopup={this.toggleDisclaimerPopup.bind(this)}
                    /> : null
                }

Learn The Basics

 Add pop up disclaimer

ADD list here of different basics hacks to learn. (css, SQLi etc)

        );
    }

A: As you are using class-based component, you can use withRouter HOC and wrap the child component in it. That will allow you to have access to this.props.location.pathname, now in your componentDidMount() function, check for the exact pathname you are looking for, and set the local state to be true if it matches and consequently render the disclaimer popup.
You can read about withRouter more here

A: Making popup as stateful and using useEffect.  I have set the deps array empty so that the disclaimer pops on for the first time, the user enters the page.
function LearnTheBasics() {
    let [popup, setPopup] = React.useState(false);

    useEffect(() => {
        setPopup(true);
    }, [])

    return (

        {popup ? 'popup called': 'dont call the method'}

    )
}


text:
Q: How to change camera direction in osmdroid? I would like to know if there is a way to change camera direction for a perspective mapview? (Z-Axis)
It looks like this.

A: There's a few examples in the sample app for setting the map rotation. Here's some code

mMapView.setMapOrientation(90f);

And a link to the source
https://github.com/osmdroid/osmdroid/blob/master/osmdroid-android/src/main/java/org/osmdroid/views/MapView.java#L575

A: This feature (as of now) is not supported by OSMDroid. To perform an Z-Axis tilting on the mapview, you will need to look for alternatives elsewhere.


text:
Q: Where do the input_ids, input_mask, and segment_ids variables come from in a BERT model? I'm trying to work through the Google BERT tutorial in Google Colab, and am having a hard time following some of its steps.
Specifically, there is a function called create_model which reads like this:
def create_model(is_predicting, input_ids, input_mask, segment_ids, labels,
             num_labels):
"""Creates a classification model."""

bert_module = hub.Module(
  BERT_MODEL_HUB,
  trainable=True)
bert_inputs = dict(
  input_ids=input_ids,
  input_mask=input_mask,
  segment_ids=segment_ids)
bert_outputs = bert_module(
  inputs=bert_inputs,
  signature="tokens",
  as_dict=True)

# Use "pooled_output" for classification tasks on an entire sentence.
# Use "sequence_outputs" for token-level output.
output_layer = bert_outputs["pooled_output"]

hidden_size = output_layer.shape[-1].value

# Create our own layer to tune for politeness data.
output_weights = tf.get_variable(
  "output_weights", [num_labels, hidden_size],
  initializer=tf.truncated_normal_initializer(stddev=0.02))

output_bias = tf.get_variable(
  "output_bias", [num_labels], initializer=tf.zeros_initializer())

with tf.variable_scope("loss"):

# Dropout helps prevent overfitting
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)

logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)

# Convert labels into one-hot encoding
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)

predicted_labels = tf.squeeze(tf.argmax(log_probs, axis=-1, output_type=tf.int32))
# If we're predicting, we want predicted labels and the probabiltiies.
if is_predicting:
  return (predicted_labels, log_probs)

# If we're train/eval, compute loss between predicted and actual label
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, predicted_labels, log_probs)

This would be fine, but when I look for where the create_model function is called in the notebook, the origin of the input_ids, input_mask and segment_ids arguments is not clear to me.
This is where the function is referenced later on in the notebook:
def model_fn_builder(num_labels, learning_rate, num_train_steps,
                 num_warmup_steps):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params):  # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""

input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]

is_predicting = (mode == tf.estimator.ModeKeys.PREDICT)

# TRAIN and EVAL
if not is_predicting:

  (loss, predicted_labels, log_probs) = create_model(
    is_predicting, input_ids, input_mask, segment_ids, label_ids, num_labels)

The problem here is that the features argument is not listed as an argument in the parent function, and it's not defined anywhere else in the notebook.  So I'm not sure why it works, and even more importantly, I'm not sure what things like features['input_ids'] are supposed to represent.  Without this being clear to me, it'll be difficult to make sense of what BERT actually does.
Thank you for your help.


text:
Q: Remove all the  and  tags from within all  tags of a class using BeautifulSoup or re I am trying to remove  and  tags from all the DIV tags that has class "sf-item" from an HTML source because they are breaking the text while scraping from a web url.
(for this demo, I have assigned a sample html string to the BeautifulSoup method - but it would ideally be a web URL as source)
So far I have tried using re with below line - but am not sure how to specify a condition in re such that - remove only the substring between all the  only within DIV tags of class sf-item
data = re.sub('', '', data)

Also tried removing all  and  tags from the entire source using below line, but somehow it doesn't work. Am kind of unsure how to specify all the  and  tags only within DIV tags with class sf-item.
for tag in soup.find_all('u'):
    tag.replaceWith('')

Appreciate if you could please help me achieve this.
Below is the Sample Python code that works -
from re import sub
from bs4 import BeautifulSoup
import re

data = """

 The rabbit got to the halfway point at
 here  However, it couldn't see the turtle.

 He was hot and tired and decided to stop and take a short nap.

 Even if the turtle passed him at
Link. he would be able to race to the finish line ahead of
place, he just kept going.

"""

# data = re.sub('', '', data)  ## This works for this particular string but I cannot use on a web url
# It would solve if I can somehow specify to remove  and  only within DIV of class sf-item

soup = BeautifulSoup(data, "html.parser")

for tag in soup.find_all('u'):
    tag.replaceWith('')

fResult = []
rMessage=soup.findAll("div",{'class':"sf-item"})

for result in rMessage:
    fResult.append(sub("“|.”","","".join(result.contents[0:1]).strip()))

fResult = list(filter(None, fResult))
print(fResult)

Output that I get from above code is
['The rabbit got to the halfway point at', 'He was hot and tired and decided to stop and take a short nap.', 'Even if the turtle passed him at']

But I need the output as below -
['The rabbit got to the halfway point at here However, it couldnt see the turtle.', 'He was hot and tired and decided to stop and take a short nap.', 'Even if the turtle passed him at Link. he would be able to race to the finish line ahead of place, he just kept going.']

A: BeautifulSoup has a builtin method for getting the visible text from a tag (i.e. the text that would be displayed when rendered in a browser). Running the following code, I get your expected output:
from re import sub
from bs4 import BeautifulSoup
import re

data = """

 The rabbit got to the halfway point at
 here  However, it couldn't see the turtle.

 He was hot and tired and decided to stop and take a short nap.

 Even if the turtle passed him at
Link. he would be able to race to the finish line ahead of
place, he just kept going.

"""

soup = BeautifulSoup(data, "html.parser")

rMessage=soup.findAll("div",{'class':"sf-item"})

fResult = []

for result in rMessage:
    fResult.append(result.text.replace('\n', ''))

That will give you the proper output, but with some extra spaces. If you want to reduce them all to single spaces, you can run fResult through this:
fResult = [re.sub(' +', ' ', result) for result in fResult]


text:
Q: Couchbase stuck at re-balancing 0 nodes I have a Couchbase cluster of 3 nodes. 2 of them went down briefly and came back up, after which I started re-balancing from couchbase console.
However, the console is showing Rebalancing 0 nodes for past 28 hours. I tried to stop the rebalance but it's stuck with the same message.
When I used command line tool to stop the rebalance I get the following message:
$ /opt/couchbase/bin/couchbase-cli rebalance-stop -c 127.0.0.1:8091 -u my-admin -p my-password
$ SUCCESS: rebalance cluster stopped

Yet, it's not actually stopped and the popover in console is still there. Is there any way I can fix it? I have already tried restarting both servers (that are stuck in pending).
EDIT:
I ended up pushing data on a different cluster using XDCR and then shutting down the entire cluster (even restarting all nodes didn't work). Some data was lost.
I'm keeping this open in case anyone has a better solution for such situation.

A: Looks like this is a known issue with Couchbase since at least version 2.5.1 through version 4.0.0:
https://forums.couchbase.com/t/rebalance-stuck-at-0-and-does-not-cancel/6568
Looks like you need to know how their erlang setup works and how to restart ns_server from there.

A: Have you tried to remove the node from the cluster and then re-add it to the cluster?


text:
Q: Speech recognition shows Error In Python (Positional Argument Error) Python gives a error when I run this code and I've checked it number of times. The source here is the Microphone, but yet it keeps on asking a value for the 'source'. What should I do. What parameter should I pass to the 'source'?
import pyttsx3
import speech_recognition as sr
#Required Modules

engine = pyttsx3.init()
r = sr.Recognizer
#Initializes variable (Avoiding Time Delay)

def Speak(audio):
    engine.say(audio)
    engine.runAndWait()
#Defining the function Speak() for Audio Output

def Listen():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise
        print("Listening")
        voice = r.listen(source)
        print("Done Listening")
        a = r.recognize_google(voice)
        a = a.lower()
        print("You asked - "+a)
#Defining the function Listen() for Audio Input (INTERNET REQUIRED)

while True:
    Speak("Ask Me Some Questions")
    #Speaks

    Listen()
    #Listens

    try:
        if a == "how are you":
            print("I'm Fine Sir")
            Speak("I'm Fine Sir")
    #Tries to do the program without error

    except:
        print("Error Occured!!!")
    #If error occured, this will be the Output

#Looped

This Code Gives an error,
Traceback (most recent call last):
  File "c:\Users\Vishal\AppData\Local\Programs\Python\Python39\Python Projects\Speech.py", line 29, in <module>
    Listen()
  File "c:\Users\Vishal\AppData\Local\Programs\Python\Python39\Python Projects\Speech.py", line 18, in Listen
    voice = r.listen(source)
TypeError: listen() missing 1 required positional argument: 'source'

What is actaully the error and how to solve it? (I'm a beginner in python, so go easy on me)

A: Here is the updated code
1.You have to go through documentation always first there should be sr.Recognizer()
2.and if you are creating method then for interaction you should return value
import pyttsx3
import speech_recognition as sr
#Required Modules

engine = pyttsx3.init()
r = sr.Recognizer()
#Initializes variable (Avoiding Time Delay)

def Speak(audio):
    engine.say(audio)
    engine.runAndWait()
#Defining the function Speak() for Audio Output

def Listen():
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Listening")
        voice = r.listen(source)
        print("Done Listening")
        a = r.recognize_google(voice)
        a = a.lower()
        print("You asked - "+a)
        return a
#Defining the function Listen() for Audio Input (INTERNET REQUIRED)

while True:
    Speak("Ask Me Some Questions")
    #Speaks

    a=Listen()
    #Listens

    try:
        if a == "how are you":
            print("I'm Fine Sir")
            Speak("I'm Fine Sir")
    #Tries to do the program without error

    except:
        print(a)
        print("Error Occured!!!")
    #If error occured, this will be the Output

#Looped


text:
Q: Uncovering tree nodes Considering the following code:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{trees}

\tikzset{
  invisible/.style={opacity=0},
  visible on/.style={alt=#1{}{invisible}},
  alt/.code args={<#1>#2#3}{%
    \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
  },
}

\begin{document}
\begin{frame}
      \begin{tikzpicture}[overlay,remember picture,
      level 1/.style={level distance=12mm,every child/.style={edge from parent/.style={->,solid,draw=blue}} },
      level 2/.style={sibling distance=12mm,every child/.style={edge from parent/.style={->,solid,draw=blue}}},
      level 3/.style={sibling distance=8mm,every child/.style={edge from parent/.style={->,solid,draw=blue}}},
      semithick]

      \node[draw=none,text=red] {S}
      child[visible on=<2,3>] {node[draw=none,text=red] (a)  {A}};

    \end{tikzpicture}
\end{frame}
\end{document}

I am getting an error if I specify slide range using comma , at visible on option. It works well if I specify the range using 2-3.

A: The problem is that the comma is interpreted as a separator between different options. When the value of a key you are setting contains a , you should protect it with { and }: in your case you should use visible on={<2,3>}.
In this case, looking at how the value is used, you should add braces also to the line containing the definition of visible on, like this: visible on/.style={alt={#1{}{invisible}}},.
Therefore a working version of you example is:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{trees}

\tikzset{
  invisible/.style={opacity=0},
  visible on/.style={alt={#1{}{invisible}}},
  alt/.code args={<#1>#2#3}{%
    \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
  },
}

\begin{document}
\begin{frame}
      \begin{tikzpicture}[overlay,remember picture,
      level 1/.style={level distance=12mm,every child/.style={edge from parent/.style={->,solid,draw=blue}} },
      level 2/.style={sibling distance=12mm,every child/.style={edge from parent/.style={->,solid,draw=blue}}},
      level 3/.style={sibling distance=8mm,every child/.style={edge from parent/.style={->,solid,draw=blue}}},
      semithick]

      \node[draw=none,text=red] {S}
      child[visible on={<2,3>}] {node[draw=none,text=red] (a)  {A}};

    \end{tikzpicture}
\end{frame}
\end{document}


text:
Q: Pure strategy Nash equilibria I'm given a matrix:
$$\begin{bmatrix}
    (4,3)      & (5,1) & (6,2) \\
  (2,1)       & (8,4) & (3,6\\
   (3,0)      & (9,6) & (2,8)
\end{bmatrix}$$
I'm supposed to find the pure strategy Nash equilibrium and Pareto efficiency in this game. I know how to approach when I need to find a mixed strategy using probability distributions, but I do not know how to approach this one. Any help?

A: Suppose the left elements from the pairs are the payoffs for player $1$, and the right the ones for player $2$, then you underline the optimal choice for player $i$ ($i=1,2$), given the choice of the other player. So for your example you would have
\begin{bmatrix}
    (\underline{4},\underline{3})      & (5,1) & (\underline{6},2) \\
  (2,1)       & (8,4) & (3,\underline{6})\\
   (3,0)      & (\underline{9},6) & (2,\underline{8})
\end{bmatrix}
The strategy $(1,1)$ yields a pure strategy Nash equilibrium, since the strategy $1$ is optimal for both players given the choice of the other. Can you see why this works in general for $2$ player games with a finite amount of choices?


text:
Q: preserve colors in tikz when changing slide color in beamer I draw and compile tikz pictures standalone:
\documentclass[tikz]{standalone}
\begin{tikzpicture}
 \draw [<->,thick]
        (0,5) node (yaxis) [left] {$Y$}
        |-
        (5,0) node (xaxis) [below] {$X$};
\draw[blue,thick] (0,0) -- (4,4);
\end{tikzpicture}
\end{document}

and then include the pdf in a beamer presentation with the usual white background:
\documentclass{beamer}
\begin{document}
\begin{frame}
\includegraphics{tikz_pic.pdf}
\end{frame}
\end{document}

and it works fine:

But if I change the slide background to black (via \setbeamercolor{normal text}{fg=white, bg=black}) it inverts the tikz picture too:

How can I preserve the colors in the tikz picture while changing the slide color?
Note that the same thing happens if you line-in the tikz code to beamer:
\documentclass{beamer}
\begin{document}
\begin{frame}
    \begin{tikzpicture}
     \draw [<->,thick]
            (0,5) node (yaxis) [left] {$Y$}
            |-
            (5,0) node (xaxis) [below] {$X$};
    \draw[blue,thick] (0,0) -- (4,4);
    \end{tikzpicture}
\end{frame}
\end{document}

EDIT
I know you can add [background rectangle/.style={fill=white}, show background rectangle] to the tikz picture call and explicitly color lines black:
\begin{tikzpicture}[background rectangle/.style={fill=white}, show background rectangle]
 \draw [<->,thick,black]
      (0,5) node (yaxis) [left] {$Y$}
        |-
        (5,0) node (xaxis) [below] {$X$};
\draw[blue,thick] (0,0) -- (4,4);
\end{tikzpicture}

but this also does not work:

Note that this will work if you directly input the tikz code into the frame, but this is very cumbersome when you have many pictures, as it requires completely re-writing a slide deck.
What is odd is that even when the axes are explicitly drawn black, they inherit the beamer text color (white). Yet if you draw the axes in any other color (e.g. gray), they do not inherit the slide text color.

A: I transform my comment to an answer.
Your image is transparent. You can fill a rectangle in the background, for example by using backgrounds library and adding the style [background rectangle/.style= {fill=white},show background rectangle].
And your first draw command is using the default color (that usually is black), you can put \draw [black,<->,thick] ....
The image (tikz_pic.tex):
\documentclass[tikz]{standalone}
\usetikzlibrary{backgrounds}
\begin{document}
\begin{tikzpicture}[background rectangle/.style={fill=white}, show background rectangle]
  \draw [<->,thick,black]
      (0,5) node (yaxis) [left] {$Y$} |- (5,0) node (xaxis) [below] {$X$};
  \draw[blue,thick] (0,0) -- (4,4);
\end{tikzpicture}
\end{document}

The Beamer file is unchanged :
\documentclass{beamer}
\setbeamercolor{normal text}{fg=white, bg=black}
\begin{document}
  \begin{frame}
    \includegraphics{tikz_pic.pdf}
  \end{frame}
\end{document}

A: You could explicitly use black as colour:
\documentclass{beamer}
\usepackage{tikz}
\setbeamercolor{normal text}{fg=white, bg=black}
\begin{document}
\begin{frame}
\textcolor{black}{
    \begin{tikzpicture}
     \draw [<->,thick]
            (0,5) node (yaxis) [left] {$Y$}
            |-
            (5,0) node (xaxis) [below] {$X$};
    \draw[blue,thick] (0,0) -- (4,4);
    \end{tikzpicture}
    }
\end{frame}
\end{document}

Of course you won't see the black axis on a black background, but you wanted them black ....


text:
Q: Riemannian metric inverse matrix I have an immersion $F: M\to\mathbb R^{n+1}$ with an n-dimensional smooth manifold. The coefficients of the metric $g$ are defined by $g_{ij}(p)=\left\langle \frac{\partial F}{\partial x_i}(p), \frac{\partial F}{\partial x_j}(p) \right\rangle, p\in M$, where $\langle \cdot, \cdot \rangle$ is the standard scalar product on $\mathbb R^{n+1}$.
How can I calculate the coefficients of the inverse matrix $\{g^{ij}\}=\{g_{ij}\}^{-1}$?
Thanks for any help


text:
Q: How can i convert this JSON object into this format? I would to get some help on changing the data structure of a JSON object {Object - Object} into a format that works with Re-Charts data structure{Array - Object}. Can you please guide on how and what is the best way to solve for this. I really appreciate your time and let me know if I should provide any additional information.

JSON Object I would like to convert

{
    "Date": {
      "0": "2019-08-02",
      "1": "2019-08-05",
      "2": "2019-08-06",
      "3": "2019-08-07",
      "4": "2019-08-08",
      "5": "2019-08-09",
      "6": "2019-08-12",
      "7": "2019-08-13",
      "8": "2019-08-14",
      "9": "2019-08-15",
      "10": "2019-08-16"
},
"Open": {
      "0": 205.529999,
      "1": 197.990005,
      "2": 196.309998,
      "3": 195.410004,
      "4": 200.199997,
      "5": 201.300003,
      "6": 199.619995,
      "7": 201.020004,
      "8": 203.160004,
      "9": 203.460007,
      "10": 204.279999
},
"High": {
      "0": 206.429993,
      "1": 198.649994,
      "2": 198.070007,
      "3": 199.559998,
      "4": 203.529999,
      "5": 202.759995,
      "6": 202.050003,
      "7": 212.139999,
      "8": 206.440002,
      "9": 205.139999,
      "10": 207.160004
}
}

Format I would like to convert to

[{ Date: '2019-08-02', Open: 205.529999 }, { Date: '2019-08-05', Open: 197.990005}, { Date: '2019-08-06', Open: 196.309998}, {...} ]

A: You could use a map of the keys of the date option to iterate over these dates:
const arrData = Object.keys(data.Date).map((value, index) => {
    return {
      name: `Page ${String.fromCharCode(index+65)}`,
        uv: data.Open[index],
        pv: data.High[index]
    };
});

Or a reduce:
const arrData = Object.keys(data.Date).reduce((arr, value, index) => {
    arr.push({
      name: `Page ${String.fromCharCode(index+65)}`,
        uv: data.Open[index],
        pv: data.High[index],
        amt: 0 // Where ever you get this info from ;)
    })
    return arr;
}, []);

A: Here is what I used to make it happen:
Initialized consts
const values = Object.values(Data.default)
const dates  = values[0]
const prices = values[1]
const arr = [];

For Loop Statement (I had to work with the for loop to make this happen, please answer other ways that could be done without the for loop statement.)
var i;
var l = Object.keys(dates).
for( i=0; i < l.length; i++ )
{
var b = {};
b["Dates"] = dates[i]
b["Prices"]= prices[i]
arr.push(b);
}


text:
Q: EF Code First(existing database) Relate single entity with two table
Possible Duplicate:
How map single entity with multiple table

I want to get data from two tables and store it into one entity. How??
Entity Class:
 public class HomeViewModel
{
    [Key]
    [Column("candidate_ID")]
    public int candidateID { get; set; }
    [Column("first_name")]
    public string firstName { get; set; }
    [Column("last_name")]
    public string lastName { get; set; }

   // [Column("")]
    public string emailID { get; set; }
   // [Column("")]
    public string mb_country_code { get; set; }
    //[Column("")]
    public int mobile_no { get; set; }
}

Above entity class holds 6 property where 3 property represents ont table1 and 3 represents table2.
 At database table 1 holds candidate_id as primary key and tablte two holds candidate_id as foreign key.


text:
Q: Spark : No Encoder found for java.util.UUID I have a case class that contains a type field UUID.
I use anorm to parse a Postgres table and I want to transform the list to a Dataset.
When I create the Dataset, I have this error No Encoder found for java.util.UUID
def encoder[T: Encoder] = implicitly[Encoder[T]]

val parser = Macro.namedParser[Vehicle]

val result = SQL(s"SELECT * FROM $tableName").as(parser.*)

spark.createDataset(result)(encoder[Vehicle])

How can I manage this error ?
Thanks for your help.

A: There are no encoder for UUID in spark 2. you should use String instead.


text:
Q: Extracting Data from table and writing to a file using PowerShell I have a SQL Server DB from which I need to pull data and write it to a |-separated .dat file.
DB Name:    AppleDB
Tables : ApplePhone and AppleGear
Structure of table ApplePhone:
Id  Phone
1   6s
2   7s

Structure of table AppleGear:
Id  Gear
1   ear
2   watch

I need a script that extracts the information from the above 2 tables and writes it to 2 |-separated .dat files.
ApplePhone.dat:
Id|Phone
1|6s
2|7s

AppleGear.dat:
Id|Gear
1|ear
2|watch

The below code generates xls file,but I need to get .dat file with | delimited.
## ---------- Working with SQL Server ---------- ##

## - Get SQL Server Table data:
$SQLServer = 'myServer';
$Database = 'AppleDB';
$SqlQuery = @'
Select Id,Phone FROM [AppleDB].[dbo].[ApplePhone]
'@;

## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;

## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
## ----------  Excel ---------- ##

## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application;

## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0;
$xlsWb = $xlsobj.Workbooks.Add();
$xlsSh = $xlsWb.Worksheets.item(1);

## - Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName;

## - Build column header:
[Int] $RowHeader = 1;
foreach ($ColH in $getColumnNames)
{
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true;
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName;
$RowHeader++;
};

## - Adding the data start in row 2 column 1:
[Int] $rowData = 2;
[Int] $colData = 1;

foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@";

## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = `
$rec.$($Coln.ColumnName).ToString();
$ColData++;
};
$rowData++; $ColData = 1;
};

## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange;
$xlsRng.EntireColumn.AutoFit();

## ---------- Saving file and Terminating Excel Application ---------- ##

## - Saving Excel file - if the file exist do delete then save
$xlsFile = `
"C:\Temp\dbResults_$((Get-Date).ToString("yyyymmddhhmmss")).xls";

if (Test-Path $xlsFile)
{
Remove-Item $xlsFile
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
}
else
{
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
};

## Quit Excel and Terminate Excel Application process:
$xlsObj.Quit(); (Get-Process Excel*) | foreach ($_) { $_.kill() };

## - End of Script - ##

I want to get both ApplePhone.dat and AppleGear.dat created with a single script.
Help me getting edited the code.


text:
Q: Need help to increment by 1 using a for loop. Only increment by 1 each time So I have a Score Method, which is run after we play, and again if the user wants to replay the game. I am showing scores in it.
Such as
First Try :
Game 1 : He scored 20

then the user decides to replay the game, gets a different score. Then I want it to show.
Second Try :
Game 1 : He scored 20

Game 2 : He scored 10

Third Try : etc
Game 1 : He Scored 20

Game 2 : He scored 10

Game 3 : He scored 5

I have tried using a for loop inside a foreach, then putting the i into another int
public void HighScore()
        {
            int gameList = 1;
            foreach (var item in Points)
            {
                for (int i = 1; i < Points.Count; i++)
                {
                    gameList = i++;
                }
                Console.WriteLine($"{name} : Game {gameList} Score : {item} : Level [{GameLevel}]");
            }
        }

//Points is a Int List
//I want to change the game numbers Game 1, 2, 3, 4,.

A: No need for a for loop:
public void HighScore()
    {
        int gameList = 1;
        foreach (var item in Points)
        {
            Console.WriteLine($"{name} : Game {gameList} Score : {item} : Level [{GameLevel}]");
            gameList++;
        }
    }

A: // use like this
gameList++;

// instead of doing this
gameList = i++;

I hope now you will fix.

A: Fristly you dont need a for loop.Create a class for accessing point for every game for store them regularly like above.
    public class Score
    {
        public Score(int point ,int game)
        {
            Point = point;
            Game = game;
        }

        public int Point { get; set; }
        public int Game { get; set; }

    }

And then create a global variable
List<Score> scores = new List<Score>();

so you can save your score and gameCount.
    int point = 10;//any number
    int lastGame = (scores.Any()) ? scores.Last().Game : 0;//this is about first game if no score its first game
    scores.Add(new Score(point, lastGame += 1));

you can show to user confortable with loop.
foreach(var score in scores){
Console.WriteLine($"Game {score.Game} Point: {score.Point}");

}
    Game  Score
     1      10
     2      20

A: Try below.
Use gameList++ instead of gameList = i++; Unary Increment Operator
public static void HighScore()
{
    int gameList = 1;
    List<int> Points = new List<int>() { 10,20,39,40,50};

    foreach (var item in Points)
    {
       Console.WriteLine($"Game {gameList} Score : {item}");

        gameList++;

    }
}


text:
Q: Can I create a unique constraint on Loopback4's hasManyThrough (M:M) table Preamble
I'm somewhat new to Loopback 4, and I have successfully created 2 working CRUD controllers, repositories, models, etc. I have Users and Organizations, and I am have successfully created a M:M relation between Users and Organizations using the relation generator. So, I can create a user, create an organization, and separately I can link them together in a many-to-many table called "membership". All of this follows (as far as I know) loopback best practices per their docs.
Question:
How do I make sure that each record in the membership table is unique?
here's an example of my table with duplicates
For example, User #1, Jeff, joins Organization #1, Amazon. Some erroneous code then attempts to add Jeff to Amazon a 2nd time, I want this to fail.
I was thinking I could simply check the database if the record exists, but it seems cleaner to add this constraint to the model, so that any attempted insert would fail if duplicate. I have dug around in the docs and haven't found anything.
Any help is appreciated!

A: In database design, a unique constraint would be enforced by a compound/composite key on the junction table. This would enforce a unique pair of orgId and userId.
Hence, the junction table should have only 2 columns:

*

*orgId

*userId

To create a composite key in LoopBack 4, update the through model as follows:
// Some parts were omitted for bevity

@model()
export class OrgUser extends Entity {
  @property({id: 1})
  orgId: number;

  @property({id: 2})
  userId: number;

  constructor(data?: Partial<OrgUser>) {
    super(data);
  }
}


text:
Q: Error - The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data try
        {
            string CSVFilePathName = textBox4.Text;
            for (int i = 0; i < CSVFilePathName.Length; i++)
            {
                if (CSVFilePathName[i] == '\\')
                {
                    CSVFilePathName.Insert(i + 1, "\\");
                }
            }
                if (string.IsNullOrWhiteSpace(textBox4.Text))
                {
                    MessageBox.Show("Please Select a File");
                }
                else
                {
                    int count = 0;
                    // your code here
                    // string CSVFilePathName = @"'" + textBox4.Text + "'";
                    string[] Lines = File.ReadAllLines(CSVFilePathName);
                    string[] Fields;
                    Fields = Lines[0].Split(new char[] { ',' });
                    int Cols = Fields.GetLength(0);
                    DataTable dt = new DataTable();
                    for (int i = 1; i < Lines.GetLength(0); i++)
                    {
                        Fields = Lines[i].Split(new char[] { ',' });
                        for (int f = 0; f < Cols; f++)
                        {
                            q = "SELECT * from questions where main_section='" + Fields[0] + "' AND secondary_section='" + Fields[1] + "' AND tert_section='" + Fields[2] + "' AND question='" + Fields[3] + "' AND difficulty='" + Fields[4] + "'";
                            OleDbCommand cmdn = new OleDbCommand(q, conn);
                            //MessageBox.Show(q);
                            object obj = cmdn.ExecuteScalar();
                            if (obj == null)
                            {
                                q = "insert into questions values('" + Fields[0] + "','" + Fields[1] + "','" + Fields[2] + "','" + Fields[3] + "' ,'" + Fields[4] + "')";
                                OleDbCommand cmdn1 = new OleDbCommand(q, conn);
                                cmdn1.ExecuteNonQuery();
                            }
                            else
                            {
                                count++;
                            }
                            //MessageBox.Show(Fields[f]);
                        }

                    }
                    //  dataGridClients.DataSource = dt;
                    string msg = "Upload successful\n";
                    if (count > 0)
                    {
                        msg=count.ToString()+" Questions missed due to their duplicates in the database.";
                    }
                    MessageBox.Show(msg);
                }

        }
       catch (Exception ex)
       {
           MessageBox.Show("Error is " + ex.ToString());
           throw;
       }

I am using c# winform to upload a csv file to my ms access db, but it is givig the error "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data." What should  do now?

A: I suggest specifying the table fields in the SQL like
INSERT INTO questions (fieldname1, fieldname2, ...) VALUES (...)

Use parameterized-values rather than writing the values directly in the string.  This also allows you to specify the datatype and then the ADO.Net OLE adapter will hopefully handle it appropriately and get the long text inserted with no trouble.  Go to Read / Write BLOBs  ... for an example inserting BLOBS.  The concept and code example are very relevant to inserting Long Text values.  It demonstrates how to set up parameters for the query.  In your case, use OleDbType.LongVarWChar for the Long Text fields.