text:
Q: PowerShell, test the performance/efficiency of asynchronous tasks with Start-Job and Start-Process I'm curious to test out the performance/usefulness of asynchronous tasks in PowerShell with Start-ThreadJob, Start-Job and Start-Process. I have a folder with about 100 zip files and so came up with the following test:
New-Item "000" -ItemType Directory -Force   # Move the old zip files in here
foreach ($i in $zipfiles) {
    $name = $i -split ".zip"
    Start-Job -scriptblock {
        7z.exe x -o"$name" .\$name
        Move-Item $i 000\ -Force
        7z.exe a $i .\$name\*.*
    }
}

The problem with this is that it would start jobs for all 100 zip, which would probably be too much, so I want to set a value $numjobs, say 5, which I can change, such that only $numjobs will be started at the same time, and then the script will check for all 5 of the jobs ending before the next block of 5 will start. I'd like to then watch the CPU and memory depending upon the value of $numjobs
How would I tell a loop only to run 5 times, then wait for the Jobs to finish before continuing?
I see that it's easy to wait for jobs to finish
$jobs = $commands | Foreach-Object { Start-ThreadJob $_ }
$jobs | Receive-Job -Wait -AutoRemoveJobchange

but how might I wait for Start-Process tasks to end?
Although I would like to use Parallel-ForEach, the Enterprises that I work in will be solidly tied to PowerShell 5.1 for the next 3-4 years I expect with no chance to install PowerShell 7.x (although I would be curious for myself to test with Parallel-ForEach on my home system to compare all approaches).

A: ForEach-Object -Parallel and Start-ThreadJob have built-in functionalities to limit the number of threads that can run at the same time, the same applies for Runspace with their RunspacePool which is what is used behind the scenes by both cmdlets.
Start-Job does not offer such functionality because each Job runs in a separate process as opposed to the cmdlets mentioned before which run in different threads all in the same process. I would also personally not consider it as a parallelism alternative, it is pretty slow and in most cases a linear loop will be faster than it. Serialization and deserialization can be a problem in some cases too.
How to limit the number of running threads?
Both cmdlets offer the -ThrottleLimit parameter for this.

*

*https://learn.microsoft.com/en-us/powershell/module/threadjob/start-threadjob?view=powershell-7.2#-throttlelimit

*https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.2#-throttlelimit
How would the code look?
$dir = (New-Item "000" -ItemType Directory -Force).FullName

# ForEach-Object -Parallel
$zipfiles | ForEach-Object -Parallel {
    $name = [IO.Path]::GetFileNameWithoutExtension($_)
    7z.exe x -o $name .\$name
    Move-Item $_ $using:dir -Force
    7z.exe a $_ .\$name\*.*
} -ThrottleLimit 5

# Start-ThreadJob
$jobs = foreach ($i in $zipfiles) {
    Start-ThreadJob {
        $name = [IO.Path]::GetFileNameWithoutExtension($using:i)
        7z.exe x -o $name .\$name
        Move-Item $using:i $using:dir -Force
        7z.exe a $using:i .\$name\*.*
    } -ThrottleLimit 5
}
$jobs | Receive-Job -Wait -AutoRemoveJob

How to achieve the same having only PowerShell 5.1 available and no ability to install new modules?
The RunspacePool offer this same functionality, either with it's .SetMaxRunspaces(Int32) Method or by targeting one of the RunspaceFactory.CreateRunspacePool overloads offering a maxRunspaces limit as argument.
How would the code look?
$dir   = (New-Item "000" -ItemType Directory -Force).FullName
$limit = 5
$iss   = [initialsessionstate]::CreateDefault2()
$pool  = [runspacefactory]::CreateRunspacePool(1, $limit, $iss, $Host)
$pool.ThreadOptions = [Management.Automation.Runspaces.PSThreadOptions]::ReuseThread
$pool.Open()

$tasks  = foreach ($i in $zipfiles) {
    $ps = [powershell]::Create().AddScript({
        param($path, $dir)

        $name = [IO.Path]::GetFileNameWithoutExtension($path)
        7z.exe x -o $name .\$name
        Move-Item $path $dir -Force
        7z.exe a $path .\$name\*.*
    }).AddParameters(@{ path = $i; dir = $dir })
    $ps.RunspacePool = $pool

    @{ Instance = $ps; AsyncResult = $ps.BeginInvoke() }
}

foreach($task in $tasks) {
    $task['Instance'].EndInvoke($task['AsyncResult'])
    $task['Instance'].Dispose()
}
$pool.Dispose()

Note that for all examples, it's unclear if the 7zip code is correct or not, this answer attempts to demonstrate how async is done in PowerShell not how to zip files / folders.

Below is a helper function that can simplify the process of parallel invocations, tries to emulate ForEach-Object -Parallel and is compatible with PowerShell 5.1, though shouldn't be taken as a robust solution:
using namespace System.Management.Automation
using namespace System.Management.Automation.Runspaces
using namespace System.Collections.Generic

