Wednesday 30 September 2020

golang 9 struct

 package main

import "fmt"

type Point struct {
x int32
y int32
}

type Circle struct {
radius float64
center *Point
}

func main() {
c1 := Circle{1.5, &Point{2, 3}}
fmt.Println(c1)
fmt.Println(c1.center)
fmt.Println(c1.center.x, c1.center.y)
}

//cmd
C:\Users\bob\golang1>go run tutorial.go
{1.5 0xc0000120a0}
&{2 3}
2 3

reference:

Monday 28 September 2020

golang 8 pointer reference

 package main

import "fmt"

func pointer_func(str *string) {
*str = "value changed by pointer"
}

func string_func(str string) string {
str = "value is unchanged, but new string is returned by string_func"
return str
}

func main() {
value := "old value"
string_value := string_func(value)
fmt.Println(value, "\n", string_value)
pointer_func(&value)
fmt.Println(value)
}

//cmd
C:\Users\bob\golang1>go run tutorial.go
old value
 value is unchanged, but new string is returned by string_func
value changed by pointer

reference:

Saturday 26 September 2020

golang 6 function 1

 package main

import "fmt"

func add(x, y int) (z1, z2 int) {
defer fmt.Println("after return")
z1 = x + y
z2 = x - y
fmt.Println("before return")
return
}

func main() {
ans1, ans2 := add(14, 7)
fmt.Println(ans1, ans2)
}

//cmd
PS C:\Users\bob\golang1> go run tutorial.go
before return
after return
21 7

reference:

Friday 25 September 2020

厦门村子大排档

golang5 map

 package main

import "fmt"

func main() {
var mp map[string]int = map[string]int{
"apple":  5,
"pear":   6,
"orange": 9,
}
fmt.Println(mp)

mp1 := make(map[string]string)
fmt.Println(mp1)

mp1["dog"] = "pet"
mp1["cat"] = "pet"
fmt.Println(mp1)

delete(mp1, "cat")
fmt.Println(mp1)

val, exist := mp1["dog"]
fmt.Println(val, exist)

fmt.Println(len(mp1))
}

//cmd

C:\Users\bob\golang1>go run tutorial.go
map[apple:5 orange:9 pear:6]
map[]
map[cat:pet dog:pet]
map[dog:pet]
pet true
1

reference:

Relaxing Guitar Music

Thursday 24 September 2020

golang4 range

 package main

import (
"fmt"
)

func main() {
var a []int = []int{5, 6, 7, 8, 5, 4, 3, 2}

for i, element := range a {
fmt.Printf("index: %d, value: %d\n", i, element)
}

//find duplicate
for i, element := range a {
for j := i + 1; j < len(a); j++ {
element2 := a[j]
if element2 == element {
fmt.Printf("\nduplicate found: %d\n", element)
}
}
}
}

//cmd
C:\Users\bob\golang1>go run tutorial.go
index: 0, value: 5
index: 1, value: 6
index: 2, value: 7
index: 3, value: 8
index: 4, value: 5
index: 5, value: 4
index: 6, value: 3
index: 7, value: 2

duplicate found: 5

reference:

Wednesday 23 September 2020

golang 3 slice

 package main

import (
"fmt"
)

func main() {
var x []int = []int{1, 2, 3, 4, 5}
var s []int = x[1:3]
fmt.Println(s)
fmt.Println(s[:cap(s)])

b := append(s, 6)
fmt.Println(b)
fmt.Println(b[:cap(b)])
fmt.Println(s[:cap(s)])

a := make([]int, 5)
fmt.Println(a)
}

//cmd
C:\Users\bob\golang1>go run tutorial.go
[2 3]
[2 3 4 5]
[2 3 6]
[2 3 6 5]
[2 3 6 5]
[0 0 0 0 0]

reference:

Largest Fish Factory Vessel

Tuesday 22 September 2020

seaborn 8 point plot

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import signal
sns.set(style="darkgrid")

titanic = sns.load_dataset("titanic")
titanic.head()



sns.barplot(x="sex", y="survived", hue="class", data=titanic)
sns.catplot(x="sex", y="survived", hue="class", kind="point", data=titanic)

sns.catplot(x="class", y="survived", hue="sex",
            palette={"male": "g", "female": "m"},
            markers=["^", "o"], linestyles=["-", "--"],
            kind="point", data=titanic)
reference:

Sunday 20 September 2020

