Get minimum value in an array and then get index - arrays

I want to get the minimum value in an array and then get the index of that item, in one step without writing my own loop (if I have to please let me know).
I know I can just do the
$b = ($a | Measure -Minimum).Minimum
But then I have to do
[array]::IndexOf($a, $b)
And while that is normally okay, I'm looking for a way to do it once because I'm running this MANY MANY times in a loop.
Thanks!
EDIT: One step meaning without looping through the array twice

Personally, I might consider a different data structure. Maybe something sorted to begin with...
This code may work for your needs:
$myArray = 5,66,4,33,2,9,9,12
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
"MinIndex $minIndex = MinValue $minValue"

its a problem of type, try like this:
$myArray = [int[]]5,66,4,33,2,9,9,12
$minvalue=[int]($myArray | measure -Minimum).Minimum
$myArray.IndexOf($minvalue)

Here are 6 different options for you...
cls
$myArray = #(5,66,4,33,2,9,9,12)
$iterations = 50000
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minValue = [int]($myArray | Measure-Object -Minimum).Minimum
$minIndex = $myArray.IndexOf($minValue)
}
}).TotalSeconds
"measure-object with indexOf: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
}
}).TotalSeconds
"pipeline with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = 0
$minValue = [int]::MaxValue
foreach ($index in 0..($myArray.count-1)) {
if ($myArray[$index] -lt $minValue) {
$minValue = $myArray[$index]
$minIndex = $index
}
}
}
}).TotalSeconds
"foreach-loop with compare: $t"
$t = (measure-command{
foreach ($i in 1..$iterations) {
$h = [System.Collections.ArrayList]::new()
foreach ($index in 0..($myArray.count-1)) {
$null = $h.add([tuple]::Create($myArray[$index], $index))
}
$h.Sort()
$minIndex = $h[0].Item2
}
}).TotalSeconds
"quicksort of a list of tuples: $t"
Add-Type -TypeDefinition #"
using System;
using System.Linq;
public static class My {
public static int indexOfMin(int[] arr){
int min = arr.Min();
return Array.IndexOf(arr, min);
}
}
"#
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minIndex = [my]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and IndexOf: $t"
Add-Type #"
public static int[] indexOfMin(int[] arr){
int min = int.MaxValue;
int minIndex = 0;
for (int i = 0; i < arr.Length; i++) {
if (arr[i]<min) {
min = arr[i];
minIndex = i;
}
}
return new int[] {min, minIndex};
}
"# -name My2 -Namespace System
$t = (measure-command{
foreach ($i in 1..$iterations) {
$minValue, $minIndex = [my2]::indexOfMin($myArray)
}
}).TotalSeconds
"custom type and looping: $t"

Related

sqlsrv_fetch_array() expects parameter 1 to be resource, object given

Good Day,
I was looking for the solution of this code. But unfortunately I couldn`t fix it hope someone can enlighten me on this matter.
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
return "None";
}
}
and this is the other one they have both same errors
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
$charinfo['Name'] = 'None';
return $charinfo;
}
}
I just fund out the error was because of my Condition and it only appears if the query doesn`t have a result. Please check below for the fix that I did:
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
if($char_result->num_rows()<=0){
return 'None';
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
}
}
and
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
if($char_result->num_rows()<=0){
$charinfo['Name'] = 'None';
return $charinfo;
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
}
}

When changing templates on custom block the content gets deleted from the DB