function Invoke-Parallel {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, DontShow)]
        [object] $InputObject,

        [Parameter(Mandatory, Position = 0)]
        [scriptblock] $ScriptBlock,

        [Parameter()]
        [int] $ThrottleLimit = 5,

        [Parameter()]
        [hashtable] $ArgumentList
    )

    begin {
        $iss = [initialsessionstate]::CreateDefault2()
        if($PSBoundParameters.ContainsKey('ArgumentList')) {
            foreach($argument in $ArgumentList.GetEnumerator()) {
                $iss.Variables.Add([SessionStateVariableEntry]::new($argument.Key, $argument.Value, ''))
            }
        }
        $pool  = [runspacefactory]::CreateRunspacePool(1, $ThrottleLimit, $iss, $Host)
        $tasks = [List[hashtable]]::new()
        $pool.ThreadOptions = [PSThreadOptions]::ReuseThread
        $pool.Open()
    }
    process {
        try {
            $ps = [powershell]::Create().AddScript({
                $args[0].InvokeWithContext($null, [psvariable]::new("_", $args[1]))
            }).AddArgument($ScriptBlock.Ast.GetScriptBlock()).AddArgument($InputObject)

            $ps.RunspacePool = $pool
            $invocationInput = [PSDataCollection[object]]::new(1)
            $invocationInput.Add($InputObject)

            $tasks.Add(@{
                Instance    = $ps
                AsyncResult = $ps.BeginInvoke($invocationInput)
            })
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
    }
    end {
        try {
            foreach($task in $tasks) {
                $task['Instance'].EndInvoke($task['AsyncResult'])
                if($task['Instance'].HadErrors) {
                    $task['Instance'].Streams.Error
                }
                $task['Instance'].Dispose()
            }
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
        finally {
            if($pool) { $pool.Dispose() }
        }
    }
}

An example of how it works:
# Hashtable Key becomes the Variable Name inside the Runspace!
$outsideVariables = @{ Message = 'Hello from {0}' }
0..10 | Invoke-Parallel {
    "[Item $_] - " + $message -f [runspace]::DefaultRunspace.InstanceId
    Start-Sleep 5
} -ArgumentList $outsideVariables -ThrottleLimit 3

A: To add to Santiago Squarzon's helpful answer:
Below is helper function Measure-Parallel, which allows you to compare the speed of the following approaches to parallelism:

*

*Start-Job:

*

*Child-process-based: creates a child PowerShell process behind the scenes, which makes this approach both slow and resource-intensive.

*Start-ThreadJob - ships with PowerShell (Core) (v6+) ; installable via Install-Module ThreadJob in Windows PowerShell v5.1:

*

*Thread-based: Much lighter-weight than Start-Job while providing the same functionality; additionally avoids potential loss of type fidelity due to cross-process serialization / deserialization.

*ForEach-Object -Parallel - available only in PowerShell (Core) 7.0+:

*

*Thread-based: In essence a simplified wrapper around Start-ThreadJob with support for direct pipeline input and direct output, with invariably synchronous overall execution (all launched threads are waited for).

*Start-Process

*

*Child-process-based: Invokes an external program asynchronously by default, on Windows in a new window by default.

*Note that this approach only makes sense if your parallel tasks only consist of a single call to an external program, as opposed to needing to execute a block of PowerShell code.

*Notably, the only way to capture output with this approach is by redirection to a file, invariably as text only.

Note:

*

*Given that the tests below wrap a single call to an external executable (such as 7z.exe in your case), the Start-Process approach will perform best, because it doesn't have the overhead of job management. However, as noted above, this approach has fundamental limitations.

*Due to its complexity, the runspace-pool-based approach from Santiago's answer wasn't included; if Start-ThreadJob or ForEach-Object -Parallel are available to you, you won't need to resort to this approach.
Sample Measure-Parallelism call, which contrast the runtime performance of the approaches:
# Run 20 jobs / processes in parallel, 5 at a time, comparing
# all approaches.
# Note: Omit the -Approach argument to enter interactive mode.
Measure-Parallel -Approach All -BatchSize 5 -JobCount 20

Sample output from a macOS machine running PowerShell 7.2.6 (timings vary based on many factors, but the ratios should provide a sense of relative performance):
# ... output from the jobs

JobCount                         : 20
BatchSize                        : 5
BatchCount                       : 4
Start-Job (secs.)                : 2.20
Start-ThreadJob (secs.)          : 1.17
Start-Process (secs.)            : 0.84
ForEach-Object -Parallel (secs.) : 0.94

Conclusions:

*

*ForEach-Object -Parallel adds the least thread/job-management overhead, followed by Start-ThreadJob

*Start-Job, due to needing an extra child process - for the hidden PowerShell instance running each task - is noticeably slower. It seems that on Windows the performance discrepancy is much more pronounced.

Measure-Parallel source code:

*

*Important:

*

*The function hard-codes sample input objects as well as what external program to invoke - you'll have to edit it yourself as needed; the hard-coded external program is the platform-native shell in this case (cmd.exe on Windows, /bin/sh on Unix-like platform), which is passed a command to simply echo each input object.

*

*It wouldn't be too hard to modify the function to accept a script block as an argument, and to receive input objects for the jobs via the pipeline (though that would preclude the Start-Process approach, except if you explicitly call the block via the PowerShell CLI - but in that case Start-Job could just be used).

*What the jobs / processes output goes directly to the display and cannot be captured.

*The batch size, which defaults to 5, can be modified with -BatchSize; for the thread-based approaches, the batch size is also used as the -ThrottleLimit argument, i.e. the limit on how many threads are allowed to run at the same time. By default, a single batch is run, but you may request multiple batches indirectly by passing the total number of parallel runs to the -JobCount

*You can select approaches via the array-valued -Approach parameter, which supports Job, ThreadJob, Process, ForEachParallel, and All, which combines all of the preceding.

*

*If -Approach isn't specified, interactive mode is entered, where you're (repeatedly) prompted for the desired approach.

*Except in interactive mode, a custom object with comparative timings is output.
function Measure-Parallel {

  [CmdletBinding()]
  param(
    [ValidateRange(2, 2147483647)] [int] $BatchSize = 5,
    [ValidateSet('Job', 'ThreadJob', 'Process', 'ForEachParallel', 'All')] [string[]] $Approach,
    [ValidateRange(2, 2147483647)] [int] $JobCount = $BatchSize # pass a higher count to run multiple batches
  )

  $noForEachParallel = $PSVersionTable.PSVersion.Major -lt 7
  $noStartThreadJob = -not (Get-Command -ErrorAction Ignore Start-ThreadJob)

  $interactive = -not $Approach
  if (-not $interactive) {
    # Translate the approach arguments into their corresponding hashtable keys (see below).
    if ('All' -eq $Approach) { $Approach = 'Job', 'ThreadJob', 'Process', 'ForEachParallel' }
    $approaches = $Approach.ForEach({
      if ($_ -eq 'ForEachParallel') { 'ForEach-Object -Parallel' }
      else { $_ -replace '^', 'Start-' }
    })
  }

  if ($noStartThreadJob) {
    if ($interactive -or $approaches -contains 'Start-ThreadJob') {
      Write-Warning "Start-ThreadJob is not installed, omitting its test; install it with ``Install-Module ThreadJob``"
      $approaches = $approaches.Where({ $_ -ne 'Start-ThreadJob' })
    }
  }
  if ($noForEachParallel) {
    if ($interactive -or $approaches -contains 'ForEach-Object -Parallel') {
      Write-Warning "ForEach-Object -Parallel is not available in this PowerShell version (requires v7+), omitting its test."
      $approaches = $approaches.Where({ $_ -ne 'ForEach-Object -Parallel' })
    }
  }

  # Simulated input: Create 'f0.zip', 'f1'.zip', ... file names.
  $zipFiles = 0..($JobCount - 1) -replace '^', 'f' -replace '$', '.zip'

  # Sample executables to run - here, the native shell is called to simply
  # echo the argument given.
  # The external program to invoke.
  $exe = if ($env:OS -eq 'Windows_NT') { 'cmd.exe' } else { 'sh' }
  # The list of its arguments *as a single string* - use '{0}' as the placeholder for where the input object should go.
  $exeArgList = if ($env:OS -eq 'Windows_NT') { '/c "echo {0}"' } else { '-c "echo {0}"' }

  # A hashtable with script blocks that implement the 3 approaches to parallelism.
  $approachImpl = [ordered] @{}

  $approachImpl['Start-Job'] = { # child-process-based job
    param([array] $batch)
    $batch |
    ForEach-Object {
      Start-Job { Invoke-Expression ($using:exe + ' ' + ($using:exeArgList -f $args[0])) } -ArgumentList $_
    } |
    Receive-Job -Wait -AutoRemoveJob # wait for all jobs, relay their output, then remove them.
  }

  if (-not $noStartThreadJob) {
    # If Start-ThreadJob is available, add an approach for it.
    $approachImpl['Start-ThreadJob'] = { # thread-based job - requires Install-Module ThreadJob in WinPS
      param([array] $batch)
      $batch |
      ForEach-Object {
        Start-ThreadJob -ThrottleLimit $BatchSize { Invoke-Expression ($using:exe + ' ' + ($using:exeArgList -f $args[0])) } -ArgumentList $_
      } |
      Receive-Job -Wait -AutoRemoveJob
    }
  }

  if (-not $noForEachParallel) {
    # If ForEach-Object -Parallel is supported (v7+), add an approach for it.
    $approachImpl['ForEach-Object -Parallel'] = {
      param([array] $batch)
      $batch | ForEach-Object -ThrottleLimit $BatchSize -Parallel {
        Invoke-Expression ($using:exe + ' ' + ($using:exeArgList -f $_))
      }
    }
  }

  $approachImpl['Start-Process'] = { # direct execution of an external program
    param([array] $batch)
    $batch |
    ForEach-Object {
      Start-Process -NoNewWindow -PassThru $exe -ArgumentList ($exeArgList -f $_)
    } |
    Wait-Process # wait for all processes to terminate.
  }

  # Partition the array of all indices into subarrays (batches)
  $batches = @(
    0..([math]::Ceiling($zipFiles.Count / $batchSize) - 1) | ForEach-Object {
      , $zipFiles[($_ * $batchSize)..($_ * $batchSize + $batchSize - 1)]
    }
  )

  # In interactive use, print verbose messages by default
  if ($interactive) { $VerbosePreference = 'Continue' }

  :menu while ($true) {
    if ($interactive) {
      # Prompt for the approach to use.
      $choices = $approachImpl.Keys.ForEach({
        if ($_ -eq 'ForEach-Object -Parallel') { '&' + $_ }
        else { $_ -replace '-', '-&' }
      }) + '&Quit'
      $choice = $host.ui.PromptForChoice("Approach", "Select parallelism approach:", $choices, 0)
      if ($choice -eq $approachImpl.Count) { break }
      $approachKey = @($approachImpl.Keys)[$choice]
    }
    else {
      # Use the given approach(es)
      $approachKey = $approaches
    }
    $tsTotals = foreach ($appr in $approachKey) {
      $i = 0; $tsTotal = [timespan] 0
      $batches | ForEach-Object {
        $ts = Measure-Command { & $approachImpl[$appr] $_ | Out-Host }
        Write-Verbose "$batchSize-element '$appr' batch finished in $($ts.TotalSeconds.ToString('N2')) secs."
        $tsTotal += $ts
        if (++$i -eq $batches.Count) {
          # last batch processed.
          if ($batches.Count -gt 1) {
            Write-Verbose "'$appr' processing of $JobCount items overall finished in $($tsTotal.TotalSeconds.ToString('N2')) secs."
          }
          $tsTotal # output the overall timing for this approach
        }
        elseif ($interactive) {
          $choice = $host.ui.PromptForChoice("Continue?", "Select action", ('&Next batch', '&Return to Menu', '&Quit'), 0)
          if ($choice -eq 1) { continue menu }
          if ($choice -eq 2) { break menu }
        }
      }
    }
    if (-not $interactive) {
      # Output a result object with the overall timings.
      $oht = [ordered] @{}; $i = 0
      $oht['JobCount'] = $JobCount
      $oht['BatchSize'] = $BatchSize
      $oht['BatchCount'] = $batches.Count
      foreach ($appr in $approachKey) {
        $oht[($appr + ' (secs.)')] = $tsTotals[$i++].TotalSeconds.ToString('N2')
      }
      [pscustomobject] $oht
      break # break out of the infinite :menu loop
    }
  }

}

A: You could add a counter to your foreach loop and break if the counter reaches your desired value
$numjobs = 5
$counter = 0
foreach ($i in $zipfiles) {
  $counter++
  if ($counter -ge $numjobs) {
    break
  }
  <your code>
}

or with Powershells Foreach-Object
$numjobs = 5
$zipfiles | select -first $numjobs | Foreach-Object {
  <your code>
}

If you want to process the whole array in batches and wait for each batch to complete you have to save the object that is returned by Start-Job and pass it to Wait-Job like this:
$items = 1..100

$batchsize = 5

while ($true) {
    $jobs = @()
    $counter = 0
    foreach ($i in $items) {
        if ($counter -ge $batchsize) {
            $items = $items[$batchsize..($items.Length)]
            break
        }
        $jobs += Start-Job -ScriptBlock { Start-Sleep 10 }
        $counter++
    }
    foreach ($job in $jobs) {
        $job | Wait-Job | Out-Null
    }
    if (!$items) {
        break
    }
}

By design arrays have fixed lengths, that's why I'm rewriting the whole array with $items = $items[$batchsize..($items.Length)]


text:
Q: Compile all rustdoc comments in project folder into single markdown file Let's say I have the following directory structure in a VSCode project:
- MY_EXAMPLES
 - Example_1
   - src
    - main.rs
   - Cargo.lock
   - Cargo.toml
 - Example_2
   - src
    - main.rs
   - Cargo.lock
   - Cargo.toml

Now I want to compile the comments from all main.rs files. In this case, that'd be MY_EXAMPLES/Example_1/src/main.rs and MY_EXAMPLES/Example_2/src/main.rs. Note that I would like this solution to scale, so I could automatically compile the comments if I had 10 or 20 Example_X folders.
MY_EXAMPLES/Example_1/src/main.rs
/// My notes on Example 1 that I'd like to add to my README.md
fn main(){
//..
}

MY_EXAMPLES/Example_2/src/main.rs
/// My notes on Example 2 that I'd like to add to my README.md
fn main(){
//..
}

Running:
C:\Users\Primary User\Desktop\MY_EXAMPLES> cargo doc

should create a README.md file that looks like:

Example_1
My notes on Example 1 that I'd like to add to my README.md
Example_2
My notes on Example 2 that I'd like to add to my README.md

So our general template for the README.md content is something like:
### Project Rootdir
rustdoc comments

Does rustdoc have any kind of templating system, similar to that of JSDoc, etc?
I've also seen this similar question, which is currently without an answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I access a POST parameter in Node js AWS Lambda with API Gateway integration? I know how to access GET string variables in a Node js Lambda that is integrated with API Gateway with:
 event["queryStringParameters"]["variable_name"]

What is the equivalent for accessing POST variables?

A: Use the following
if (event.body !== null && event.body !== undefined) {
        let body = JSON.parse(event.body) //use in case of JSON body
        //your code
}

AWS Documentation


text:
Q: How can I calculate the median of irregular datasets? In R, I've got some data in a dataframe with the x-values in column df$a and y in column df$b. I want to interpolate them to a series of generated x-values à la output_x_values <- seq(0.0, 100.0, 1.0).  Now approx(df$a, y = df$b, xout = output_x_values) somehow only extracts the first length(output_x_values) from the given df with nrow(df) > length(output_x_values). What is going wrong here and what can I do to fix it? Atm it looks like as shown in the figure, and I want to add a median-line.Fraction of precipitation by percentile.

A: The approx function you are attempting to use for interpolation has a default "rule" argument that will not interpolate values outside the observed range in the vector which is truncating the values in the result with NA. You can change this to "rule = 2" in order to allow for interpolation outside of the expected range:
output_x_values <- seq(0.0, 100, 1.0)

# Toy data
set.seed(1)
df <- data.frame(a = seq(50, 150, 10), b = seq(0, 100, 10) + rnorm(11, 20, 10))

df

# a         b
# 1   50  13.73546
# 2   60  31.83643
# 3   70  31.64371
# 4   80  65.95281
# 5   90  63.29508
# 6  100  61.79532
# 7  110  84.87429
# 8  120  97.38325
# 9  130 105.75781
# 10 140 106.94612
# 11 150 135.11781

approx(x = df$a, y = df$b, xout = output_x_values, rule = 2)

However, this has a slightly odd effect on the data:
plot(df)
plot(approx(x = df$a, y = df$b, xout = output_x_values, rule = 2))

You may wish to try:
# Toy data scaled with centiles but without interpolation
plot(percent_rank(df$a), percent_rank(df$b))

# Toy data scaled with centiles with interpolation
plot(approx(x = percent_rank(df$a), y = percent_rank(df$b), n = 100))


text:
Q: Transfer all data to a new phoenix cluster Is there a standard way to move all apache phoenix data to a new cluster? and how long would it take to move 2 terabytes of phoenix rows?
senario:
I launched my platform using virtual servers (as its cheaper) but now I am ready to move to dedicated servers but I want to know the right way to move the data to a new cluster so my users dont hunt me down to torture me for messing up the data they trusted my platform with.

A: All phoenix data is present as hbase tables, so the easiest way is to take a snapshot of all tables in hbase, then use hbase to copy them over.
https://community.hortonworks.com/questions/57049/hbase-table-copy-from-one-cluster-to-other.html


text:
Q: SQL Query to Compare Two Tables and Output Results to Two Reports in Proper Order I am developing software for a fishing tournament that supports maintaining the waterfront here in Jacksonville and I am learning SQL as I go. For this problem I have no idea where to even start:
I am working in SQL Server 2008 and I have four tables:
Anglers, Boats, VIG_FishWeight and VIG_FishAggWeight

Anglers:
Angler_ANID, ANLname, ANFName, ANCity, ANState

Boats:
BT_ANID, BoatName

VIG_Fishweight:
FWAngler_ANID, FWBoatNumber, FWWeight,FWTimeStamp

VIG_FishAggWeight:
FAAngler_ANID, FABoatNumber,FAggWeight,FATimestamp

VIG_FishWeight contains a list of all fish weighed.
VIG_FishAggWeight contains the sum of all fish weighed by each angler
ANID is Angler ID, an auto generated number that is consistent across all tables.
The tournament pays the first 25 places in the biggest fish and the greatest aggregate weight tournaments.
If an angler's aggregate weight is in a higher position than his biggest fish weight, then he is placed in the aggregate tournament.  Basically each angler is ranked in the tournament that will pay him the biggest prize.
I need a query to create two reports, one for biggest fish and one for aggregate that contains:
Rank, Boat Number AnglerFNAme, AnglerLName, ANCity, ANState, Weight

As I said, I don't have any idea where to begin with this, so any help would be greatly appreciated.

A: Solved it.  Here is the Query I used:
INSERT INTO WeightsScoreTable
    (ANFName, ANLName, BNBoatNAme, ANCity, ANState, BNBoatNumber, ANBFWeight, ANAggWeight)
     SELECT p.FAAFName, p.FAALName, p.BAABoatName, p.FAACity, p.FAAState, p.FAABoatNumber, c.FWWeight, p.FAAAggWieght
     FROM FAAReport AS p LEFT OUTER JOIN
     WeightsScoreTable AS n ON n.BNBoatNumber = p.FAABoatNumber LEFT OUTER JOIN
     FWReport AS c ON p.FAABoatNumber =c.FWABoatNumber
     ORDER BY ANBFWeight DESC

     DECLARE @LoopValue INT
     SET @LoopValue = (SELECT COUNT (*)
     FROM WeightsScoreTable)

     WHILE @LoopValue > 0
     BEGIN

     INSERT INTO BigFishScore (ANFName, ANLName, BNBoatName, ANCity, ANState, ANBFWeight, BNBoatNumber)
     SELECT ANFName, ANLName, BNBoatName, ANCity, ANState, ANBFWeight, BNBoatNumber
     FROM WeightsScoreTable
     WHERE (ANBFWeight = (SELECT MAX(ANBFWeight) AS Expr1
     FROM WeightsScoreTable))
     ORDER BY ANBFWeight DESC

     DELETE FROM WeightsScoreTable
     WHERE ANBFWeight
     IN (SELECT MAX(ANBFWeight)
     FROM WeightsScoreTable)

     INSERT INTO AggScore (ANFName, ANLName, BNBoatName, ANCity, ANState, ANAggWeight, BNBoatNumber)
     SELECT ANFName, ANLName, BNBoatName, ANCity, ANState, ANAggWeight, BNBoatNumber
     FWHERE (ANBFWeight = (SELECT MAX(ANAggWeight) AS Expr2
     FROM WeightsScoreTable))
     ORDER BY ANAggWeight DESC

     DELETE FROM WeightsScoreTable
     WHERE ANAggWeight
     IN (SELECT MAX(ANAggWeight)
     FROM WeightsScoreTable)

   SET @LoopValue = (@LoopValue - 1)
END

A: Just for fun I wanted to throw together a single select and so I'm curious to see if this does actually produce the result you were trying to describe. It sounds like an angler can only place in one of the two tournaments (and can only place once in the biggest fish as well.)
with individual as (
   select
        FAAngler_ANID as AnglerId, FWWeight as Weight,
        rank() over (order by FWWeight desc) as Rnk
    from VIG_FishWeight
), aggregate as (
    select
        FAAngler_ANID as AnglerId, sum(FWWeight) as Weight,
        rank() over (order by sum(FWWeight) desc) as Rnk
    from VIG_FishWeight
    group by FAAngler_ANID
), combined as (
    select
        i.AnglerId,
        /* Aggregate ranking must beat all the Individual rankings to win out.
           Remember there might be multiple fish on the Individual side. */
        case when min(a.Rnk) < min(i.Rnk)
             then 'Aggregate' else 'Big Fish' end as Tournament,
        case when min(a.Rnk) < min(i.Rnk)
             then min(a.Rnk) else min(i.Rnk) end as Rnk,
        case when min(a.Rnk) < min(i.Rnk)
             then max(a.Weight) else max(i.Weight) end as Weight
    from individual as i inner join aggregate as a on a.AnglerId = i.AnglerId
    group by i.AnglerId
), tournament as (
    select
        AnglerId, Tournament, Weight,
        rank() over (partition by Tournament order by Rnk) as TournamentRank
    from combined
)
select Tournament, TournamentRank, AnglerId, Weight
from tournament /* inner join to Anglers table for name, etc. */
where TournamentRank <= 25
order by Tournament, TournamentRank;

http://rextester.com/discussion/LBF76134/Ranking-split-across-tournaments


text:
Q: How to map C integer to Java enum via JNA using TypeConverter? I would like to have the conversion made by JNA automatically. Right now I'm following the solution from the second answer in a very similar question and JNA's own EnumConverter utility class. There's one crucial difference, my enum has a constructor argument.
My code defining the TypeConverter:
public class SentinelStatusConverter implements TypeConverter {
    @Override
    public SentinelStatus fromNative(Object nativeValue, FromNativeContext context) {
        Integer code = (Integer) nativeValue;
        return SentinelStatus.fromCode(code);
    }

    @Override
    public Integer toNative(Object value, ToNativeContext context) {
        SentinelStatus status = (SentinelStatus) value;
        return Integer.valueOf(status.getCode());
    }

    @Override
    public Class<Integer> nativeType() {
        return Integer.class;
    }
}

public class SentinelTypeMapper extends DefaultTypeMapper {
    public SentinelTypeMapper() {
        addTypeConverter(SentinelStatus.class, new SentinelStatusConverter());
    }
}

Here's code directly registering the native C library along with my custom TypeMapper. C functions return an int which I want to map automatically into a SentinelStatus enum:
public class SentinelLibrary {
    static {
        Map<String, Object> options = new HashMap<String, Object>();
        options.put(Library.OPTION_TYPE_MAPPER, new SentinelTypeMapper());
        Native.register(NativeLibrary.getInstance("libnamelib", options));
    }

    public static native SentinelStatus hasp_get_sessioninfo(
        NativeLong sessionHandle,
        String query,
        PointerByReference info);
}

SentinelStatus is an enum like so:
public enum SentinelStatus {
    HASP_STATUS_OK(0),
    HASP_SOME_ERROR(13),
    ...
    HASP_NOT_IMPL(1831);

    private final int code;

    SentinelStatus(final int code) { this.code = code; }

    public int getCode() { return this.code; }

    public static SentinelStatus fromCode(final int code) {
        for (SentinelStatus status : EnumSet.allOf(SentinelStatus.class)) {
            if (code == status.getCode()) {
                return status;
            }
        }
        return SentinelStatus.HASP_NOT_IMPL;
    }
}

With this JNA mapping and converter I get an error whenever I try to load the SentinelLibrary class:
java.lang.ExceptionInInitializerError
...
Caused by: java.lang.IllegalArgumentException: Unsupported Structure field type class package.name.SentinelStatus
at com.sun.jna.Structure$FFIType.get(Structure.java:1851)
at com.sun.jna.Structure$FFIType.get(Structure.java:1806)
at com.sun.jna.Native.register(Native.java:1438)
at com.sun.jna.Native.register(Native.java:1165)
at package.name.SentinelLibrary.<clinit>(line with Native.register() call)

I've read the documentation and there weren't any restriction as to the mapped class or type. Only the NativeMapped interface required the implementer to provide a public no-argument constructor.
Is it possible to map a C integer to an enum this way?
UPDATE:
After further rummaging through JNA code, I've added this field to the SentinelStatus enum:
public final static TypeMapper TYPE_MAPPER = new SentinelTypeMapper();

Now SentinelLibrary gets loaded without errors. But all methods returning the enum, return null with error printed to stderr:
JNA: unrecognized return type, size 4

A: Most likely you are defining your Structure outside the context of your library definition (which is where the TypeMapper information is stored).
You can either explicitly set the type mapper on your Structure class, or define your Structure class within your native Library class.  If there is no TypeMapper explicitly defined for a Structure, it will fall back to the options provided by any surrounding Library class.
public class MyStructure extends Structure {
    public MyStructure() {
        setTypeMapper(new MyTypeMapper());
    }
}

Alternatively,
public interface MyLibrary extends Library {
    public class MyStructure extends Structure {
    }
}

Or with direct mapping:
public class MyLibrary implements Library {
    { Native.register(...); }
    public class MyStructure extends Structure { }
}

When a Structure class fails to find an explicitly-set type mapper, it looks for enclosing class of type Library, and attempts to look up the options used when instantiating that class.  These options get cached when the native library is loaded, so the are available via key lookup using the Library subclass as key.  You'll need to implement the Library interface so that your direct-mapped library is recognized as a native library class.
EDIT
This is a bug in JNA's type mapper handling (see project issue).  This seems to be restricted to direct-mapped libraries and enum type mapping.
EDIT
There are several JNA bugs at work here, a fix is available if you'd like to try it.  This issue is isolated to type mappers on direct-mapped libraries where a primitive is being converted to a Java object.


text:
Q: How to install RDP Client Access License trial or use its grace period? We want to have multiple active sessions in Windows Server 2012. Each active session will run an app to which one user will be connected. The problem is that we can not keep more than 2 sessions active at a time.
As explained here we probably need to have RDP CALs for each session. But before buying we want to try how well it works in our scenario.
So how do I install the trial license in Windows Server 2012 for RDP to have multiple active sessions? Or what setup/configuration do I need if there is no trial license/grace period needed?

A: The CALs are not what is limiting you to 2 sessions.  You need to go through the Remote Desktop Services installation process through Server Manager.
Here is an article from Microsoft about the process:
Remote Desktop Services (RDS) Quick Start Deployment for RemoteApp, Windows Server 2012 Style
After you go through the process there is a 120 day grace period before you need to install licensing.

A: After you install the RDP roles, you should be able to use unlimited CALs for the grace period:
https://technet.microsoft.com/en-us/library/hh553157(v=ws.10).aspx
120 days I believe.
The Grace period starts from when the RDP server receives its first connection.


text:
Q: MySQL DATE returns NULL I have the following table structure:
uid     | ... | created | ...
int(10) | ... | int(10) | ...

created field is filled with timestamps; here are the results of query SELECT created FROM mytable WHERE 1 LIMIT 5:
created
----------
1308122243
1308122243
1308552690
1309247417
1309254571

But when I execute SELECT DATE(created) FROM mytable WHERE 1 LIMIT 5, I get strange NULL's:
DATE(created)
-------------
2013-08-12
2013-08-12
NULL
NULL
NULL

Why that happens?

A: This is happening because you fundamentally misunderstand MySQL's date and time handling. Why are you storing dates as int(10) and not DATE or TIMESTAMP?  That's just wrong.
Read the documentation. http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
To summarize, the int is converted to a string, and the string is interpreted as a date representation.  1308122243 is interpreted as 13-08-12 plus some extra characters and so is converted to August 12, 2013. However 1308552690 is Aug 55, 2013, and thus invalid and thus null.

A: You're probably looking for
SELECT DATE(FROM_UNIXTIME(created)) FROM mytable WHERE 1 LIMIT 5

A: I think you want
SELECT FROM_UNIXTIME(created) FROM mytable

A: I found my own mistake, and solution was simple.
If you want to have an int(10) field be interpreted correctly as a timestamp, you should do DATE(FROM_UNIXTIME(created)) instead of just DATE(created).

A: did you try FROM_UNIXTIME?
SELECT DATE( FROM_UNIXTIME(`created`)) FROM mytable WHERE 1 LIMIT 5

A: MY QUERY - SELECT *,Year(date) AS Year FROM sql_basics.patients;
is returning NULL in the Year column. the date is stored as DD-MM-YYYY in my database.


text:
Q: Deployment of play 2.2.3 application in glassfish 3.1 I tried to build a war for play 2.2.3 application to deploy in glassfish server using play2war plugin. I followed the steps in
 https://github.com/play2war/play2-war-plugin/wiki/Configuration.
 But its not worked.
How to deploy play 2.2.3 application in glassfish server 3.1. Please help..

A: There seems to be compatibility issue of Play 2.2.3 using play2war deployment on Glassfish 3. I get error as below:
Exception: java.lang.ClassCircularityError thrown from the UncaughtExceptionHandler in thread "Grizzly-kernel-thread(1)"

Sorry I do not know the fix, but using the same war deploys fine on Glassfish 4
For Play2War, it runs the best on Apache tomcat servers based on my simple tests

A: To install play framework on glassfish (3 or 4) follow step by step the ssh codes:

*

*For glassfish home dir /your_path/glassfish4/glassfish/domains/domain1/lib/
1) Download and unzip glassfish:

    unzip glassfish-4.1*zip
    rm -rf rm -rf glassfish-4.1.zip