蒙古烤羊腿,套娃火锅



golang3

//tutorial.go 
package main

import (
"bufio"
"fmt"
"os"
"strconv"
)

func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("Type the year you were born: ")
scanner.Scan()
input, _ := strconv.ParseInt(scanner.Text(), 10, 64)
fmt.Printf("You will be %d years old at the end of 2020", 2020-input)
}

//cmd
C:\Users\bob\golang1>go run tutorial.go
Type the year you were born: 2000
You will be 20 years old at the end of 2020

reference:

Saturday 19 September 2020

golang2

//tutorial.go
 package main

import "fmt"

func main() {
price := 12.3
fmt.Printf("value is %v, type is %t\n\n", price, price)
decimal := 1025
fmt.Printf("%b\n", decimal)
fmt.Printf("%c\n", decimal)
fmt.Printf("%d\n", decimal)
fmt.Printf("%o\n", decimal)
fmt.Printf("%q\n", decimal)
fmt.Printf("%x\n\n", decimal)
number := 12345.6789
fmt.Printf("%e\n", number)
fmt.Printf("%.2f\n", number)
fmt.Printf("%15.2f\n", number)

}

//cmd
C:\Users\bob\golang1>go run tutorial.go
value is 12.3, type is %!t(float64=12.3)

10000000001
Ё
1025
2001
'Ё'
401

1.234568e+04
12345.68
       12345.68

reference:

Friday 18 September 2020

jets over Taiwan





golang 1

 download & install go @ https://golang.org/

vscode install go extension

create tutorial.go
//tutorial.go

package main

import "fmt"

func main()  {
fmt.Println("Hello World!")
}

--------------------------
//cmd

C:\Users\bob\golang1>go run tutorial.go
Hello World!

C:\Users\bob\golang1>go build tutorial.go

C:\Users\bob\golang1>tutorial.exe
Hello World!

reference:

Tuesday 15 September 2020

powershell 32 UI 5 listview paint

check colors to show circles




 
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles() 

$sampleForm = New-Object System.Windows.Forms.Form
$sampleForm.Width = 500
$sampleForm.Height = 350 

# Create three ListViewItems

$item1 = New-Object System.Windows.Forms.ListViewItem('Red')
$item1.SubItems.Add('#ff0000')
$item1.SubItems.Add('rgb(255, 0, 0)')

$item2 = New-Object System.Windows.Forms.ListViewItem('Green')
$item2.SubItems.Add('#00ff00')
$item2.SubItems.Add('rgb(0, 255, 0)')

$item3 = New-Object System.Windows.Forms.ListViewItem('Blue')
$item3.SubItems.Add('#0000ff')
$item3.SubItems.Add('rgb(0, 0, 255)')

# Create a ListView, set the view to 'Details' and add columns

$listView = New-Object System.Windows.Forms.ListView
$listView.View = 'Details'
$listView.Width = 450
$listView.Height = 120
$listView.Location = New-Object System.Drawing.Point(20, 20)

$listView.Columns.Add('Color', 120)
$listView.Columns.Add('Hex', 120)
$listView.Columns.Add('Rgb', 120)

# Display check boxes.
$listView.CheckBoxes = $true;
# Display grid lines.
$listView.GridLines = $true;

# Add items to the ListView

$listView.Items.AddRange(($item1, $item2, $item3))

$imageList = new-Object System.Windows.Forms.ImageList 
$imageList.ImageSize = New-Object System.Drawing.Size(15, 15) # Size of the pictures
 
$bitm1 = [System.Drawing.Image]::FromFile("C:\Users\bob\Desktop\1.png")
$bitm2 = [System.Drawing.Image]::FromFile("C:\Users\bob\Desktop\2.png")
$bitm3 = [System.Drawing.Image]::FromFile("C:\Users\bob\Desktop\3.png")

$imageList.Images.Add("image1", $bitm1) 
$imageList.Images.Add("image2", $bitm2)
$imageList.Images.Add("image3", $bitm3)

$listView.SmallImageList = $imageList
$item1.ImageIndex = 0
$item2.ImageIndex = 1
$item3.ImageIndex = 2

$formGraphics = $sampleForm.createGraphics()