I have a custom block for Concrete5 I built which uses multiple template files associated with it. If I apply the template to the block when I am initially adding the block to the page everything works fine. However if I then try to change templates after the block has already been set I run into issues. When saving changes with the new template, all my content gets deleted from the DB; so everything in that current row equals null except the block id "bID", the bID will change to the next increment.
I do not know why this happens!! I feel like I ran into a similar a long time ago but don't remember how it was resolved. Any advice would be great!
My template files are just standard html in a php file with the <?php defined('C5_EXECUTE') or die("Access Denied."); ?> at the top of the file.
My controller (which is my suspect for the issue right now) look like this:
<?php
namespace Concrete\Package\ThemeCaboodle\Block\GridBlock;
use Concrete\Core\Block\BlockController;
use Database;
use Page;
use Concrete\Core\Editor\LinkAbstractor;
use Core;
use File;
use View;
use BlockType;
class Controller extends BlockController
{
public $defaultBlockClassList = '';
public $defaultEntriesClassList = 'unit-md-4';
protected $btTable = 'btGrid';
protected $btExportTables = array('btGrid', 'btGridEntries');
protected $btInterfaceWidth = "600";
protected $btWrapperClass = 'ccm-ui';
protected $btInterfaceHeight = "550";
protected $btCacheBlockRecord = true;
protected $btExportFileColumns = array('thumbnailFID');
protected $btCacheBlockOutput = true;
protected $btCacheBlockOutputOnPost = true;
protected $btCacheBlockOutputForRegisteredUsers = false;
protected $btIgnorePageThemeGridFrameworkContainer = true;
public function getBlockTypeDescription()
{
return t("Easily add a grid with prebuilt templates to your site using the grid block");
}
public function getBlockTypeName()
{
return t("Grid");
}
public function getFileObject($fID) {
return File::getByID($fID);
}
public function getSearchableContent()
{
$db = Database::get();
$rows = $db->Execute('SELECT * FROM btGridEntries WHERE bID = ?', array($this->bID));
$content = '';
foreach ($rows as $row) {
$content .= $row['title'].' ';
$content .= $row['description'].' ';
}
return $content;
}
public function view()
{
$this->set('entries', $this->getEntries());
$this->set('block', $this->getBlockData());
$this->addHeaderItem('<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>');
}
public function add()
{
$this->requireAsset('core/file-manager');
$this->requireAsset('core/sitemap');
$this->requireAsset('redactor');
}
public function edit()
{
$this->requireAsset('core/file-manager');
$this->requireAsset('core/sitemap');
$this->requireAsset('redactor');
$this->set('entries', $this->getEntries());
$this->set('block', $this->getBlockData());
}
public function composer()
{
$this->edit();
}
public function registerViewAssets($outputContent = '')
{
$al = \Concrete\Core\Asset\AssetList::getInstance();
$this->requireAsset('javascript', 'jquery');
}
public function duplicate($newBID)
{
parent::duplicate($newBID);
$db = Database::get();
$rows = $db->Execute('SELECT * FROM btGridEntries WHERE bID = ?', array($this->bID));
while ($row = $rows->FetchRow()) {
$db->execute('INSERT INTO btGridEntries (bID, thumbnailFID, fallbackFID, title, description, classList, buttonText, sortOrder, externalLinkURL, internalLinkCID, fileFID) values(?,?,?,?,?,?,?,?,?,?,?)',
array(
$newBID,
$row['ENTRY_thumbnailFID'],
$row['ENTRY_fallbackFID'],
$row['ENTRY_title'],
$row['ENTRY_description'],
$row['ENTRY_classList'],
$row['ENTRY_buttonText'],
$row['ENTRY_sortOrder'],
$row['ENTRY_externalLinkURL'],
$row['ENTRY_internalLinkCID'],
$row['ENTRY_fileFID']
)
);
}
}
public function delete()
{
$db = Database::get();
$db->delete('btGridEntries', array('bID' => $this->bID));
parent::delete();
}
public function save($args)
{
$db = Database::get();
$db->execute('DELETE from btGridEntries WHERE bID = ?', array($this->bID));
parent::save($args);
if (isset($args['ENTRY_sortOrder'])) {
$count = count($args['ENTRY_sortOrder']);
$i = 0;
while ($i < $count) {
$externalLinkURL = $args['ENTRY_externalLinkURL'][$i];
$internalLinkCID = $args['ENTRY_internalLinkCID'][$i];
$fileFID = $args['ENTRY_fileFID'][$i];
switch (intval($args['ENTRY_linkType'][$i])) {
case 1:
$externalLinkURL = '';
$fileFID = 0;
break;
case 2:
$internalLinkCID = 0;
$fileFID = 0;
break;
case 3:
$externalLinkURL = '';
$internalLinkCID = 0;
break;
default:
$externalLinkURL = '';
$internalLinkCID = 0;
$fileFID = 0;
break;
}
if (isset($args['ENTRY_description'][$i])) {
$args['ENTRY_description'][$i] = LinkAbstractor::translateTo($args['ENTRY_description'][$i]);
}
$db->execute('INSERT INTO btGridEntries (bID, thumbnailFID, fallbackFID, title, description, classList, buttonText, sortOrder, externalLinkURL, internalLinkCID, fileFID) values(?,?,?,?,?,?,?,?,?,?,?)',
array(
$this->bID,
intval($args['ENTRY_thumbnailFID'][$i]),
intval($args['ENTRY_fallbackFID'][$i]),
$args['ENTRY_title'][$i],
$args['ENTRY_description'][$i],
$args['ENTRY_classList'][$i],
$args['ENTRY_buttonText'][$i],
$args['ENTRY_sortOrder'][$i],
$externalLinkURL,
$internalLinkCID,
$fileFID
)
);
++$i;
}
}
}
public function getBlockAssetPath() {
$bt = BlockType::getByHandle('buckets_block');
return Core::make('helper/concrete/urls')->getBlockTypeAssetsURL($bt);
}
public function getBlockData()
{
$db = Database::get();
$row = $db->GetRow('SELECT * FROM btGrid WHERE bID = ?', array($this->bID));
if ($row['bgFID']) {
$row['BG'] = \File::getByID($row['bgFID'])->getVersion()->getRelativePath();
}
return $row;
}
public function getEntries()
{
$v = View::getInstance();
$db = Database::get();
$rows = $db->GetAll('SELECT * FROM btGridEntries WHERE bID = ? ORDER BY sortOrder', array($this->bID));
// in view mode, linkURL takes us to where we need to go whether it's on our site or elsewhere
$entries = array();
foreach ($rows as $row) {
// Generate the URL based on what the linkType is
if ($row['externalLinkURL'] =='' && !$row['fileFID'] && $row['internalLinkCID']) {
$c = Page::getByID($row['internalLinkCID'], 'ACTIVE');
$row['linkURL'] = $c->getCollectionLink();
} elseif ($row['externalLinkURL'] =='' && !$row['internalLinkCID'] && $row['fileFID']) {
$f = File::getByID($row['fileFID']);
$row['linkURL'] = $f ? $f->getVersion()->getRelativePath() : '';
} elseif ($row['externalLinkURL']!='') {
$row['linkURL'] = $row['externalLinkURL'];
} else {
$row['linkURL'] = '';
}
// Thumbnail
$thumbnail = $row['thumbnailFID'] ? File::getByID($row['thumbnailFID'])->getVersion()->getRelativePath() : $v->getThemePath().'/no-image.jpg';
$row['thumbnail'] = $thumbnail;
$fallback = $row['fallbackFID'] ? File::getByID($row['fallbackFID'])->getVersion()->getRelativePath() : $v->getThemePath().'/no-image.jpg';
$row['fallback'] = $fallback;
$row['description'] = LinkAbstractor::translateFrom($row['description']);
$entries[] = $row;
}
return $entries;
}
public function getClassList($string) {
$array = explode(',',$string);
if (count($array) > 0) {
return implode(' ',$array);
}
}
}
I apologize for the pretty long file in advance ;) i just want to make sure you can see all possible issues
I think your problem is that in the duplicate function, once you got your results back from your select you put an ENTRY_ prefix everywhere like in $row['ENTRY_thumbnailFID'] when it should really be $row['thumbnailFID'] according to your screenshot

