Category Archives: How to Implement

Unity: How to Implement Timer

The first step is to implement the UpdateRegister function, inherited from MonoBehavior, and use Unity’s own Update method. Functionality provided to external registration and deregistration

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace JunFramework
{
    public enum UpdateMode
    {
        Update,
        FixedUpdate,
        LateUpdate
    }

    public enum TimeMode
    {
        Scaled,
        UnScaled
    }
    public class UpdateRegister : MonoBehaviour
    {
        /// <summary>
        /// update
        /// </summary>
        private static Dictionary<int, Action> update = new Dictionary<int, Action>();

        /// <summary>
        /// fixedupfate
        /// </summary>
        private static Dictionary<int, Action> fixedupdate = new Dictionary<int, Action>();

        /// <summary>
        /// lateupdate
        /// </summary>
        private static Dictionary<int, Action> lateupdate = new Dictionary<int,Action>(); 

        ///  <summary> 
        /// Globally unique update subscript
         ///  </summary> 
        private  static  int updateIndex = 0 ; 
      
        ///  <summary> 
        /// Whether to initialize
         ///  </summary> 
        private  static  bool isInit = false ; 

        ///  <summary> 
        /// has been initialized
         ///  </summary> 
        public  static  bool IsInit 
        { 
            get => isInit; 
        } 

        ///  <summary> 
        /// register
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static int Register(UpdateMode mode, Action handler)
        {
            ++updateIndex;
            switch (mode)
            {
                case UpdateMode.Update:
                    update.Add(updateIndex, handler);
                    break;
                case UpdateMode.FixedUpdate:
                    fixedupdate.Add(updateIndex, handler);
                    break;
                case UpdateMode.LateUpdate:
                    lateupdate.Add(updateIndex, handler);
                    break;
            }
            return updateIndex;
        }

        /// <summary>
        /// Unregister according to updateindex
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="index"></param>
        public static void Cancle(UpdateMode mode, int index)
        {
            switch (mode)
            {
                case UpdateMode.Update:
                    update.Remove(index);
                    break;
                case UpdateMode.FixedUpdate:
                    fixedupdate.Remove(index);
                    break;
                case UpdateMode.LateUpdate:
                    lateupdate.Remove(index);
                    break;
            }
        }

        private void Awake()
        {
            isInit = true;
        }

        private void Update()
        {
            using (var e = update.GetEnumerator())
            {
                if (e.MoveNext())
                {
                    e.Current.Value?.Invoke();
                }
            }
        }

        private void FixedUpdate()
        {
            using (var e = fixedupdate.GetEnumerator())
            {
                if (e.MoveNext())
                {
                    e.Current.Value?.Invoke();
                }
            }
        }

        private void LateUpdate()
        {
            using (var e = lateupdate.GetEnumerator())
            {
                if (e.MoveNext())
                {
                    e.Current.Value?.Invoke();
                }
            }
        }
    }
}

The second step is to implement the Timer object, store the information passed in by the caller, and get the Timer status (is it completed? Is it working? Current progress?). Callable start, end, pause, resume, reset, finish functions

using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System; 

namespace JunFramework.Timer 
{ 
    public  class Timer 
    { 
        #region timer setting /// <summary> /// Timer is automatically released
         /// </summary > public static bool IsAutoRelease = true ; /// <summary> /// Timer update mode
         /// </summary> public static UpdateMode TimerUpdateMode =

         
         
          

         
         
         UpdateMode.FixedUpdate; 

        ///  <summary> 
        /// Whether the Timer time is affected by Unity scaling
         ///  </summary> 
        public  static TimeMode TimerScaledModel = TimeMode.UnScaled; 

        #endregion 

        private  float currentTime = 0f; // Current time ( 0 -- steptime) 
        private  int currentRepeat = 0 ; // current repeat times 
        private  float stepTime = 0f; // interval 
        private  int repeatTimes = 0 ; // repeat times 
        private  bool isLoop = false; // Whether to loop 
        private  bool isDone = false ; // Whether to complete 
        private  bool isStart = false ; // Whether to start 
        private  int updateIndex = 0 ; // The subscript obtained by update registration is used to remove update registration 
        private Action callback; // Callback 
        private  float timeAcceleration; // Increased time per frame 