# code or call to a function to perform graphics drawing
$RBrush = [System.Drawing.SolidBrush]::New([System.Drawing.Color]::FromArgb(100, 255, 0, 0))
$GBrush = [System.Drawing.SolidBrush]::New([System.Drawing.Color]::FromArgb(100, 0, 255, 0))
$BBrush = [System.Drawing.SolidBrush]::New([System.Drawing.Color]::FromArgb(100, 0, 0, 255))

$RRec = [System.Drawing.Rectangle]::New(178, 150, 100, 100)
$GRec = [System.Drawing.Rectangle]::New(150, 195, 100, 100)
$BRec = [System.Drawing.Rectangle]::New(206, 195, 100, 100)


$sampleForm.Controls.AddRange(@($listView))

$ListView.Add_ItemChecked( { listView_ItemChecked })

function listView_ItemChecked {
    $sampleForm.add_paint(
        {
            if ($item1.Checked) { $formGraphics.FillEllipse($RBrush, $RRec) }
            if ($item2.Checked) { $formGraphics.FillEllipse($GBrush, $GRec) }
            if ($item3.Checked) { $formGraphics.FillEllipse($BBrush, $BRec) }
        }
    )
    $sampleForm.refresh()
}

[void] $sampleForm.ShowDialog()

Sunday 13 September 2020

powershell 31 UI 4 radio button, progress bar

                       
                                        place radio buttons in group box



Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = New-Object System.Drawing.Point(290,206)
$Form.text                       = "Form"
$Form.TopMost                    = $false

$Groupbox1                       = New-Object system.Windows.Forms.Groupbox
$Groupbox1.height                = 100
$Groupbox1.width                 = 200
$Groupbox1.text                  = "Radio Group"
$Groupbox1.location              = New-Object System.Drawing.Point(39,26)

$RadioButton1                    = New-Object system.Windows.Forms.RadioButton
$RadioButton1.text               = "0%"
$RadioButton1.AutoSize           = $true
$RadioButton1.width              = 104
$RadioButton1.height             = 20
$RadioButton1.location           = New-Object System.Drawing.Point(20,24)
$RadioButton1.Font               = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$RadioButton2                    = New-Object system.Windows.Forms.RadioButton
$RadioButton2.text               = "50%"
$RadioButton2.AutoSize           = $true
$RadioButton2.width              = 104
$RadioButton2.height             = 20
$RadioButton2.location           = New-Object System.Drawing.Point(20,52)
$RadioButton2.Font               = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$RadioButton3                    = New-Object system.Windows.Forms.RadioButton
$RadioButton3.text               = "100%"
$RadioButton3.AutoSize           = $true
$RadioButton3.width              = 104
$RadioButton3.height             = 20
$RadioButton3.location           = New-Object System.Drawing.Point(20,79)
$RadioButton3.Font               = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$ProgressBar1                    = New-Object system.Windows.Forms.ProgressBar
$ProgressBar1.width              = 262
$ProgressBar1.height             = 14
$ProgressBar1.value              = 28
$ProgressBar1.location           = New-Object System.Drawing.Point(15,160)

$Form.controls.AddRange(@($Groupbox1, $ProgressBar1))
$Groupbox1.controls.AddRange(@($RadioButton1, $RadioButton2, $RadioButton3))

$RadioButton1.Add_CheckedChanged( { radioChecked })
$RadioButton2.Add_CheckedChanged( { radioChecked })
$RadioButton3.Add_CheckedChanged( { radioChecked })

function radioChecked
    if ($RadioButton1.checked) { $ProgressBar1.value = 0 }
    if ($RadioButton2.checked) { $ProgressBar1.value = 50 }
    if ($RadioButton3.checked) { $ProgressBar1.value = 100 }
}


#Write your logic code here

[void]$Form.ShowDialog()

reference:

Saturday 12 September 2020

powershell 30 UI 3 comboBox, dataGridView

select drive from comboBox, dataGridView shows drive info

services

processes

 
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = New-Object System.Drawing.Point(1026,725)
$Form.text                       = "Form"
$Form.TopMost                    = $false

$DataGridView1                   = New-Object system.Windows.Forms.DataGridView
$DataGridView1.width             = 1013
$DataGridView1.height            = 657
$DataGridView1.location          = New-Object System.Drawing.Point(5,60)

$ComboBox1                       = New-Object system.Windows.Forms.ComboBox
$ComboBox1.text                  = "comboBox"
$ComboBox1.width                 = 356
$ComboBox1.height                = 20
@('Service','Process','Drive') | ForEach-Object {[void] $ComboBox1.Items.Add($_)}
$ComboBox1.location              = New-Object System.Drawing.Point(10,20)
$ComboBox1.Font                  = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ComboBox1.BackColor             = [System.Drawing.ColorTranslator]::FromHtml("#f8e71c")