How can I display the max value array, edited in a class

I need to find the worker with highest salary in PHP and display only him (his name, position and salary). Made several tries in the IF statement but none of them lead to what i needed.
class Workers {
public $name;
public $position;
public $salary;
private function Workers($name, $position, $salary){
$this->name = $name;
$this->position = $position;
$this->salary = $salary;
}
public function newWorker($name, $position, $salary){
// if ( ) {
return new Workers($name, $position, $salary);
// }
// else return NULL;
}
}
$arr = array();
$arr[] = Workers::newWorker("Peter", "work1", 600);
$arr[] = Workers::newWorker("John", "work2", 700);
$arr[] = Workers::newWorker("Hans", "work3", 550);
$arr[] = Workers::newWorker("Maria", "work4", 900);
$arr[] = Workers::newWorker("Jim", "work5", 1000);
print_r($arr);
This is my code and like that it will display all workers i have created but i need to output only the one with highest salary (worker 5 - Jim with 1000 salary)
You can use this snippet:
$max = null;
foreach ($arr as $worker) {
$max = $max === null ? $worker : ($worker->salary > $max->salary ? $worker : $max);
}
Or this, as more clarity:
$max = null;
foreach ($arr as $worker) {
if (!$max) {
$max = $worker;
} elseif ($worker->salary > $max->salary) {
$max = $worker;
}
}
$max now contains a worker with maximum salary.