2) Download and Unzip Play framework (jars)

unzip play-2.2.6.zip
rm -rf play-2.2.6.zip

3) Extract it to your glassfish domain lib dir:

find play-2.2.6/repository/local/ '*.jar' -exec cp -vuni '{}'
  "glassfish4/glassfish/domains/domain1/lib/" ";"
      find play-2.2.6/repository/local/ -iname *.jar -exec cp {}   glassfish4/glassfish/domains/domain1/lib/ \;
      rm -rf play-2.2.6

4) Download new activator to create new application.conf file:

unzip typesafe-activator-1.2.12-minimal.zip
rm -rf typesafe-activator-1.2.12-minimal.zip
cd activator-1.2.12-minimal
./activator new sport-api play-scala
cd ..

5) Stop and start your glassfish

glassfish4/glassfish/bin/asadmin stop-domain
  glassfish4/glassfish/bin/asadmin start-domain

6) Add custom variable to glassfish:

glassfish4/glassfish/bin/asadmin create-jvm-options -Dconfig.file=/your_path/sport-api/conf/application.conf

7) Done! Deploy your .war file using play framework features.

Obs: You can download this project "play 4 glassfish" with custom sh installer for glassfish 4.1. More features for future.
https://github.com/rbsdev/play4glassfish.git