        ///  <summary> 
        /// Is it complete
         ///  </summary> 
        public  bool IsDone 
        { 
            get =>isDone; 
        } 

        ///  <summary> 
        /// Current Progress
         ///  </summary> 
        public  float Progress 
        { 
            get => currentTime / stepTime; 
        } 

        ///  <summary> 
        /// Is it working
         ///  </ summary> summary> 
        public  bool IsWokring 
        { 
            get => !isDone && isStart; 
        } 

        ///  <summary> 
        ///  
        ///  </summary> 
        ///  <param name="stepTime"> Interval duration </param> 
        // / <param name="repeatTimes">times of repetition</param>
        /// <param name="callback">call-back</param>
        public Timer(float stepTime, int repeatTimes, Action callback)
        {
            this.currentTime = 0f;
            this.currentRepeat = 0;
            this.stepTime = stepTime;
            this.repeatTimes = repeatTimes;
            this.isLoop = false;
            this.isDone = false;
            this.timeAcceleration = GetPerTime();
            this.callback = callback;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stepTime">interval</param>
        /// <param name="callback">call-back</param>
        public Timer(float stepTime, Action callback)
        {
            this.currentTime = 0f;
            this.currentRepeat = 0;
            this.stepTime = stepTime;
            this.repeatTimes = 1;
            this.isLoop = false;
            this.isDone = false;
            this.timeAcceleration = GetPerTime();
            this.callback = callback;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stepTime">Interval</param>
        /// <param name="isLoop">Loop or not</param>
        /// <param name="callback">call-back</param>
        public Timer(float stepTime, bool isLoop, Action callback)
        {
            this.currentTime = 0f;
            this.currentRepeat = 0;
            this.stepTime = stepTime;
            this.isLoop = isLoop;
            if (!isLoop)
            {
                this.repeatTimes = 1;
            }
            this.timeAcceleration = GetPerTime();
            this.isDone = false;
            this.callback = callback;
        }

        /// <summary>
        /// Update every frame
         ///  </summary> 
        ///  <param name="addTime"> Added time per frame </param> 
        private  void Update( float addTime) 
        { 
            if (isDone)
                 return ;
             if (! isStart)
                 return ; 

            currentTime += addTime;
             if (currentTime >= stepTime) 
            { 
                callback ? .Invoke(); 
                currentTime = 0f;
                 if (!isLoop)
                {
                    ++currentRepeat;
                    if (currentRepeat >= repeatTimes)
                    {
                        isDone = true;
                        if (IsAutoRelease)
                        {
                            Stop();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// TimerStart
        /// </summary>
        public void Start()
        {
            if(! UpdateRegister.IsInit) 
            { 
                Debug.LogWarning( " UpdateRegister is not init, so this action will not work, please init UpdateRegister first!!! " );
                 return ; 
            } 
            isStart = true ;
             this .updateIndex = UpdateRegister.Register(TimerUpdateMode , () => this .Update(timeAcceleration)); 
        } 

        ///  <summary> 
        /// Stop the timer (if you just want to pause the available Pause, the stop operation cannot be resumed)
         ///  </summary> 
        public  void Stop( ) 
        {
            isStart = false;
            isDone = true;
            UpdateRegister.Cancle(TimerUpdateMode, this.updateIndex);
        }

        /// <summary>
        /// Pause
        /// </summary>
        public void Pause()
        {
            isStart = false;
        }

        /// <summary>
        /// Continue
        /// </summary>
        public void Resume()
        {
            isStart = true; 
        } 

        ///  <summary> 
        /// Reset
         ///  </summary> 
        public  void Reset() 
        { 
            isStart = false ; 
            isDone = false ; 
            currentTime = 0f; 
            currentRepeat = 0 ; 
        } 

        ///  <summary> 
        / // No need to wait, complete directly
         ///  </summary> 
        public  void Complete() 
        { 
            if (isLoop)
                 return; 
            isDone = true ; 

            int tempRepeat = repeatTimes;
             while (tempRepeat > 0 ) 
            { 
                callback ? .Invoke();
                 -- tempRepeat; 
            } 
            Stop(); 

        } 

        ///  <summary> 
        /// Obtained by update mode and time mode Update time per frame
         ///  </summary> 
        ///  <returns></returns> 
        private  float GetPerTime() 
        { 
            float resultTime = 0f;
             if (TimerScaledModel == TimeMode.Scaled && TimerUpdateMode == UpdateMode.FixedUpdate)
            {
                resultTime = Time.fixedDeltaTime;
            }
            else if (TimerScaledModel == TimeMode.UnScaled && TimerUpdateMode == UpdateMode.FixedUpdate)
            {
                resultTime = Time.fixedUnscaledDeltaTime;
            }
            else if (TimerScaledModel == TimeMode.Scaled && TimerUpdateMode == UpdateMode.Update)
            {
                resultTime = Time.deltaTime;
            }
            else if (TimerScaledModel == TimeMode.UnScaled && TimerUpdateMode == UpdateMode.FixedUpdate)
            {
                resultTime = Time.unscaledDeltaTime;
            }
            return resultTime;
        }
    }
}

The third step is to simply write the test code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using JunFramework.Timer;

public class TimerExample : MonoBehaviour
{
    private Timer timer = null;
    // Start is called before the first frame update
    void Start()
    {
        Timer.IsAutoRelease = true;
        Timer.TimerScaledModel = JunFramework.TimeMode.UnScaled;
        Timer.TimerUpdateMode = JunFramework.UpdateMode.FixedUpdate;

        //Example1
        //int i = 0;
        //Timer timer = new Timer(2, 2, () => Debug.Log(i++));
        //timer.Start();

        //Example2
        //timer = new Timer(2, true, () => Debug.Log("Exeture"));
        //timer.Start();

        //Example3
        timer = new Timer(2, 3, () => Debug.Log("LookMe"));
        timer.Start();
        timer.Complete();

        timer.Reset();
        timer.Start();
    }

    // Update is called once per frame
    void Update()
    {
        //Example2
        //if (Input.GetKeyDown(KeyCode.Space))
        //{
        //    timer.Pause();
        //}
        //else if (Input.GetKeyDown(KeyCode.A))
        //{
        //    timer.Resume();
        //}
    }
}

gatk: How to Merge vcf Files

001. Test data

[[email protected] test]# ls                            ## test data
seg1_1.vcf seg1_2.vcf seg1_3.vcf
[[email protected] test]# ll - h
total 1 .2G
 -rw-r--r--. 1 root root 392M Dec   1  18 : 14 seg1_1.vcf
 -rw-r--r--. 1 root root 410M Dec   1  18 : 15 seg1_2.vcf
 -rw -r--r--. 1 root root 386M Dec   1  18 : 14 seg1_3.vcf

 

 

002. Merge vcf files

g atk MergeVcfs -I seg1_1.vcf -I seg1_2.vcf -I seg1_3.vcf -O xxx.vcf ## merge command

 

The combined result is as follows:

[[email protected] test]# ls
seg1_1.vcf seg1_2.vcf seg1_3.vcf xxx.vcf xxx.vcf.idx
[[email protected] test]# ll - h 
total 2 .4G
 -rw-r--r--. 1 root root 392M Dec   1  18 : 14 seg1_1.vcf
 -rw-r--r--. 1 root root 410M Dec   1  18 : 15 seg1_2.vcf
 -rw-r--r--. 1 root root 386M Dec   1  18 : 14 seg1_3.vcf
 -rw-r--r--. 1 root root 1 .2G Dec   1  19 : 16 xxx.vcf
 -rw-r--r--. 1 root root 6.2K Dec   1  19 : 16 xxx.vcf.idx

 

 

003. Generate a list of vcf files that need to be merged

[[email protected] test]# ls
seg1_1.vcf seg1_2.vcf seg1_3.vcf vcf.list
[[email protected] test]# cat vcf.list ## Vcf list file to be merged
seg1_1.vcf
seg1_2.vcf
seg1_3.vcf
[[email protected] test]# java -jar /home/software/picard/picard.jar MergeVcfs I=vcf.list O=xxx.vcf ## merge command

 

 

004. Merge result

[[email protected] test]# ls
seg1_1.vcf seg1_2.vcf seg1_3.vcf vcf.list xxx.vcf xxx.vcf.idx
[[email protected]1 test]# ll - h 
total 2 .4G
 -rw-r--r--. 1 root root 392M Dec   1  18 : 14 seg1_1.vcf
 -rw-r--r--. 1 root root 410M Dec   1  18 : 15 seg1_2.vcf
 -rw-r--r--. 1 root root 386M Dec   1  18 : 14 seg1_3.vcf
 -rw-r--r--. 1 root root    33 Dec   1  19 : 24 vcf .list
 -rw-r--r--. 1 root root 1.2G Dec   1  19 : 24 xxx.vcf
 -rw-r--r--. 1 root root 6 .2K Dec   1  19 : 24 xxx.vcf.idx

 

Vue: How to Share Your Screen

Document: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia

Method: https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture

Example Codes:

<template>

  <video ref="video" autoplay="true" style="width: 500px; height: 300px"></video>
  <canvas ref="canvas" style="display: none"></canvas>

</template>
 


<script lang="ts" setup>


 import { onMounted, ref } from 'vue'

  const canvas = ref()
  const video = ref()
  const timer = ref()
 



 onMounted(async () => {
let stream = null
try {
    stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
        audio: true
    })
    video.value.srcObject = stream
    dumpOptionsInfo()
    const ctx = canvas.value.getContext('2d')
    // devicePixelRatio returns the ratio of the physical pixel resolution of the current display device to the CSS pixel resolution, allowing for better reproduction of realistic video scenes
    const ratio = window.devicePixelRatio || 1
    ctx.scale(ratio, ratio)
    // The canvas size remains the same as the image size, and the screenshot is not redundant
    canvas.value.width = video.value.offsetWidth * ratio
    canvas.value.height = video.value.offsetHeight * ratio
    timer.value = setInterval(() = > {
        ctx.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height)
        const imgUrl = canvas.value.toDataURL('image/jpeg')
        console.log('imgUrl: ', imgUrl)
    }, 5000)
} catch (e) {
    console.log(e)
}
// Monitor to manually turn off screen sharing
const videoTrack = video.value.srcObject.getVideoTracks()[0]
videoTrack.addEventListener('ended', handleStop)
  })

const dumpOptionsInfo = () = > {
    const videoTrack = video.value.srcObject.getVideoTracks()[0]
    console.info('Track settings:')
    console.info(JSON.stringify(videoTrack.getSettings(), null, 2))
    console.info('Track constraints:')
    console.info(JSON.stringify(videoTrack.getConstraints(), null, 2))
}
const handleStop = () = > {
    clearInterval(timer.value)
    let tracks = video.value.srcObject.getTracks()
    tracks.forEach((track: {
        stop: () = > any
    }) = > track.stop())
    video.value.srcObject = null
}

 

luffy: How to create a database and interface

1 Create a Banner database

Since the time, deletion, etc. in this database can be shared, we can write a separate table model for him, and finally make it not built into the database when the database is built. This code can be shared, and then we inherit BaseModels

from django.db import models


class BaseModels(models.Model):
    created_time = models.DateTimeField(auto_now_add=True, verbose_name= ' created time ' )
    updated_time = models.DateTimeField(auto_now=True, verbose_name= ' last update time ' )
    is_delete = models.BooleanField(default=False, verbose_name= ' Delete or not ' )
    is_show = models.BooleanField(default=True, verbose_name= ' Whether it is on the shelf ' )
    orders = models.IntegerField(verbose_name= ' priority ' )

    class Meta:
        abstract = True
from utils.models import BaseModels
 from django.db import models

class Banner(BaseModels):
    title = models.CharField(max_length=16, unique=True, verbose_name= ' name ' )
    image = models.ImageField(upload_to= ' banner ' , verbose_name= ' image ' )
    link = models.CharField(max_length=64, verbose_name= ' jump link ' )
    info = models.TextField(verbose_name= ' details ' )

    class Meta:
        db_table = ' luffy_banner ' 
        verbose_name_plural = ' Carousel chart '

    def  __str__ (self):
         return self.title

At this point, our Banner table is created

2 Write the Banner interface

By inheriting GenericViewSet and ListModelMixin, we can quickly write the interface, but if we want to return data in a specified format, we must pass the list data to another variable from the list method in ListModelMixin, so that we can easily Pass the value according to the specified parameters of the function. Since this list method may be reused in many places, we can make a package for it.

from rest_framework.mixins import ListModelMixin
 from .response import APIResponse

class BannerListView(ListModelMixin):
     def list(self, request, *args, ** kwargs):
        res = super().list(request, *args, ** kwargs)
         return APIResponse(data=res.data)
from luffyapi.utils.listviews import BannerListView
 from .models import Banner
 from .serializer import BannerSerializers
 # Create your views here. 
from rest_framework.viewsets import GenericViewSet
 from django.conf import settings

class BannerView(GenericViewSet, BannerListView):
    queryset =Banner.objects.all().filter(is_delete=False,is_show=True).order_by( ' orders ' )[:settings.AREA]
    serializer_class =BannerSerializers

Docker: How to Modify Your Hostname

docker change hostname

When docker is running, it is the same as the container id, and the host name is randomly generated. If you want to fix the host name, I will summarize several common methods.

specify hostname

When docker run, specify the hostname parameter, this parameter will directly write the corresponding hostname to the /etc/hostname file of the machine

docker run -itd --network $netname --hostname $host --name $name yourimage

Specify other machine information

You can also add hostname: use the add-host=$hostname:$ip parameter, which will add a line of mapping to the /etc/hostname file in the container

docker run -itd --network $netname --add-host=$host:$ip --name $name yourimage

If it is through docker-compose, you need to pass the extra_hosts parameter

# docker-compose.yml
extra_hosts:
 - "host1:172.18.0.3"
 - "host2:172.18.0.4"

If deployed through k8s

DataGrid: How to center the title bar and content

Content centered style

<Style
    x:Key="HorizontalAlignedData"
    BasedOn="{StaticResource {x:Type TextBlock}}"
    TargetType="{x:Type TextBlock}">
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

title centering style

<Style TargetType="DataGridColumnHeader">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="BorderBrush" Value="#a8a8a8" />
    <Setter Property="Background" Value="#f2f2f2" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="Padding" Value="5" />
    <Setter Property="Foreground" Value="{StaticResource TextColorGeneral}" />
    <Setter Property="BorderThickness" Value="0,0,1,1" />
</Style>

Realize that each column is displayed proportionally

Set the column width to starswidth="*"


<DataGridTextColumn
    Width="*"
    Binding="{Binding Name}"
    ElementStyle="{StaticResource HorizontalAlignedData}"
    Header="Project"
    IsReadOnly="True" />

Complete demo code


<DataGrid.Columns>

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Name}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Project"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Value}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Outcome"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="2*"
        Binding="{Binding Tolerance}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Task"
        IsReadOnly="True" />

</DataGrid.Columns>

WPF: How to Implement Table Style with DataGrid

resource

Define colors and styles


<SolidColorBrush x:Key="TextColorGeneral" Color="#a2a2a2" />


<Style TargetType="DataGridColumnHeader">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="BorderBrush" Value="#a8a8a8" />
    <Setter Property="Background" Value="#f2f2f2" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="Padding" Value="5" />
    <Setter Property="Foreground" Value="{StaticResource TextColorGeneral}" />
    <Setter Property="BorderThickness" Value="0,0,1,1" /> // Important!
</Style>

Set dataGrid properties


<DataGrid
        Grid.Row="5"
        d:ItemsSource="{StaticResource testItems}"
        AutoGenerateColumns="False"
        BorderBrush="#a8a8a8"
        CanUserAddRows="False"
        CanUserReorderColumns="False"
        CanUserResizeColumns="False"
        HeadersVisibility="Column"
        ItemsSource="{Binding CalibrationItems}"
        SelectionMode="Single"
        SelectionUnit="Cell"
        Style="{StaticResource BaseStyle}"
        BorderThickness="1,1,0,0" // Important!
        HorizontalGridLinesBrush="#a8a8a8" // Important!
        VerticalGridLinesBrush="#a8a8a8"> // Important!
</DataGrid>

renderings

image