Multidimensional arrays and for loops

i have this code >
if ($firstDayOfTheMonth == "Monday")
{
$eachDay["monday1"]="1st";
$eachDay["tuesday1"]="2nd";
$eachDay["wednesday1"]="3rd";
$eachDay["thursday1"]="4th";
$eachDay["friday1"]="5th";
$eachDay["saturday1"]="6th";
$eachDay["sunday1"]="7th";
$eachDay["monday2"]="8th";
$eachDay["tuesday2"]="9th";
$eachDay["wednesday2"]="10th";
$eachDay["thursday2"]="11th";
$eachDay["friday2"]="12th";
$eachDay["saturday2"]="13th";
$eachDay["sunday2"]="14th";
$eachDay["monday3"]="15th";
$eachDay["tuesday3"]="16th";
$eachDay["wednesday3"]="17th";
$eachDay["thursday3"]="18th";
$eachDay["friday3"]="19th";
$eachDay["saturday3"]="20th";
$eachDay["sunday3"]="21st";
$eachDay["monday4"]="22nd";
$eachDay["tuesday4"]="23rd";
$eachDay["wednesday4"]="24th";
$eachDay["thursday4"]="25th";
$eachDay["friday4"]="26th";
$eachDay["saturday4"]="27th";
$eachDay["sunday4"]="28th";
$eachDay["monday5"]="29th";
$eachDay["tuesday5"]="30th";
$eachDay["wednesday5"]="31st";
}
and i wondered if anyone could help me condense it down into a loop?
The code is far too long and messy and i would love to shorten it down
One probable implementation assuming its perl
use strict;
sub dayHash {
my $firstDayOfMonth = lc(shift);
my #days = qw(monday tuesday wednesday thursday friday saturday sunday);
my $start = -1;
my $i;
for ( $i = 0; $i < $#days; $i++ ) {
if ( $firstDayOfMonth eq $days[$i] ) {
$start = $i;
last;
}
}
my %eachDay = ();
my $suffix = 1;
my $key;
my $val;
for ( $i = 1; $i <= 31; $i++ ) {
$key = "$days[$start++]$suffix";
if ( $start > $#days ) {
$start = 0;
$suffix++;
}
if ( ($i % 10) == 1 && int($i / 10) != 1 ) {
$val = $i. 'st';
} elsif ( ($i % 10) == 2 && int($i / 10) != 1 ) {
$val = $i . 'nd';
} elsif ( ($i % 10) == 3 && int($i / 10) != 1 ) {
$val = $i . 'rd';
} else {
$val = $i . 'th';
}
$eachDay{$key} = $val;
}
return %eachDay
}
my $firstDayOfMonth = "Monday";
my %eachDay = dayHash($firstDayOfMonth);

Passing multiple variables to parameter