text:
Q: Caching downloaded JSON data to SQLite database - is it a good idea? In my app I have to download JSON data from numerous web services. The data classes I use are fairly complex ones (lots of properties, quite deep inheritance tree, etc.).
I intend to do caching, using a single db table, where I'd store the downloaded JSON data in a VARCHAR column (along with other meta-data containing columns). JSON serialization is being done with the Gson library.
It seems quite convenient to just dump the instances into JSON, and parse them again later when I need them. No need to create custom tables for every class, or write loads of custom serialization code. Also, I can do queries on the cache table this way.
The question: Is this approach an anti-pattern by any means?

A: There is absolutely nothing wrong with this approach; however, I am going to recommend that you instead use the built in caching storage. See the section called "Saving cache files" in Data Storage for more details.This way you don't hog any precious space if your JSON objects are large in the event of a low memory situation.


text:
Q: Nodetool getsstable for composite partition key I've a table as following in keyspace test -
CREATE TABLE mytable (
  firstname text,
  lastname text,
  address text,
  phone text,
  PRIMARY KEY (firstname,lastname,address)
)
I've inserted a record
insert into test.mytable(firstname,lastname,address,phone)  values ('H','P','Kolkata','9836852120');

and also have executed nodetool compact test mytable to force the record to go to sstable.
Now I'm want to execute nodetool getsstables for this record. How will I pass composite key in this command nodetool getsstables test mytable <key> ?

A: Thank you guys. Finally I figured it out myself. I first did a list mytable in cassandra-tcli, then took the RowKey value from the result and used it in the command nodetool getsstables test mytable H:P:Kolkata
So key will be H:P:Kolkata
If you have composite partition key then use : between them in sequence to find out the RowKey(PartitionKey).


text:
Q: Dúvida sobre sintaxe do Android Activity e o método "onCreate" e o que são seus argumentos! Sou novato no mundo da programação e tenho estudado java. Estou querendo entender a aplicação de Java para apps Android e me deparei com estes métodos da Activity.
A teoria eu compreendo sem problemas, porém eu empaco na sintaxe. Basicamente eu preciso que alguém explique o que esses termos significam e porque eles estão dispostos da forma que estão. Por exemplo:
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
}

Eu sei que protected void onCreate(Bundle savedInstanceState){ é um método; sei que Bundle e savedInstanceState são parâmetros/argumentos deste método, sei o que eles alegadamente fazem que é salvar estados de informação para permitir serem recuperados após alguma interrupção na Activity, porém minhas dúvidas são:

*

*O que exatamente é um Bundle? Certamente é um parâmetro para o método, mas, varias coisas podem ser parâmetros. É uma variável? Objeto? Classe? Outro método (é possível?)

*O que é e da onde vem Bundle e savedInstanceState?

*E quanto a sintaxe dentro do escopo das outras linhas (onCreate e setContentview)?

Estou confuso porque não sei da onde vem esses elementos, sei que vem de alguma biblioteca importada, mas o que eles são ou representam?

A: Bundle é uma classe cuja função é salvar e recuperar informações de estado sobre a Activity em questão. Há certas situações, como mudança de orientação do aparelho (retrato p/ paisagem, por exemplo), em que a Activity precisa ser reconstruída e o estado anterior dela recuperado, nesse caso, o onCreate é chamado e, no Bundle, estarão as informações da Activity para que ela possa ser recriada da maneira como estava antes do evento que chamou esse onCreate.
O setContentView basicamente "desenha" a Activity. Ele recebe como parâmetro uma referência a um arquivo XML que representa o "desenho", a esquematização gráfica do que vai ser exibido para o usuário. Em outras palavras, cada "tela" de um app é uma Activity, construída a partir de um arquivo XML.


text:
Q: How to get datatable from stored procedure? I have a below stored procedure:
create or replace
PROCEDURE "SP_UTILITIES_LOG"
(
p_utility_name IN varchar2,
p_r_object_id IN varchar2,
p_platform_name IN varchar2,
p_exported_file_path IN varchar2,
p_Is_binary IN number,
p_extraction_status IN varchar2,
p_extraction_error IN varchar2,
p_extraction_datetime IN VARCHAR2,
p_schema_name IN varchar,
p_publication_path IN varchar,
p_schema_tcm_id IN varchar,
p_component_tcm_id IN varchar,
p_component_name IN varchar,
p_loading_status IN varchar,
p_transformed_file_path IN varchar,
p_transformed_status IN varchar,
p_import_status IN varchar,
p_loading_error IN varchar,
p_transform_error IN varchar,
p_import_error IN varchar,
p_loading_datetime IN TIMESTAMP,
p_transform_datetime IN TIMESTAMP,
p_import_datetime IN TIMESTAMP

)
   IS
   BEGIN

    IF(p_utility_name ='EXTRACTION')
    THEN
    BEGIN
   INSERT INTO utilities_log(R_OBJECT_ID,
PLATFORM_NAME,
EXPORTED_FILE_PATH,
IS_BINARY,
EXTRACTION_STATUS,
EXTRACTION_ERROR,
EXTRACTION_DATETIME
)
   VALUES(p_r_object_id, p_platform_name,p_exported_file_path, p_is_binary, p_extraction_status, p_extraction_error, p_extraction_datetime);

    END;
    END IF;

    IF(p_utility_name ='LOADING')
    THEN
    BEGIN

    UPDATE UTILITIES_LOG SET schema_name=p_schema_name,
    publication_path= p_publication_path,
    schema_tcm_id= p_schema_tcm_id,
    component_tcm_id= p_component_tcm_id,
    component_name= p_component_name,
    loading_status= p_loading_status,
    loading_error= p_loading_error,
    loading_datetime= current_timestamp
    WHERE
    r_object_id= p_r_object_id;

    END;
    END IF;

    IF(p_utility_name ='PRE-TRANSFORMATION')
    THEN
    BEGIN
    SELECT exported_file_path,component_tcm_id FROM utilities_log
    WHERE
    platform_name= p_platform_name and loading_status=p_loading_status
    and extraction_status=p_extraction_status;

    END;
    END IF;

    IF(p_utility_name ='TRANSFORMATION')
    THEN
    BEGIN
    UPDATE UTILITIES_LOG SET
    transformed_file_path= p_transformed_file_path,
    transformed_status= p_transformed_status,
    transform_error= p_transform_error,
    transform_datetime= current_timestamp
    WHERE
    exported_file_path= p_exported_file_path;

    END;
    END IF;

    IF(p_utility_name ='RETRIEVE')
    THEN
    BEGIN
    execute immediate 'create global temporary table temp_import as SELECT transformed_file_path,publication_path
    FROM utilities_log
    WHERE
    platform_name= p_platform_name';

    END;
    END IF;

    IF(p_utility_name ='IMPORTER')
    THEN
    BEGIN
    UPDATE UTILITIES_LOG SET
    import_status=p_import_status,
    import_error=p_import_error,
    import_datetime=current_timestamp
    WHERE
    publication_path= p_publication_path;
    END;
    END IF;

   END;

I am getting error "Into" clause is missing in select statement...
Any help ?
Thanks

A: IF(p_utility_name ='RETRIEVE') THEN
BEGIN
  execute immediate 'create global temporary table temp_import
  as SELECT transformed_file_path,publication_path
     INTO temp_import
     FROM utilities_log
     WHERE platform_name= p_platform_name'
END
END IF

I think

A: The correct way to do this is (returning a set of query results from an sp to c#), is by using the Ref Cursor type, provided by oracle.
You can see how its implemented here and here
EDIT:
It should look like this (i dont have oracle here, but you can easily check this):
create or replace PROCEDURE "SP_UTILITIES_LOG" (
p_utility_name IN varchar2,
p_r_object_id IN varchar2,
/* your other parameters */
p_refcur out sys_refcursor /* notice the out parameter */
)
AS
BEGIN
/* one sample from your select*/
IF(p_utility_name ='PRE-TRANSFORMATION')
 THEN
 BEGIN
      OPERN p_refcur FOR
      SELECT exported_file_path,component_tcm_id FROM utilities_log
      WHERE     platform_name= p_platform_name
     AND        loading_status=p_loading_status
     AND extraction_status=p_extraction_status;
 END;
 END IF;
END;

A: The error message relates to this:
IF(p_utility_name ='PRE-TRANSFORMATION')
THEN
BEGIN
SELECT exported_file_path,component_tcm_id FROM utilities_log
WHERE
platform_name= p_platform_name and loading_status=p_loading_status
and extraction_status=p_extraction_status;
END;
END IF;

In a PL/SQL block, the data has to be selected into something, so you'd need to declare some variables, and then do:
SELECT exported_file_path,component_tcm_id
INTO <local_exported_file_path_var>, <local_component_tcm_id_var>
FROM utilities_log
...

You could then use those variables elsewhere in the SP, which you don't seem to have a need for at the moment, so not sure why you're selecting at all. Or have OUT parameters you could select them into so they could be accessed by the caller, but you aren't doing that either.
Temporary tables shouldn't be created on the fly in Oracle, so the whole concept seems confused. If you're trying to return a table of data to the caller, then as @YavgenyP says, look at ref cursors. Not sure quite what you are trying to do though.


text:
Q: Get values of groupBy This must be a really silly question but in the tutorials I found, they usually print all the values of a set. What if I only wanted the values corresponding to a key? Sorry, I'm new to Kotlin and OOP in general.
So for example:
val words = listOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length }

println(byLength.keys) // [1, 3, 2, 4]
println(byLength.values) // [[a], [abc, def], [ab], [abcd]]

How do I access only [abc, def] given the key 3?

A: groupBy returns a map. You get a value out of a map using the [] operator:
byLength[3]

A: byLength[3]
This is how you index into a map in Kotlin.

A: groupBy returns a Map, specifically a Map<Int, List<String>> in this case. If you need the value associated with a given key, you can use the get method (which can also be called as an operator):
val v1: List<String>? = byLength.get(3)
val v2: List<String>? = byLength[3]

Alternatively, there's getOrDefault which gives you a non-nullable result:
val v3: List<String> = byLength.getOrDefault(3, emptyList())

A: println(byLength[3])
and to access abc and def you can do
val tab = byLength[3]!!
println(tab[0]) // abc
println(tab[1]) // def


text:
Q: How can I set my imageView to fill my UICollectionViewCell I create my custom UICollectionViewCell (MyCell) for my UICollectionView in storyboard.
I add a UIIMageView as the child of my custom UICollectionViewCell (MyCell).
In storyboard, I can't change the location of the UIIMageView to fill my custom UICollectionViewCell.
I have tried adjust the values in attribute / size inspector. But that does not work.
Can you please help me solve my issue?

A: You're editing the properties of the cell, not the image view. Select the "Image View" item you see in the left column or double-click it on the canvas.


text:
Q: linkprop objects with hgtransform Literately figured out the last problem as soon as I posted. Was able to fix many of the issues I was having. Now the problem revolves around hgtransform and linkprop. How does one copy the object location and transformation to additional figures. The code below will copy objects from the first axes to the next and animate making all of them move. However it doesn't copy the transformation.
fig = figure();
% create subplots for stim system 3 plate setup
for aa = 1:3
    Stimsubfigures{aa} = axes(...
      'Position',[((aa*.21)-.2),.2,.2,.2],'color','none');
    set(Stimsubfigures{aa},'xLim',[-320,320])
    set(Stimsubfigures{aa},'YLim',[-240,240])
    set(Stimsubfigures{aa},'Visible','off')
end

axes(Stimsubfigures{1});
for aa = 1:10
    Xdata = [1+aa*50,10+aa*50,10+aa*50,1+aa*50];
    ObjectTransformation{aa,1} = hgtransform;                   % Add object to end of transformation list
    ObjectList{aa,1} = patch(...                                % Add object to end of Object list, bind to transformation list
                'Parent', ObjectTransformation{aa}, ...
                'XData',Xdata, 'YData',[1,1,20,20],...
                'Facecolor', [1,0,0], 'EdgeColor', [1,0,0], ...
                'visible','on');
    ObjectTransformation{aa,1}.Matrix = makehgtform('zrotate',50);
    NextStepX{aa,1} = Xdata;
end

tmp = transpose([ObjectList{:}]);
tmptrans = transpose([ObjectTransformation{:}]);

TrialLength = 10;

 % copy objects to other figures
copyobj(tmp,Stimsubfigures{2})
copyobj(tmp,Stimsubfigures{3})
property_names = {'XData', 'YData', 'ZData'};
for aa = 1:10
linked_objects = [tmp(aa),...
                          Stimsubfigures{2}.Children(aa),...
                          Stimsubfigures{3}.Children(aa)];
hlink{aa} = linkprop(linked_objects,property_names);
end

timer = tic();

while true
    t1 = toc(timer);
    if t1 >= TrialLength, break;end                             % break loop once time trial ends
    NextStepX = cellfun(@(x) x+1,NextStepX,'UniformOutput',false);
    [tmp.XData] = NextStepX{:};
    drawnow;
    pause(0.1);
    step = NextStepX;
end

for aa = 1:3
    delete(Stimsubfigures{aa}.Children)
end

When I change this section to copy the transformation, the objects transform correctly but lose the animation.
 % copy objects to other figures
copyobj(tmptrans,Stimsubfigures{2})
copyobj(tmptrans,Stimsubfigures{3})

property_names = {'XData', 'YData', 'ZData'};
trans_names = {'zrotate'};

for aa = 1:10
linked_objects = [tmp(aa),...
                          Stimsubfigures{2}.Children(aa),...
                          Stimsubfigures{3}.Children(aa)];
Trlink_objects = [tmptrans(aa),...
                          Stimsubfigures{2}.Children(aa),...
                          Stimsubfigures{3}.Children(aa)];
hlink{aa} = linkprop(linked_objects,trans_names);
Trhlink{aa} = linkprop(Trlink_objects,trans_names);
end

I tried to perform an copyobj on both handles but it just results in two sets of objects. How can one link all three together so I can perform rotation change Xdata?

A: Figured it out. Will post answer for those who had similar questions.
The hgtransform is a parent of the objects which are being rotated. because of this when I copy the hgtransform, the children are also copied, hence why the objects appear in the proper orientation in the other windows. From here, I need to link the children from the copied parents to generate the animation.
% copy objects to other figures
copyobj(tmptrans,Stimsubfigures{2})
copyobj(tmptrans,Stimsubfigures{3})

property_names = {'XData', 'YData', 'ZData'};

for aa = 1:10
    linked_objects = [tmptrans(aa).Children(1),...
                      Stimsubfigures{2}.Children(aa).Children(1),...
                      Stimsubfigures{3}.Children(aa).Children(1)];

    hlink{aa} = linkprop(linked_objects,trans_names);
end

By replacing the part of code with the section above. One can transform the objects and animate.


text:
Q: app which will record the ussd or sms As we know that, when we use any menu in sim toolkit it send command to mobile network in ussd or sms format.
I need that sms or ussd to record and show it to me in android application.
I am calling the library service which i got in main activity like this
public class MainActivity extends Activity {

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

    Intent srvIntent = new Intent(this, CDUSSDService.class);
    startService(srvIntent);

}
}