$Form.controls.AddRange(@($DataGridView1, $ComboBox1))

$ComboBox1.Add_SelectedIndexChanged( { comboBox_IndexChange })

function comboBox_IndexChange {
    $selection = $ComboBox1.SelectedItem.ToString()
    
    switch ($selection) {
        'Service'{ $DataGridView1.dataSource = Get-Service | ConvertTo-Datatable}
        'Process'{ $DataGridView1.dataSource = Get-Process | ConvertTo-Datatable}
        'Drive'{ $DataGridView1.dataSource = Get-PSDrive | ConvertTo-Datatable}
        Default {}
    }
}

function ConvertTo-DataTable {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)]
        [PSObject[]]$InputObject
    )

    Begin {
        $dataTable = New-Object System.Data.DataTable
        $first = $true

        function _GetSafeTypeName($type) {
            # internal helper function to return the correct typename for a datatable
            $types = @('System.Boolean', 'System.Byte', 'System.SByte', 'System.Char', 'System.Datetime',
                       'System.TimeSpan', 'System.Decimal', 'System.Double', 'System.Guid', 'System.Single')
            $ints  = @('System.Int16', 'System.Int32', 'System.Int64')
            $uints = @('System.UInt16', 'System.UInt32', 'System.UInt64')

            if ($types -contains $type) { return "$type" }
            # if the type is Int or UInt, always return the largest variety
            if ($ints  -contains $type) { return 'System.Int64' }
            if ($uints -contains $type) { return 'System.UInt64' }
            return 'System.String'
        }
    }
    Process {
        foreach ($object in $InputObject) {
            $dataRow = $dataTable.NewRow()
            foreach($property in $object.PSObject.Properties) {
                # read the data type for this property and make sure it is a valid type for a DataTable
                $dataType = _GetSafeTypeName $property.TypeNameOfValue
                # ensure the property name does not contain invalid characters
                $propertyName = $property.Name -replace '[\W\p{Pc}-[,]]', '_' -replace '_+', '_'
                if ($first) {
                    $dataColumn = New-Object System.Data.DataColumn $propertyName, $dataType
                    $dataTable.Columns.Add($dataColumn)
                }
                if ($property.Gettype().IsArray -or ($property.TypeNameOfValue -like '*collection*')) {
                    $dataRow.Item($propertyName) = $property.Value | ConvertTo-XML -As String -NoTypeInformation -Depth 1
                }
                else {
                    $value = if ($null -ne $property.Value) { $property.Value } else { [System.DBNull]::Value }
                    $dataRow.Item($propertyName) = $value -as $dataType
                }
            }
            $dataTable.Rows.Add($dataRow)
            $first = $false
        }
    }
    End {
        Write-Output @(,($dataTable))
    }
}
#Write your logic code here

[void]$Form.ShowDialog()

Ultrasonic solder gun + active solder

Friday 11 September 2020

The Making of an American Truck

powershell 29 UI 2


go to poshgui.com -> click winForm designer -> drag & drop textbox, button -> change color, text in property -> check click in button event

click code tab -> copy auto generated code paste in editor -> complete btn-click code

winform opens -> enter chrome in textbox -> press get process button

a gridview opens to show all chrome process

<# This form was created using POSHGUI.com  a free online gui designer for PowerShell
.NAME
    Untitled
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = New-Object System.Drawing.Point(262,182)
$Form.text                       = "Form"
$Form.TopMost                    = $false

$Button1                         = New-Object system.Windows.Forms.Button
$Button1.text                    = "Get Process"
$Button1.width                   = 93
$Button1.height                  = 30
$Button1.location                = New-Object System.Drawing.Point(80,128)
$Button1.Font                    = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Button1.ForeColor               = [System.Drawing.ColorTranslator]::FromHtml("#ffffff")
$Button1.BackColor               = [System.Drawing.ColorTranslator]::FromHtml("#4a90e2")

$Label1                          = New-Object system.Windows.Forms.Label
$Label1.text                     = "Name"
$Label1.AutoSize                 = $true
$Label1.width                    = 25
$Label1.height                   = 10
$Label1.location                 = New-Object System.Drawing.Point(48,64)
$Label1.Font                     = New-Object System.Drawing.Font('Microsoft Sans Serif',10)