Syntax:
New-VirtualSwitch [-VMHost] [-Name] [[-NumPorts] ] [[-Nic] String[]]
I am using the above cmdlet to add a new vSwitch in vSphere, where my knowledge lacks is how to use four checkbox that represent four NICs and when checked are passed to the -Nic parameter.
For instance the below wouldn't work
New-VirtualSwitch -VMHost $comboBox611.SelectedItem.toString() -Name $textBox611.Text -NumPorts 200 **-Nic $nic0,$nic1,$nic2,$nic3** -Mtu $textBox612.Text -Confirm
How do I pass the variables of each checkbox to a string array as the syntax shows it can be done?
$handler_linkLabel601_LinkClicked=
{
if ($networkdataGridView.CurrentRow.Cells['VM Host'].Value.toString() -gt " ")
{
Add-Type -AssemblyName System.Windows.Forms
$form601 = New-Object Windows.Forms.Form
$form601.Size = New-Object Drawing.Size (250,270)
$form601.StartPosition = "CenterScreen"
$label611.Size = New-Object Drawing.Size (70,40)
$label611.Location = New-Object System.Drawing.Size (10,15)
$label611.Text = "vSwitch Name:"
$textBox611.Size = New-Object Drawing.Size (100,30)
$textBox611.Location = New-Object System.Drawing.Size (90,15)
$textBox611.Name = "vSwitch Name"
$label612.Size = New-Object Drawing.Size (50,20)
$label612.Location = New-Object System.Drawing.Size (10,55)
$label612.Text = "Host:"
$vmhostlist = Get-VMHost
foreach ($vmhost in $vmhostlist)
{
$comboBox611.Items.add($vmhost.name.toString())
}
$comboBox611.Size = New-Object Drawing.Size (100,20)
$comboBox611.Location = New-Object System.Drawing.Size (90,50)
$checkBox611.Size = New-Object Drawing.Size (20,20)
$checkBox611.Location = New-Object System.Drawing.Size (100,80)
# Add Click-Event
$checkBox611.Add_CheckStateChanged({
If ($checkBox611.Checked) {
$global:nic0 = "vmnic0"
} Else {
$global:nic0 = ""
}
})
$checkBox612.Size = New-Object Drawing.Size (20,20)
$checkBox612.Location = New-Object System.Drawing.Size (170,80)
$checkBox611.Add_CheckStateChanged({
If ($checkBox611.Checked) {
$global:nic1 = "vmnic1"
} Else {
$global:nic1 = ""
}
})
$checkBox613.Size = New-Object Drawing.Size (20,20)
$checkBox613.Location = New-Object System.Drawing.Size (100,100)
$checkBox611.Add_CheckStateChanged({
If ($checkBox611.Checked) {
$global:nic2 = "vmnic2"
} Else {
$global:nic2 = ""
}
})
$checkBox614.Size = New-Object Drawing.Size (20,20)
$checkBox614.Location = New-Object System.Drawing.Size (170,100)
$checkBox611.Add_CheckStateChanged({
If ($checkBox611.Checked) {
$global:nic3 = "vmnic3"
} Else {
$global:nic3 = ""
}
})
$label613.Size = New-Object Drawing.Size (80,20)
$label613.Location = New-Object System.Drawing.Size (10,140)
$label613.Text = "MTU Size:"
$textBox612.Size = New-Object Drawing.Size (100,20)
$textBox612.Location = New-Object System.Drawing.Size (90,140)
$textBox612.Name = "MTU"
$button = New-Object System.Windows.Forms.Button
$button.Size = New-Object Drawing.Size (90,30)
$button.Location = New-Object System.Drawing.Size (70,200)
$selectedvmhost = ($comboBox611.SelectedItem.toString())
$button.add_click({test})
$button.Text = "Add New vSwitch"
$form601.Controls.Add($button)
$form601.Controls.Add($textBox611)
$form601.Controls.Add($textBox612)
$form601.Controls.Add($label611)
$form601.Controls.Add($label612)
$form601.Controls.Add($label613)
$form601.Controls.Add($comboBox611)
$form601.Controls.Add($checkBox611)
$form601.Controls.Add($checkBox612)
$form601.Controls.Add($checkBox613)
$form601.Controls.Add($checkBox614)
$form601.ShowDialog()
}
ELSE
{}
}
function test
{
$nic = #($global:nic0,$global:nic1,$global:nic2,$global:nic3 | ? {-not [string]::IsNullOrEmpty($_)})
if ( $nic.count )
{
New-VirtualSwitch -VMHost $comboBox611.SelectedItem.toString() -Name $textBox611.Text -NumPorts 200 -Nic $nic -Mtu $textBox612.Text -Confirm
}
}
just as C.B. said replace $nic0 with $global:nic0, and $nic1 with $global:nic1 etc.
then test is
function test
{
$nic = #($global:nic0,$global:nic1,$global:nic2,$global:nic3 | ? {-not [string]::IsNullOrEmpty($_)})
if ( $nic.count )
{
New-VirtualSwitch -VMHost $comboBox611.SelectedItem.toString() -Name $textBox611.Text -NumPorts 200 -Nic $nic -Mtu $textBox612.Text -Confirm
}
}

Resources