USSD Service Class is like that:
    public class CDUSSDService extends Service{

    private String TAG = CDUSSDService.class.getSimpleName();
    private boolean mActive = true;//false  //we will only activate this "USSD listener" when we want it

    BroadcastReceiver receiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if(intent.getAction().equals(Intent.ACTION_INSERT))
            {
                //activity wishes to listen to USSD returns, so activate this
                mActive = true;
                Log.d(TAG, "activate ussd listener");

                showtoast(""+"activate ussd listener");
            }
            else if(intent.getAction().equals(Intent.ACTION_DELETE))
            {
                mActive = false;
                Log.d(TAG, "deactivate ussd listener");
                showtoast(""+"DeActivate ussd listener");
            }
        }
    };

    private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub ()
    {
        public void clearMmiString() throws RemoteException
        {
            Log.d(TAG, "called clear");
            showtoast("called clear.");
        }

        public void setMmiString(String number) throws RemoteException
        {
            Log.d (TAG, "setMmiString:" + number);
            showtoast("setMmiString:"+number);
        }

        public CharSequence getMmiRunningText() throws RemoteException
        {
            if(mActive == true)
            {
                return null;
            }

            return "USSD Running";
        }

        public CharSequence getUserMessage(CharSequence text)
                throws RemoteException {
            Log.d(TAG, "get user message " + text);
            showtoast("GET Usr Message:"+text);

            if(mActive == false){
                //listener is still inactive, so return whatever we got
                Log.d(TAG, "inactive " + text);
                showtoast("inactive:"+text);
                return text;
            }

            //listener is active, so broadcast data and suppress it from default behavior

            //build data to send with intent for activity, format URI as per RFC 2396
            Uri ussdDataUri = new Uri.Builder()
            .scheme(getBaseContext().getString(R.string.uri_scheme))
            .authority(getBaseContext().getString(R.string.uri_authority))
            .path(getBaseContext().getString(R.string.uri_path))
            .appendQueryParameter(getBaseContext().getString(R.string.uri_param_name), text.toString())
            .build();

            sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));

            mActive = false;
            return null;
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "called onbind");

        //the insert/delete intents will be fired by activity to activate/deactivate listener since service cannot be stopped
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_INSERT);
        filter.addAction(Intent.ACTION_DELETE);
        filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
        filter.addDataAuthority(getBaseContext().getString(R.string.uri_authority), null);
        filter.addDataPath(getBaseContext().getString(R.string.uri_path), PatternMatcher.PATTERN_LITERAL);
        registerReceiver(receiver, filter);

        return mBinder;
    }

    public void showtoast(String str)
    {
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    }
    }

I have created MainActivity inside the UssdLibray structure is like that in the below picture:

A: you can do this with the help of this library https://github.com/alaasalman/ussdinterceptor


text:
Q: How do I run Chromium on Ubuntu Server I am running ubuntu server (no gui).
I am trying to run Chromium and somehow view the gui using another tool (vnc?)
When I try to run chromium-browser I get this error:
(chromium-browser:3869): Gtk-WARNING **: cannot open display:

I think I might have to set the DISPLAY environment variable.
I really don't know how to do this at all. Help!

A: You cannot run a GUI application if you have a headless server without a GUI. In Linux/Ubuntu you need to install XWindows. I expect that when installing Chromium there were some suggestions on installing other dependancies? Like XWindows. Otherwise you could install a mininum GUI like XFCE4 without all the dependancies (so not the Xubuntu desktop, but only XFCE4). This will enable you to start the XWindows system from command line (startxfce4) when you want. But it is no longer a real headless server.
Like the other commenters said: you can start it using ssh -X (-X will forward XWindows) but not VNC. The VNC software expects a GUI already running, while ssh -X will start it's own (have a look at http://en.wikipedia.org/wiki/X_Window_System).
When using SSH from a different computer you also need a XWindows server. For windows install CygWin (and XWin) or use XMing.

A: Use ssh -X server.some.where and you get $DISPLAY.

A: If you use ssh to log in to the server, use the option -X for X11 forwarding. Otherwise, there was some issue with launching Chrome as root. You can see it here


text:
Q: Calculating distance between points in matlab Having difficulty understanding the following code in Matlab to calculate Euclidean distance between two points, where X is the data to be classified and label corresponds to cluster membership.
label = ones(1, data_dim);
[N,~]=size(X);
[c,~]=size(clusters);
dist = zeros(N,c);
for i = 1:c
    dist(:,i) = sum(bsxfun(@minus, X, clusters(i,:)).^2, 2);
end

[~,label] = min(dist,[],2);

Can anyone explain what is going on here and maybe explain it from first principles without using bsxfun?

A: *

*The for loop iterates over every row in clusters. Each row is presumably the coordinates of a point in that cluster.

*bsxfun(@minus, X, clusters(i,:) subtracts that particular cluster row from every row in X. In other words, it outputs a matrix where the first row is X(1,:) - clusters(i,:), the second row is X(2,:) - clusters(i,:), etc. This is like a direction vector from each point in X to the particular cluster point i.

*Every value is squared (.^2) and then these are summed along each row (sum(...,2)) . That gives you a column vector containing the square of the Euclidean distance from every point in X to the cluster point. This is stored in the matrix 'dist' which therefore contains the square of the distance from every point in X to each point in clusters

*the min(dist,[],2) command finds the minimum of these values over each column of dist, i.e. it find the minimum distance for each point in x. However, the actual value is ignored and instead the index is stored in label - this index corresponds to the cluster which had the minimum distance


text:
Q: Какой тип данных в SQL создавать? У меня есть @Entity класс "Account".
Также, у меня есть @Entity класс "Transaction", который содержит 2 поля :
private Account from;
private Account to;

Такой вопрос : В самой таблице MYSQL какой тип данных указывать для "from" и "to" ?

A: java:
    private String Account from;
    private String Account to;

mysql:
    from NVARCHAR(20),
    to NVARCHAR(20)

A: Вопрос решен.
Автоматически направляю данные в базу с помощью JPA - HIBERHATE.


text:
Q: More than 80 posts and no editor badge
Possible Duplicate:
Strunk & White badge missing

According to the documentation, all you need to get the Strunk & White badge is 80 edits.
I have 88 of them but still don't recieve it.
Something missing?

A: Do all edits conform to these rules?:

*

*Perform a total of 80 edits between
questions and answers

*Edits on deleted posts do not count

*Edits to your own posts do not count

*Edits to CW posts do count

*Edits that consist only of tag
changes do not count

*Tag wiki edits do count

*Edits you suggest before gaining
full edit privileges do count, once
approved
Consult the list of all badges and requirements.


text:
Q: Spring LDAP example requires persistence? I am new to Spring and LDAP. I found an awesome example that explains how to quickly start with spring boot and apacheds. I followed the example by using the suggested Gradle configuration. The link. When I start spring boot I receive the following error...

 Error creating bean with name 'persistenceExceptionTranslationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.

I am not sure why Spring is asking for the persistence translator though from searching through other postings it appears there is an ORM within the classpath (I haven't loaded an ORM JAR and the exception does not occur if the spring security boot entry is removed from gradle) and this is why Spring is looking for a JPA implementation and the translator. Anyone else have issue with the example from the link. Thanks!

A: The problem is that spring-security-ldap has a transitive dependency on spring-tx and the version that's being pulled in is 3.2.8.RELEASE. Spring Boot 1.2 requires 4.1.x. This doesn't happen with Maven due to its superior dependency management.
You can fix the problem by adding an explicit dependency on spring-tx. There's no need to specify a version as Spring Boot will take care of this for you. Based on the example that you linked to in the question, this will leave your dependencies looking like this:
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework:spring-tx")
    compile("org.springframework.security:spring-security-ldap:3.2.4.RELEASE")
    compile("org.apache.directory.server:apacheds-server-jndi:1.5.5")
    testCompile("junit:junit")
}


text:
Q: Is it safe to call setImmediate recursively? Is it safe to call setImmediate() recursively in (a reasonably up-to-date version of) NodeJS?
I have experimented with the following code and I haven't seen a stack overflow, or constant memory growth, but I can't find any documentation anywhere explicitly stating that this is safe to do:
let i = 0;
(function runTest() {
    i++;
    console.log(i);
    setImmediate(runTest);
}());


text:
Q: What does "ku" or "kU" mean with regards to procuring ICs? (not about RF) NB: This is not referring to RF subject matter.
I'm seeing 1ku and 10ku on procurement documentation for purchasing motor driver ICs (TI DRV8811 and some others). Does this mean "one-thousand units"?  Sometimes I also see it written as kU (10kU) in the same context.

A: 1kU refers to 1000 units.
10kU refers to 10,000 units.
You will often see this on a pricing schedule where the vendor or manufacturer specify pricing based upon committed quantity from the purchaser.

A: 1ku = 1,000 units
10ku = 10,000 units
EE commonly uses the SI Metric Unit prefixes where 'k' is kilo, 1,000


text:
Q: transalate Currency Symbol into arabic I have two stores English and Arabic. I am using SAR(Saudi Riyal) currency symbol. Right now the price is shown like SAR 1250 but for Arabic Store I want to translate SAR into ريـال and the price show like 699.00 ريـال.

A: Go to Admin Panel :
System->Manage Currency->Symbols Then Uncheck Use Standard Checkbox If Selected. Then Write ريـال Instead of SAR.
Now Click On Save Currency Symbol. And Refresh On Frontend Side to see Changes.

A: Remove the following code from /lib/Zend/Locale/Data/ar_SA.xml
<numbers>
    <currencyFormats numberSystem="latn">
        <currencyFormatLength>
            <currencyFormat type="standard">
                <pattern>¤#0.00</pattern>
            </currencyFormat>
        </currencyFormatLength>
    </currencyFormats>

</numbers>

it will show " ر.س." as default currency symbol for Saudi riyal. To change it to "ريـال" open file /lib/Zend/Locale/Data/ar.xml and replace " ر.س." with "ريـال" at line 6223
don't forget to flush cache

A: Since the US$ is given in the xml file and the other currency is taken from the admin panel, you are getting the error. You need to make the following changes in the ar.xml and the ar_SA.xml file. This changes fixed my issue.
In the lib/Zend/Locale/Data/ar.xml file
You need to replace the US$ with the SAR
and remove the following code from the  lib/Zend/Locale/Data/ar_SA.xml file.

                ¤#0.00

Clear the cache, Re-index and check your website.

A: I am Changing UAE Currency symbol....
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency_symbol, $currency ) {
switch( $currency ) {
case 'AED'  : $currency_symbol = 'AED'; break;
}
return $currency_symbol;
}