$TextBox1                        = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline              = $false
$TextBox1.width                  = 100
$TextBox1.height                 = 20
$TextBox1.location               = New-Object System.Drawing.Point(119,62)
$TextBox1.Font                   = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TextBox1.BackColor              = [System.Drawing.ColorTranslator]::FromHtml("#f8e71c")

$Form.controls.AddRange(@($Button1,$Label1,$TextBox1))

$Button1.Add_Click({ btnGetProcess_click })

function btnGetProcess_click
    Get-Process $TextBox1.Text | Out-GridView
}


#Write your logic code here

[void]$Form.ShowDialog()

reference:

Wednesday 9 September 2020

Aluminum Recycling And Extrusion

powershell 28 UI 1

 
progress bar

PS C:\Windows\System32> for($i = 0; $i -le 100; $i+=20){
>>     Write-Progress -Activity "Search in porgress" -Status "$i% complete:" -PercentComplete $i;
>>     Start-Sleep 1
>> }


PS C:\Windows\System32> get-childItem | Out-GridView -Title "File List"

PS C:\Windows\System32> [int]$age = Read-Host 'Enter age'
Enter age: d
MetadataError: Cannot convert value "d" to type "System.Int32". Error: "Input string was not in a correct format."

PS C:\Windows\System32> $password = Read-Host 'Enter password' -ASSecureString
Enter password: *******
PS C:\Windows\System32> write-output $password
System.Security.SecureString

reference:

Bubble Lady

Monday 7 September 2020

powershell 27 firewall

firewall on hearthstone is enabled in the begining

PS C:\Windows\System32> get-NetFirewallRule | where DisplayName -match hearthstone

Name                  : TCP Query User{49D8D1A3-5E67-41A8-A5A3-2D4F05355A57}C:\program files
                        (x86)\hearthstone\hearthstone.exe
DisplayName           : hearthstone
Description           : hearthstone
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Public
Platform              : {}
Direction             : Inbound
Action                : Allow
EdgeTraversalPolicy   : DeferToUser
LooseSourceMapping    : False
LocalOnlyMapping      : False
Owner                 :
PrimaryStatus         : OK
Status                : The rule was parsed successfully from the store. (65536)
EnforcementStatus     : NotApplicable
PolicyStoreSource     : PersistentStore
PolicyStoreSourceType : Local

Name                  : UDP Query User{BDC29526-D763-4132-83F1-F81470C54F8B}C:\program files
                        (x86)\hearthstone\hearthstone.exe
DisplayName           : hearthstone
Description           : hearthstone
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Public
Platform              : {}
Direction             : Inbound
Action                : Allow
EdgeTraversalPolicy   : DeferToUser
LooseSourceMapping    : False
LocalOnlyMapping      : False
Owner                 :
PrimaryStatus         : OK
Status                : The rule was parsed successfully from the store. (65536)
EnforcementStatus     : NotApplicable
PolicyStoreSource     : PersistentStore
PolicyStoreSourceType : Local

firewall on hearthstone is disabled

#disable firewall on a program
PS C:\Windows\System32> get-NetFirewallRule | where DisplayName -match hearthstone | Disable-NetFirewallRule

#re-enable firewall on a program
PS C:\Windows\System32> get-NetFirewallRule | where DisplayName -match hearthstone | enable-NetFirewallRule

#block a program
Set-NetFirewallRule -DisplayName hearthstone -Action block

hearthstone is blocked

#allow a program through
Set-NetFirewallRule -DisplayName hearthstone -Action allow

reference:

Sunday 6 September 2020

animehd47

 https://animehd47.com/

seaborn 7 barplot

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import signal
sns.set(style="darkgrid")

tips = sns.load_dataset("tips")
tips.head()

  total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

sns.barplot(x="day", y="total_bill", data=tips)

sns.barplot(x="day", y="total_bill", hue="sex", data=tips)

sns.barplot(x="time", y="tip", data=tips,
                 order=["Dinner", "Lunch"])

from numpy import median
sns.barplot(x="day", y="tip", data=tips, estimator=median)

sns.barplot("size", y="total_bill", data=tips,
                 palette="Blues_d")

sns.catplot(x="sex", y="total_bill",
                hue="smoker", col="time",
                data=tips, kind="bar",
                height=4, aspect=.7);