text:
Q: Python urllib2 code returns "HTTP error 503" on one machine but not another I can open a webpage such as nike's page with Python 2.7's urllib2 library on my ubuntu desktop. But, when I move that code to a google compute engine server (with the same O.S.), it starts returning a HTTP Error 503: Service Unavailable.
What could be causing this error from one place and not another and, if possible, how would I go about making my machines behave consistently?

A: That server returns urllib2.HTTPError: HTTP Error 403: Forbidden unless you pass an 'Accept' header. Using only the 'User-Agent' header failed when I tried. Here is the working code; I've commented out the unnecessary 'User-Agent' and 'Connection' headers, but left them for reference:
import urllib2
user_agent = {'User-Agent': 'Mozilla/5.0'}
req_headers = {
    # 'User-Agent': user_agent,
    # 'Connection': 'Keep-Alive',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
request = urllib2.Request('http://www.nike.com/us/en_us/c/men', headers=req_headers)
response = urllib2.urlopen(request)
data = response.read()
print data

Also see this other Stackoverflow answer, which I used as a reference for the 'Accept' string.

A: HTTP Status 503 means, and I quote RFC 2612: "The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header."
So, it's not at all about where the request comes from: it's all about the server being temporarily overloaded, or, in maintenance. Check for a Retry-After header in the response and apply it; or, if missing, "retry later" more generically.
If persistent (it shouldn't be: 503 means the server is suffering a temporary condition), contact the web site system administrators and get an explanation of what's going on. To repeat, this is strictly about the web server you're contacting, and should be a temporary condition; not at all about your client.


text:
Q: Find the minima and maxima of a list I have a list, such as:
testdata = {{1, 317}, {2, 317}, {3, 317}, {4, 317}, {5, 317}, {6,
    317}, {7, 318}, {8, 318}, {9, 318}, {10, 318}, {11, 319}, {12,
    319}, {13, 319}, {14, 319}, {15, 314}, {16, 314}, {17, 314}, {18,
    314}, {19, 314}, {20, 314}, {21, 314}, {22, 314}, {23, 314}, {24,
    314}, {25, 314}, {26, 314}, {27, 314}, {28, 306}, {29, 306}, {30,
    306}, {31, 306}, {32, 293}, {33, 293}, {34, 293}, {35, 293}, {36,
    293}, {37, 293}, {38, 293}, {39, 223}, {40, 223}, {41, 223}, {42,
    223}, {43, 154}, {44, 154}, {45, 154}, {46, 154}, {47, 219}, {48,
    219}, {49, 219}, {50, 219}, {51, 267}, {52, 267}, {53, 267}, {54,
    267}, {55, 293}, {56, 293}, {57, 293}, {58, 293}, {59, 300}, {60,
    300}, {61, 300}, {62, 300}, {63, 287}, {64, 287}, {65, 287}, {66,
    287}, {67, 273}, {68, 273}, {69, 273}, {70, 248}, {71, 248}, {72,
    248}, {73, 248}, {74, 232}, {75, 232}, {76, 232}, {77, 232}, {78,
    203}, {79, 203}, {80, 203}, {81, 203}, {82, 180}, {83, 180}, {84,
    180}, {85, 180}, {86, 163}, {87, 163}, {88, 163}, {89, 163}, {90,
    158}, {91, 158}, {92, 158}, {93, 158}, {94, 179}, {95, 179}, {96,
    179}, {97, 179}, {98, 203}, {99, 203}, {100, 203}, {101,
    203}, {102, 228}, {103, 228}, {104, 228}, {105, 228}, {106,
    228}, {107, 228}, {108, 228}, {109, 228}, {110, 228}, {111,
    228}, {112, 228}, {113, 228}, {114, 228}, {115, 230}, {116,
    230}, {117, 230}, {118, 230}, {119, 225}, {120, 225}, {121,
    225}, {122, 225}, {123, 214}, {124, 214}, {125, 214}, {126,
    224}, {127, 224}, {128, 224}, {129, 224}, {130, 228}, {131,
    228}, {132, 228}, {133, 228}, {134, 239}, {135, 239}, {136,
    239}, {137, 239}, {138, 244}, {139, 244}, {140, 244}, {141,
    244}, {142, 232}, {143, 232}, {144, 232}, {145, 232}, {146,
    231}, {147, 231}, {148, 231}, {149, 231}, {150, 192}, {151,
    192}, {152, 192}, {153, 192}, {154, 128}, {155, 128}, {156,
    128}, {157, 128}, {158, 112}, {159, 112}, {160, 112}, {161,
    192}, {162, 192}, {163, 192}, {164, 192}, {165, 249}, {166,
    249}, {167, 249}, {168, 249}, {169, 257}, {170, 257}, {171,
    257}, {172, 257}, {173, 240}, {174, 240}, {175, 240}, {176,
    240}, {177, 214}, {178, 214}, {179, 214}, {180, 214}, {181,
    200}, {182, 200}, {183, 200}, {184, 200}, {185, 212}, {186,
    212}, {187, 212}, {188, 212}, {189, 201}, {190, 201}, {191,
    201}, {192, 201}, {193, 173}, {194, 173}, {195, 173}, {196,
    140}, {197, 140}, {198, 140}, {199, 140}, {200, 137}, {201,
    137}, {202, 137}, {203, 137}, {204, 149}, {205, 149}, {206,
    149}, {207, 149}, {208, 164}, {209, 164}, {210, 164}, {211,
    164}, {212, 203}, {213, 203}, {214, 203}, {215, 203}, {216,
    242}, {217, 242}, {218, 242}, {219, 242}, {220, 270}, {221,
    270}, {222, 270}, {223, 270}, {224, 275}, {225, 275}, {226,
    275}, {227, 275}, {228, 266}, {229, 266}, {230, 266}, {231,
    275}, {232, 275}, {233, 275}, {234, 275}, {235, 285}, {236,
    285}, {237, 285}, {238, 285}, {239, 291}, {240, 291}, {241,
    291}, {242, 291}, {243, 277}, {244, 277}, {245, 277}, {246,
    277}, {247, 271}, {248, 271}, {249, 271}, {250, 271}, {251,
    271}, {252, 271}, {253, 271}, {254, 271}, {255, 271}, {256,
    271}, {257, 271}, {258, 271}, {259, 271}, {260, 266}, {261,
    266}, {262, 266}, {263, 266}, {264, 195}, {265, 195}, {266,
    195}, {267, 195}, {268, 128}, {269, 128}, {270, 128}, {271,
    128}, {272, 193}, {273, 193}, {274, 193}, {275, 193}, {276,
    252}, {277, 252}, {278, 252}, {279, 276}, {280, 276}, {281,
    276}, {282, 276}, {283, 271}, {284, 271}, {285, 271}, {286,
    271}, {287, 256}, {288, 256}, {289, 256}, {290, 256}, {291,
    250}, {292, 250}, {293, 250}, {294, 250}, {295, 236}, {296,
    236}, {297, 236}, {298, 236}, {299, 211}, {300, 211}, {301,
    211}, {302, 211}, {303, 188}, {304, 188}, {305, 188}, {306,
    188}, {307, 165}, {308, 165}, {309, 165}, {310, 165}, {311,
    156}, {312, 156}, {313, 156}, {314, 153}, {315, 153}, {316,
    153}, {317, 153}, {318, 165}, {319, 165}, {320, 165}, {321,
    165}, {322, 191}, {323, 191}, {324, 191}, {325, 191}, {326,
    228}, {327, 228}, {328, 228}, {329, 228}, {330, 261}, {331,
    261}, {332, 261}, {333, 261}, {334, 267}, {335, 267}, {336,
    267}, {337, 267}, {338, 267}, {339, 267}, {340, 267}, {341,
    267}, {342, 267}, {343, 267}, {344, 267}, {345, 267}, {346,
    267}, {347, 266}, {348, 266}, {349, 266}, {350, 266}, {351,
    259}, {352, 259}, {353, 259}, {354, 259}, {355, 258}, {356,
    258}, {357, 258}, {358, 258}, {359, 251}, {360, 251}, {361,
    251}, {362, 251}, {363, 254}, {364, 254}, {365, 254}, {366,
    252}, {367, 252}, {368, 252}, {369, 252}, {370, 260}, {371,
    260}, {372, 260}, {373, 260}, {374, 275}, {375, 275}, {376,
    275}, {377, 275}, {378, 209}, {379, 209}, {380, 209}, {381,
    209}, {382, 136}, {383, 136}, {384, 136}, {385, 136}, {386,
    175}, {387, 175}, {388, 175}, {389, 175}, {390, 240}, {391,
    240}, {392, 240}, {393, 240}, {394, 267}, {395, 267}, {396,
    267}, {397, 267}, {398, 255}, {399, 255}, {400, 255}, {401,
    243}, {402, 243}, {403, 243}, {404, 243}, {405, 227}, {406,
    227}, {407, 227}, {408, 227}, {409, 218}, {410, 218}, {411,
    218}, {412, 218}, {413, 207}, {414, 207}, {415, 207}, {416,
    207}, {417, 196}, {418, 196}, {419, 196}, {420, 196}, {421,
    195}, {422, 195}, {423, 195}, {424, 195}, {425, 200}, {426,
    200}, {427, 200}, {428, 200}, {429, 214}, {430, 214}, {431,
    214}, {432, 214}, {433, 229}, {434, 229}, {435, 229}, {436,
    229}, {437, 256}, {438, 256}, {439, 256}, {440, 283}, {441,
    283}, {442, 283}, {443, 283}, {444, 285}, {445, 285}, {446,
    285}, {447, 285}, {448, 293}, {449, 293}, {450, 293}, {451,
    293}, {452, 294}, {453, 294}, {454, 294}, {455, 294}, {456,
    294}, {457, 294}, {458, 294}, {459, 294}, {460, 293}, {461,
    293}, {462, 293}, {463, 293}, {464, 278}, {465, 278}, {466,
    278}, {467, 278}, {468, 277}, {469, 277}, {470, 277}, {471,
    277}, {472, 266}, {473, 266}, {474, 266}, {475, 251}, {476,
    251}, {477, 251}, {478, 251}, {479, 250}, {480, 250}, {481,
    250}, {482, 250}, {483, 250}, {484, 250}, {485, 250}, {486,
    250}, {487, 250}, {488, 250}, {489, 250}, {490, 250}, {491,
    250}, {492, 239}, {493, 239}, {494, 239}, {495, 239}, {496,
    159}, {497, 159}, {498, 159}, {499, 159}, {500, 139}, {501,
    139}, {502, 139}, {503, 139}, {504, 215}, {505, 215}, {506,
    215}, {507, 215}, {508, 267}, {509, 267}, {510, 267}, {511,
    267}, {512, 289}, {513, 289}, {514, 289}, {515, 289}, {516,
    267}, {517, 267}, {518, 267}, {519, 267}, {520, 256}, {521,
    256}, {522, 256}, {523, 256}, {524, 222}, {525, 222}, {526,
    222}, {527, 194}, {528, 194}, {529, 194}, {530, 194}, {531,
    185}, {532, 185}, {533, 185}, {534, 185}, {535, 181}, {536,
    181}, {537, 181}, {538, 181}, {539, 195}, {540, 195}, {541,
    195}, {542, 195}, {543, 199}, {544, 199}, {545, 199}, {546,
    199}, {547, 199}, {548, 199}, {549, 199}, {550, 199}, {551,
    214}, {552, 214}, {553, 214}, {554, 214}, {555, 226}, {556,
    226}, {557, 226}, {558, 226}, {559, 255}, {560, 255}, {561,
    255}, {562, 268}, {563, 268}, {564, 268}, {565, 268}, {566,
    274}, {567, 274}, {568, 274}, {569, 274}, {570, 274}, {571,
    274}, {572, 274}, {573, 274}, {574, 274}, {575, 274}, {576,
    274}, {577, 274}, {578, 274}, {579, 268}, {580, 268}, {581,
    268}, {582, 268}, {583, 270}, {584, 270}, {585, 270}, {586,
    270}, {587, 260}, {588, 260}, {589, 260}, {590, 260}, {591,
    250}, {592, 250}, {593, 250}, {594, 250}, {595, 230}, {596,
    230}, {597, 230}, {598, 230}, {599, 227}, {600, 227}, {601,
    227}, {602, 227}, {603, 240}, {604, 240}, {605, 240}, {606,
    240}, {607, 240}, {608, 240}, {609, 240}, {610, 235}, {611,
    235}, {612, 235}, {613, 235}, {614, 156}, {615, 156}, {616,
    156}, {617, 156}, {618, 108}, {619, 108}, {620, 108}, {621,
    108}, {622, 190}, {623, 190}, {624, 190}, {625, 190}, {626,
    237}, {627, 237}, {628, 237}, {629, 237}, {630, 261}, {631,
    261}, {632, 261}, {633, 261}, {634, 242}, {635, 242}, {636,
    242}, {637, 242}, {638, 215}, {639, 215}, {640, 215}, {641,
    215}, {642, 191}, {643, 191}, {644, 191}, {645, 162}, {646,
    162}, {647, 162}, {648, 162}, {649, 160}, {650, 160}, {651,
    160}, {652, 160}, {653, 148}, {654, 148}, {655, 148}, {656,
    148}, {657, 147}, {658, 147}, {659, 147}, {660, 147}, {661,
    160}, {662, 160}, {663, 160}, {664, 160}, {665, 177}, {666,
    177}, {667, 177}, {668, 177}, {669, 211}, {670, 211}, {671,
    211}, {672, 211}, {673, 234}, {674, 234}, {675, 234}, {676,
    234}, {677, 252}, {678, 252}, {679, 252}, {680, 261}, {681,
    261}, {682, 261}, {683, 261}, {684, 261}, {685, 261}, {686,
    261}, {687, 261}, {688, 259}, {689, 259}, {690, 259}, {691,
    259}, {692, 245}, {693, 245}, {694, 245}, {695, 245}, {696,
    252}, {697, 252}, {698, 252}, {699, 252}, {700, 267}, {701,
    267}, {702, 267}, {703, 267}, {704, 278}, {705, 278}, {706,
    278}, {707, 278}, {708, 277}, {709, 277}, {710, 277}, {711,
    277}, {712, 267}, {713, 267}, {714, 267}, {715, 267}, {716,
    267}, {717, 267}, {718, 267}, {719, 267}, {720, 267}, {721,
    267}, {722, 267}, {723, 267}, {724, 267}, {725, 267}, {726,
    267}, {727, 267}, {728, 267}, {729, 259}, {730, 259}, {731,
    259}, {732, 259}, {733, 177}, {734, 177}, {735, 177}, {736,
    132}, {737, 132}, {738, 132}, {739, 132}, {740, 202}, {741,
    202}, {742, 202}, {743, 202}, {744, 258}, {745, 258}, {746,
    258}, {747, 258}, {748, 285}, {749, 285}, {750, 285}, {751,
    285}, {752, 278}, {753, 278}, {754, 278}, {755, 278}, {756,
    268}, {757, 268}, {758, 268}, {759, 268}, {760, 251}, {761,
    251}, {762, 251}, {763, 251}, {764, 242}, {765, 242}, {766,
    242}, {767, 251}, {768, 251}, {769, 251}, {770, 251}, {771,
    222}, {772, 222}, {773, 222}, {774, 222}, {775, 186}, {776,
    186}, {777, 186}, {778, 186}, {779, 164}, {780, 164}, {781,
    164}, {782, 164}, {783, 161}, {784, 161}, {785, 161}, {786,
    161}, {787, 177}, {788, 177}, {789, 177}, {790, 177}, {791,
    198}, {792, 198}, {793, 198}, {794, 198}, {795, 234}, {796,
    234}, {797, 234}, {798, 249}, {799, 249}, {800, 249}, {801,
    249}, {802, 249}, {803, 249}, {804, 249}, {805, 249}, {806,
    249}, {807, 249}, {808, 249}, {809, 249}, {810, 249}, {811,
    249}, {812, 256}, {813, 256}, {814, 256}, {815, 244}, {816,
    244}, {817, 244}, {818, 244}, {819, 239}, {820, 239}, {821,
    239}, {822, 239}, {823, 248}, {824, 248}, {825, 248}, {826,
    248}, {827, 256}, {828, 256}, {829, 256}, {830, 256}, {831,
    244}, {832, 244}, {833, 244}, {834, 244}, {835, 228}, {836,
    228}, {837, 228}, {838, 228}, {839, 225}, {840, 225}, {841,
    225}, {842, 225}, {843, 224}, {844, 224}, {845, 224}, {846,
    224}, {847, 222}, {848, 222}, {849, 222}, {850, 222}, {851,
    154}, {852, 154}, {853, 154}, {854, 128}, {855, 128}, {856,
    128}, {857, 128}, {858, 206}, {859, 206}, {860, 206}, {861,
    206}, {862, 262}, {863, 262}, {864, 262}, {865, 262}, {866,
    289}, {867, 289}, {868, 289}, {869, 289}, {870, 271}, {871,
    271}, {872, 271}, {873, 271}, {874, 244}, {875, 244}, {876,
    244}, {877, 244}, {878, 222}, {879, 222}, {880, 222}, {881,
    222}, {882, 206}, {883, 206}, {884, 206}, {885, 206}, {886,
    196}, {887, 196}, {888, 196}, {889, 183}, {890, 183}, {891,
    183}, {892, 183}, {893, 178}, {894, 178}, {895, 178}, {896,
    178}, {897, 172}, {898, 172}, {899, 172}, {900, 172}, {901,
    171}, {902, 171}, {903, 171}, {904, 171}, {905, 192}, {906,
    192}, {907, 192}, {908, 192}, {909, 213}, {910, 213}, {911,
    213}, {912, 213}, {913, 249}, {914, 249}, {915, 249}, {916,
    279}, {917, 279}, {918, 279}, {919, 279}, {920, 282}};

Q1: I would like to get the peak and valley in the graph and draw it,
Q2: I would like to find how many valleys are in this list,
Q3: I would like to get the first 200 points and minimum valleys.
This is what I've tried so far:
ListLinePlot[testdata]

Thanks for your help, I have been successful :)
this is my code
mins=Pick[testdata,MinDetect[testdata[[All,2]]],1];
maxs=Pick[testdata,MaxDetect[testdata[[All,2]]],1];
Show[ListLinePlot[testdata[[All,2]],Filling->Axis,AxesLabel->{number,ECG_Data}],ListPlot[maxs,PlotStyle->Red,PlotLegends->{"Peak"}],ListPlot[mins,PlotStyle->Blue,PlotLegends->{"Valley"}]]
Thr=200;

findpeak=Position[Differences[MaxDetect[testdata[[All,2]]]],-1];
findvalley=Position[Differences[MinDetect[testdata[[All,2]]]],-1];
peak=Extract[testdata,findpeak];
valley=Extract[testdata,findvalley];
valleysmin200=Select[valley,#[[2]]<Thr&];
f1=ListLinePlot[testdata,AxesLabel->{number,ECG_Data},Filling->Axis,FillingStyle->Automatic];
f2=ListPlot[peak,PlotStyle->{Red,PointSize[Large]},PlotLegends->{"Peak"}];
f3=ListPlot[valley,PlotStyle->{Blue,PointSize[Large]},PlotLegends->{"Valley"}];
f4=ListPlot[valleysmin200,PlotStyle->{Blue,PointSize[Large]},PlotLegends->{"Valley"}];
f5=ListLinePlot[Table[Thr,{Length[testdata]}],PlotStyle -> Pink];
Show[f1,f2,f3] (*modify peak & valley*)
Show[f1,f4,f5] (*valley<200*)
Length[valleysmin200]/2*12

A: Perhaps you could try this (only in the current version of Mathematica):
mins =  Pick[testdata, MinDetect[testdata[[All, 2]]], 1]
maxs =  Pick[testdata, MaxDetect[testdata[[All, 2]]], 1]

Show[ListLinePlot[testdata[[All, 2]], Filling -> Axis],
     ListPlot[mins, PlotStyle -> Red],
     ListPlot[maxs, PlotStyle -> Blue]]

A: This is my first answer at mma.se -- please bear with me... I'm still learning Mathematica!
Nevertheless, I'd like to share the following approach to find the extremal points in a list:
findExtremaPos[list_List] := Module[
  {signs, extremaPos, minPos, maxPos},
  signs = Sign[Differences[list]];
  signs = signs //. {a___, q_, 0, z__} -> {a, q, q, z};
  extremaPos = 1 + Accumulate@(Length /@ Split[signs]);
  If[First@signs == 1,
   minPos = extremaPos[[2 ;; -2 ;; 2]]; maxPos = extremaPos[[1 ;; -2 ;; 2]],
   minPos = extremaPos[[1 ;; -2 ;; 2]]; maxPos = extremaPos[[2 ;; -2 ;; 2]]
   ];
  {minPos, maxPos}
 ]

Basically, what the code does is taking the signs of the forward differences.
Whenever the sign changes, there should be either a minimum (from -1 to 1) or a maximum (from 1 to -1).
A possible pitfall arises when the forward differences take on 0, i.e. consecutive values in the initial list are exactly the same.
Here, I solve this issue by changing all 0-signs to the previous non-0-sign.
signs = signs //. {a___, q_, 0, z__} -> {a, q, q, z};

Effectively, this means that when a maximum or minimum is not sharp but forms a plateau only the position of the last value of the plateau is returned.
Here's an example that shows:

*

*the code is working

*what happens when the extremum forms a plateau

Example:
data = {1, 2, 1, 1, 3, 4, 3, 3, 3, 2, 1, 0, -1, 0, 1, 2, 3};
{minPos, maxPos} = findExtremaPos[data];
ListPlot[data, Joined -> True,
 Epilog -> {PointSize[Large],
   Red, Point[{#, data[[#]]} & /@ minPos],
   Blue, Point[{#, data[[#]]} & /@ maxPos]},
 PlotRange -> All
]

A: A fast functional implementation
Here is a functional implementation which I think should be fairly fast:
Clear[localExtremaPositionsUnique, localExtremaPositions];
localExtremaPositionsUnique[lst_List, type : (Min | Max) : Min] :=
   Pick[Range[Length[lst] - 2] + 1,
     Differences[Sign[Differences@lst] + 1],
     If[type === Min, 2, -2]
   ];

localExtremaPositions[lst_, type : (Min | Max) : Min, uniqueF_: localExtremaPositionsUnique] :=
With[{split = Split[lst]},
    With[{lengths = Length /@ split, unique  = split[[All, 1]]},
      Transpose[MapAt[# + 1 &, #, 1] &@Partition[#, Length[#]/2] &@
        Accumulate[lengths][[Flatten[{#, # + 1}] &@uniqueF[unique,type] - 1]]
      ]]];

The first function works for data which does not have valleys. The second function works for data with valleys and uses the first one.
Usage
Here is what it gives for your data:
localExtremaPositions[testdata[[All,2]],Min]

(*
  {{43,46},{90,93},{123,125},{158,160},{181,184},{200,203},{228,230},
   {268,271},{314,317},{359,362},{366,369},{382,385},{421,424},{500,503},
   {535,538},{579,582},{599,602},{618,621},{657,660},{692,695},{736,739},
   {764,766},{783,786},{819,822},{854,857},{901,904}}
*)

localExtremaPositions[testdata[[All,2]],Max]

(*
   {{11,14},{59,62},{115,118},{138,141},{169,172},{185,188},{224,227},
   {239,242},{279,282},{334,346},{363,365},{374,377},{394,397},{452,459},
   {512,515},{566,578},{583,586},{603,609},{630,633},{680,687},{704,707},
   {748,751},{767,770},{812,814},{827,830},{866,869}}
*)

It returns a list of position intervals for valleys of minima or maxima.
Benchmarks
Here is some power test:
large = RandomInteger[100,10^5];

(ints = localExtremaPositions[large,Min]);//AbsoluteTiming

(* {0.095703,Null} *)

Let us compare with the MinDetect-based solution:
(pos= Pick[Range[Length[large ]],MinDetect[large] ,1]);//AbsoluteTiming

(* {0.999023,Null}  *)

We can see that the results are the same (although my code gives intervals while the one which uses MinDetect gives individual positions), by executing
Flatten[Range@@@ints]==pos

(*  True  *)

So, at least for this particular sample, it appears that the above top-level functional implementation is an order of magnitude more efficient than a built-in function - a rare case.

A: Cormullion's solution, which invokes built-in procedures MinDetect and MaxDetect, can be made to work in earlier versions of Mathematica than 9.0 using identically named (but differently functional) procedures.  Image processing functionality was introduced in version 7 and included in that are MinDetect and MaxDetect for finding "regional" or "extended" extrema.
The idea is to represent this one-dimensional data series as a 2D image by replicating it in the second dimension.  Although two rows will do, I use more here in order increase the visibility of the images, which otherwise would be too slender to see well.  First convert the data into an image:
nrow = 32;
i = Image[SparseArray[Flatten[Table[{i, #1} -> #2 , {i, 1, nrow}] & @@@ testdata]]] // ImageAdjust

(ImageAdjust makes the data visible by means of a linear rescaling of values, which will not change the locations of any extrema.)

This immediately makes available some intriguing ways to visualize the extrema, such as with a strip-like chart:
ColorCombine[{MaxDetect[i], i, MinDetect[i]}]

In this case blues mark minima and yellows mark maxima, all superimposed on a graduated green representation of the data.
We can readily post-process the images of "peaks" and "valleys" to obtain more traditional representations of the locations of extrema, such as sorted lists of those positions:
{minima, maxima} = Flatten[Position[First[ImageData[#[i]]], 1]] & /@ {MinDetect, MaxDetect};

Show[ListPlot[testdata, Joined -> True, PlotStyle -> Gray],
 ListPlot[testdata[[minima]], PlotStyle -> Red],
 ListPlot[testdata[[maxima]], PlotStyle -> Blue],
 AxesOrigin -> Min /@ (testdata\[Transpose])]

Number of valleys:
Length[minima]

$106$

"First 200 points and minimum valleys": I'm not sure what this means, but obviously we have obtained the relevant information in a sufficiently convenient form to answer any such questions, however they might be interpreted.
Although this is a cute method (and might inspire some compact and effective visualizations), it is relatively slow: about 0.014 seconds are needed to obtain the minima and maxima lists for this short sequence of data.  About $10^5$ points can be processed per second.


text:
Q: Single Sign-On using Asp.net MVC 4 and Web Api We are devloping application looks like Google login. for example if you login Gmail and open Play Store in  another tab it will automatically login playstore.
we want to develop similar application using ASP.Net MVC 4 and WEB API & JQuery.

*

*User Flow (Login using username and password) - after login access member details

*Client Flow (Client Secret and Client Id) - Authenticate HTML, Javascrip and CSS

If you have any suggestions on below approach.
1. OAuth 2.0 and Owin Middleware
2. Token base approach
3. to get HTML and Javascript using token by site.
4. cross domain token handling
if you have any sample for Resource server, here resource server is HTML, Javascript and CSS

A: For the User Flow, you can use OpenIdConnect Middleware: https://github.com/AzureADSamples/WebApp-OpenIDConnect-DotNet. There are many additional samples in AzureADSamples.
Fore the Client Flow, this sample give a good example: https://github.com/AzureADSamples/WebApp-WebAPI-OAuth2-AppIdentity-DotNet.


text:
Q: Deserializing XML with defined ENTITY to objects using XStream / StaxDriver i want to de-serialize the XML file to java/groovy objects using XStream.
XML file has ENTITY defined. So I used the StaxDriver to resolve entities automatically. But StaxDriver/XStream ignore/remove partial contents.

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE parent [
<!ENTITY File_file SYSTEM "File_file.xml">
]>

<parent>
 <name>NAME</name>
 <description>DSCRIPTION</description>
 <context>
     <files>
&File_file;
</files>
 </context>
</parent>

After de-serialize and print as XML again: Expected is:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
 <name>NAME</name>
 <description>DSCRIPTION</description>
   <context>
      <files>
<file>
    <name>name</name>
    <path>location path</path>
</file>
      </files>
   </context>
</parent>

but I see below:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
 <name>NAME</name>
 <description>DSCRIPTION</description>
   <context>
      <files>
<file>
</file>
      </files>
   </context>
</parent>

Code/logic to deserialize xml content.
    public class Parser {

public static void main(String[] args) {
    if (args.length != 1) {
        System.out.println("Usage:Parser <Input File>");
        return;
    }
    XStream xstream = new XStream(new StaxDriver());
    xstream.alias("parent", Parent.class);
    xstream.alias("context", Context.class);
    xstream.alias("files", Files.class);
    xstream.addImplicitCollection(Files.class, "files");
    xstream.alias("files", File.class);
    String xml = Util.getFileText(args[0]);//file.text;
    System.out.println(xml);
    Parent te = (Parent)xstream.fromXML(xml);
    System.out.println(XmlUtil.serialize(xstream.toXML(te)));
}

}

A: Issue was identified as File.class referred in XStream alias() for transformation. Instead of using local com.app.model.File.class, java.io.File.class used which caused the parser/xstream not to transform the tags, eventually removes it.


text:
Q: Is there a way to define more than one itemtemplate in the default treeview? Or is my only option to extend the original treeview if I want that capability?
I want something like this, but with the two itemspresenters having two different templates defined so that they both use the same items, but apply a different template to create controls in those two spots.
        <ControlTemplate>
          <Grid>
            <wpfExp:SignalNameBox x:Name="TreeViewTimeTextBox" Grid.Row="0" Grid.Column="0"
                  Height="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path=GraphHeight}"
                  Width="200"
                  Margin="19,0,0,0"
                  MainText="Time"
                />
            <wpfExp:SignalGraphAxis
                x:Name="signal_axis"
                VerticalAlignment="Stretch"
                HorizontalAlignment="Stretch"
                GraphHeight="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path=GraphHeight}"
                MinWidth="10"
                MinHeight="10"
                PenColor="{Binding ElementName=AxisColorPicker, Path=SelectedColor, Mode=OneWay}"
                PenWidth="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path=GraphPenWidth, Mode=OneWay}"
                MaxTimeValue="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path=_SignalDataViewModel.MaxTimeValue}"
                TimeUnit="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path = TimeUnit}"
                AxisDivisionUnit="{Binding RelativeSource = {RelativeSource AncestorType={x:Type wpfExp:GraphViewer}}, Path = AxisDivisionUnit}"
                />
            <StackPanel>
              <ItemsPresenter/>
            </StackPanel>
            <ScrollViewer HorizontalScrollBarVisibility="Auto"  VerticalScrollBarVisibility="Auto">
              <StackPanel>
                <ItemsPresenter/>
              </StackPanel>
            </ScrollViewer>
          </Grid>
        </ControlTemplate>

A: A simplest example I am taking here is to show Contacts with different background color based on their sex(Male/Female).
So this is how the ItemTemplateSelector class will look
class MyDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item != null)
        {
            Contact objContact = item as Contact ;

            switch (objContact.Sex)
            {
                case "Male": return App.Current.MainWindow.FindResource("TemplateMale") as DataTemplate;
                case "Female": return App.Current.MainWindow.FindResource("TemplateFemale") as DataTemplate;
            }
        }

        return null;
    }
}

and this is how you can use it in your XAML
<Window.Resources>
    <local:MyDataTemplateSelector x:Key="myTemplateSelector"></local:MyDataTemplateSelector>

    <DataTemplate x:Key="TemplateMale">
        <TextBlock Background="Blue" Text="{Binding Name}"></TextBlock>
    </DataTemplate>
    <DataTemplate x:Key="TemplateFemale">
        <TextBlock Background="Pink" Text="{Binding Name}"></TextBlock>
    </DataTemplate>
</Window.Resources>

<TreeView ItemsSource="{Binding Contacts}"
          ItemTemplateSelector="{StaticResource myTemplateSelector}">
</TreeView>


text:
Q: Draw a triangle at a specific Longitude and Latitude on Google Maps I'm trying to draw a triangle in meters at specific latitude and longitude. The example Google give is quite obvious on how to draw polygons, however it uses longitude and latitude to specify the points of the polygon.
Is there a way to draw a triangle/polygon at a specific lon/lat but specify the points in meters?
Like how you use the API to draw a circle at a long/lat point but specify the radius in meters.

A: You can convert degrees to  meters with 1° ~  111 km at Equator.
As you go towards pole the lines of longitude converge and you will need to use the following table to compensate for this.
Degrees     Lat         Lng
0° Equator  110.574 km  111.320 km
15°         110.649 km  107.551 km
30°         110.852 km  96.486 km
45°         111.132 km  78.847 km
60°         111.412 km  55.800 km
75°         111.618 km  28.902 km
90° Pole    111.694 km  0.000 km


text:
Q: Algebraic integers Could someone please explain to me why
$ \mathbb{F}_p [X] / \langle\bar{f_\alpha} (X)\rangle \,\ \cong \,\ \mathbb{Z}[X] / \langle p, f_\alpha (X) \rangle \,\ \cong  \,\ \mathbb{Z} [\alpha] / \langle p\rangle $?
Where $p$ is prime in $\mathbb{Z}$,  $ \bar{f_\alpha} $ is the polynomial obtained by taking the coefficients of $ f_\alpha $ modulo p (and $ f_\alpha $ is the minimal polynomial of $\alpha$ in $ \mathbb{Z}[X] $)

I know that $ \mathbb{F_p} \cong \mathbb{Z}/p\mathbb{Z} $.
Thanks.

A: The map $\mathbb{Z}\to\mathbb{F}_p$ given by reduction modulo $p$ induces a homomorphism $\mathbb{Z}[x]\to\mathbb{F}_p[x]$ (reducing coefficients modulo $p$); this is the universal property of the polynomial ring.
Now consider the composite map
$$\mathbb{Z}[x] \to \mathbb{F}_p[x] \to \frac{\mathbb{F}_p[x]}{\langle \overline{f_{\alpha}(x)}\rangle}.$$
The map is onto, because the induced map $\mathbb{Z}[x]\to\mathbb{F}_p[x]$ is onto, and the canonical projection is onto. By the isomorphism theorems, you know that $\mathbb{F}_p[x]/\langle \overline{f_{\alpha}(x)}\rangle$ is isomorphic to the quotient of $\mathbb{Z}[x]$ modulo the kernel of the map.
It should be clear that the kernel contains both $p$ and $f_{\alpha}(x)$. So you just need to show that this is the entire kernel. If $g(x)$ lies in the kernel, then $g(x)\equiv f_{\alpha}(x)\pmod {p}$; this tells you that you can express $g(x)$ as a multiple of $f_{\alpha}(x)$ up to multiples of $p$ in the coefficients, which gives the equality you want.
For the other isomorphism, consider the map $\mathbb{Z}[x]\to\mathbb{Z}[\alpha]$ obtained by "evaluation at $\alpha$". The kernel of this map is precisely the ideal generated by the minimal polynomial of $\alpha$, so
$$\mathbb{Z}[\alpha]\cong\frac{\mathbb{Z}[x]}{\langle f_{\alpha}(x)\rangle}.$$
Under this isomorphism, $p + \langle f_{\alpha}(x)\rangle$ maps to $p$ in $\mathbb{Z}[\alpha]$, so the isomorphism theorem tells you that the ideal corresponding to $(p+\langle f_{\alpha}(x)\rangle)$ in the quotient corresponds to the ideal of $\mathbb{Z}[x]$ generated by $p$ and $f_{\alpha}(x)$; this gives the second isomorphism.

A: In a nutshell, all of these rings are made of polynomials in one variable where you add the condition that $p = 0$ and $f_{\alpha}(X) = 0$ (making $X$ a root of $f_{\alpha}$). In the first one, you cancel $p$ then $f_{\alpha}(X)$ (which becomes $\overline{f_{\alpha}}$ once you cancel $p$), in the third you cancel $f_{\alpha}(X)$ then $p$, and in the second, you do it simultaneously. You can easily check that the order does not matter (and give explicit isomorphisms).


text:
Q: Как составить рейтинг пользователей? У пользователей есть показатели, такие как кол-во матчей, кол-во побед и подобные.. Мне надо составить рейтинг узнать место пользователя в нём, например, по кол-ву побед, но как это сделать? Даже если отсортировать queryset по победам, то получить место пользователя по счету, как я понял, не получится. Как можно это сделать?

A: Не совсем понял почему не получится? Ты можешь создать модель, скажем, UserWithStats и сделать сортировку по убыванию побед. Тогда, первый пользователь в QuerySet[] окажется победителем. Но это в случае, если у тебя нет одинакового количества побед (тогда придётся выдавать первые места нескольким людям или вводить дополнительные филды и сортировать по ним ещё)
class UserWithStats(models.Model):
    name = models.CharField(...)
    wins = models.IntegerField()
    class Meta:
        ordering = ["-wins"]