1. 使用 Golang
2. foder name and package is 題號
3. In GOPATH, type "go test LeetCode/LeetCode_00728"
4. Benchmark, type "go test LeetCode/LeetCode_00278 -bench=."
src - LeetCode - LeetCode_00728 - LeetCode_00728.go - LeetCode_00728_test.go
src - LeetCode - LeetCode_00728 - LeetCode_00728.go - LeetCode_00728_test.go
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
SCHTASKS /ShowSid /?
==> 檔案路徑中的空白可使用兩組引號,一組
用於 CMD.EXE,另一組用於 SchTasks.exe。用於 CMD 的外部引號
必須是雙引號; 內部引號則可以是單引號或
逸出雙引號:
SCHTASKS /Create
/tr "'c:\program files\internet explorer\iexplorer.exe'
\"c:\log data\today.xml\"" ...
@echo off
%~d0
cd %~dp0
/**
set the value of an environment variable
This function changes the current value of the specified environment variable. If the
environment variable exists and the Value is an empty string, then the environment
variable is deleted. If the environment variable exists and the Value is not an empty
string, then the value of the environment variable is changed. If the environment
variable does not exist and the Value is an empty string, there is no action. If the
environment variable does not exist and the Value is a non-empty string, then the
environment variable is created and assigned the specified value.
This is not supported pre-UEFI Shell 2.0.
@param EnvKey The key name of the environment variable.
@param EnvVal The Value of the environment variable
@param Volatile Indicates whether the variable is non-volatile (FALSE) or volatile (TRUE).
@retval EFI_SUCCESS the operation was completed sucessfully
@retval EFI_UNSUPPORTED This operation is not allowed in pre UEFI 2.0 Shell environments
**/
EFI_STATUS
EFIAPI
ShellSetEnvironmentVariable (
IN CONST CHAR16 *EnvKey,
IN CONST CHAR16 *EnvVal,
IN BOOLEAN Volatile
)
{
//
// Check for UEFI Shell 2.0 protocols
//
if (gEfiShellProtocol != NULL) {
return (gEfiShellProtocol->SetEnv(EnvKey, EnvVal, Volatile));
}
function test(callback) {
console.log("in test");
var usage = Math.floor((Math.random() * 100) + 1);
if ((usage%2) == 0) {
callback(true);
} else {
callback(false);
}
console.log("exit test");
}
function b() {
console.log("in b");
var res;
test(function(result) {
console.log("in test callback", result);
/*
if (result) {
return true;
} else {
return false;
}
*/
res = result;
});
console.log("after test");
return res;
}
var a = b();
console.log("after b");
console.log(a);
set GOOS=linux set GOARCH=amd64 go build
[Protocols]
gEfiCpuIoProtocolGuid
#include <Protocol/CpuIo.h>
#include <Library/UefiBootServicesTableLib.h>
#include <stdio.h>
EFI_CPU_IO_PROTOCOL *mCpuIo = NULL;
void testReadCMOS()
{
EFI_STATUS Status;
UINT8 addr;
UINT8 data;
Status = gBS->LocateProtocol(&gEfiCpuIoProtocolGuid, NULL, (VOID **)&mCpuIo);
if (Status != EFI_SUCCESS) {
return;
}
addr = 0x30;
Status = mCpuIo->Io.Write(
mCpuIo,
EfiCpuIoWidthUint8,
0x70,
1,
&addr
);
if (Status != EFI_SUCCESS) {
return;
}
Status = mCpuIo->Io.Read(
mCpuIo,
EfiCpuIoWidthUint8,
0x71,
1,
&data
);
if (Status != EFI_SUCCESS) {
return;
}
printf("CMOS 0x30=%X", data);
}
// A WaitGroup waits for a collection of goroutines to finish.
// The main goroutine calls Add to set the number of
// goroutines to wait for. Then each of the goroutines
// runs and calls Done when finished. At the same time,
// Wait can be used to block until all goroutines have finished.
//
// A WaitGroup must not be copied after first use.
type WaitGroup struct {
noCopy noCopy
// 64-bit value: high 32 bits are counter, low 32 bits are waiter count.
// 64-bit atomic operations require 64-bit alignment, but 32-bit
// compilers do not ensure it. So we allocate 12 bytes and then use
// the aligned 8 bytes in them as state.
state1 [12]byte
sema uint32
}
func (wg *WaitGroup) Add(delta int) {
statep := wg.state()
if race.Enabled {
_ = *statep // trigger nil deref early
if delta < 0 {
// Synchronize decrements with Wait.
race.ReleaseMerge(unsafe.Pointer(wg))
}
race.Disable()
defer race.Enable()
}
...
}
wevtutil qe system "/q:*[System[TimeCreated[@SystemTime>='2017-09-10T00:00:00']]]" | find /N "12</EventID>"
wevtutil qe system /q:Event[EventData[Data[@Name='StartTime']>'2017-09-10T00:00:00']]
<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'> <System> <Provider Name='Microsoft-Windows-Kernel-General' Guid='{A68CA8B7-004F-D7B6-A698-07E2DE0F1F5D}'/> <EventID>12</EventID> <Version>0</Version> <Level>4</Level> <Task>0</Task> <Opcode>0</Opcode> <Keywords>0x8000000000000000</Keywords> <TimeCreated SystemTime='2017-09-12T01:30:41.749600400Z'/> <EventRecordID>302816</EventRecordID> <Correlation/> <Execution ProcessID='4' ThreadID='8'/> <Channel>System</Channel> <Computer> xxxxx </Computer> <Security UserID='S-1-5-18'/> </System> <EventData> <Data Name='MajorVersion'>6</Data> <Data Name='MinorVersion'>1</Data> <Data Name='BuildVersion'>7601</Data> <Data Name='QfeVersion'>23807</Data> <Data Name='ServiceVersion'>1</Data> <Data Name='BootMode'>0</Data> <Data Name='StartTime'>2017-09-12T01:30:41.125599300Z</Data> </EventData> </Event>
package main
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
)
const workTime = 8 * 60 + 75
func getCMDResult(today string) (string, error) {
subcmd := fmt.Sprintf("wevtutil qe system /q:Event[EventData[Data[@Name='StartTime']^>'%s']]", today)
cmd := exec.Command("cmd", "/C", subcmd)
out, err := cmd.Output()
if err != nil {
return "", err
}
return string(out), nil
}
func getStartTime(log string) string {
pattern := "'StartTime'>"
i := strings.Index(log, pattern)
if i >= 0 {
start := i + len(pattern)
out := log[start:start+30]
return out
}
return ""
}
func getHumanTime(t time.Time) string {
return fmt.Sprintf(
"%04d-%02d-%02d %02d:%02d",
t.Year(),
t.Month(),
t.Day(),
t.Hour(),
t.Minute(),
)
}
func printWorkTime(startTime string) {
t1, err := time.Parse(time.RFC3339, startTime)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("")
fmt.Printf("clock in : %s \n", getHumanTime(t1.Local()))
fmt.Printf("clock out : %s \n", getHumanTime(t1.Add(time.Duration(workTime)*time.Minute).Local()))
}
func main() {
t1 := time.Now()
t2 := time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.FixedZone("UTC", 0))
out, err := getCMDResult(t2.Format(time.RFC3339))
if err != nil {
log.Fatal(err)
}
startTime := getStartTime(out)
if startTime != "" {
printWorkTime(startTime)
return
}
fmt.Println("Can't get start time in Windows event log")
}
import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" server_address = ('192.168.0.163', 8080) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) print 'Starting httpd...' httpd.serve_forever()
import httplib conn = httplib.HTTPConnection("www.example.com") conn.request("GET", "/") res = conn.getresponse() print res.status, res.reason data = res.read() print data conn.close()
var regex = /(\d+) (\d+)/; var str = '123 456'; var info = regex.exec(str); for (var i = 0; i < info.length; i++) { console.log(i, info[i]); }
0 '123 456' 1 '123' 2 '456'
var regex = /(\d+) (\d+)/g; var str = '123 456; 789 100'; var info; while ((info = regex.exec(str)) != null) { console.log(regex.lastIndex); for (var i = 0; i < info.length; i++) { console.log(i, info[i]); } }
7 0 '123 456' 1 '123' 2 '456' 16 0 '789 100' 1 '789' 2 '100'
import socket import sys import time import datetime sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) server_address = ('192.168.111.1', 8080) print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) try: message = "This is the message" for x in range(0, 10): msg = '%s %02d (%s)' % (str(datetime.datetime.now()), x+1, message) print(msg) sock.sendall(message) time.sleep(2) finally: print("close socket") sock.close()
#include <Library/UefiBootServicesTableLib.h>
#include <stdio.h>
#include <time.h>
//-----------------------------------------------------------------------------
static int g_count = 1;
//-----------------------------------------------------------------------------
void printTime(void)
{
struct tm *t1;
time_t ret;
time(&ret);
ret += 8 * 60 * 60;
t1 = gmtime(&ret);
printf(
"[%04d-%02d-%02d %02d:%02d:%02d] %02d - in NotifyFunction \n",
t1->tm_year + 1900,
t1->tm_mon + 1,
t1->tm_mday,
t1->tm_hour,
t1->tm_min,
t1->tm_sec,
g_count
);
}
//-----------------------------------------------------------------------------
VOID EFIAPI
NotifyFunction(
IN EFI_EVENT Event,
IN VOID *Context
)
{
printTime();
g_count++;
}
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
EFI_EVENT event;
gBS->CreateEvent(
EVT_TIMER | EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
NotifyFunction,
NULL,
&event
);
// every 5 seconds to trigger
gBS->SetTimer(event, TimerPeriodic, 50000000);
do {
// wait NotifyFunction
} while(g_count < 10);
gBS->SetTimer(event, TimerCancel, 0);
gBS->CloseEvent(event);
return 0;
}
#include <netinet/in.h>
#include <sys/EfiSysCall.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int testTCPSocket(char *serverIP, int serverPort)
{
int rc;
int sock;
struct sockaddr_in v4;
char data[1024];
size_t sentBytes;
size_t sendStrLen;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1)
{
printf("init socket error\n");
return -1;
}
memset(&v4, 0x00, sizeof(v4));
v4.sin_len = sizeof(v4);
v4.sin_family = AF_INET;
v4.sin_addr.s_addr = inet_addr(serverIP);
v4.sin_port = htons(serverPort);
rc = connect(sock, (struct sockaddr*)&v4, sizeof(v4));
if (rc == -1)
{
printf("connect() failed (%d)\n", rc);
//return -1;
}
printf("input string to send or 'q' to exit connection\n");
while (1)
{
memset(data, 0x00, sizeof(data));
fgets(data, sizeof(data) - 1, stdin);
if (data[0] == 'q')
{
printf("ready to exit connection\n");
break;
}
sendStrLen = strlen(data);
if (sendStrLen > 0 && sendStrLen < 1023)
{
sentBytes = send(sock, data, sendStrLen, 0);
printf("\t !!! Sent data: %s(%d) --- \n", data, sentBytes);
}
}
close(sock);
return 0;
}
[LibraryClasses]
UefiLib
#include <library/efibootservicestablelib.h>
void triggerWatchdog(int sec)
{
gBS->SetWatchdogTimer(sec, 0x0000, 0x00, NULL);
}
int main(void)
{
triggerWatchdog(10);
while (1) ;
return 0;
}
[LibraryClasses]
UefiLib
#include <library/efibootservicestablelib.h>
int main(void)
{
gRT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
return 0;
}
void mySleep(int retrySleepSecs)
{
#ifdef WINDOWS_PC
Sleep(retrySleepSecs * 1000);
#else
sleep(retrySleepSecs);
#endif // WINDOWS_PC
}
package main
import "net"
import "fmt"
func main() {
port := 8080
fmt.Printf("Launching TCP server port %d\n", port)
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
fmt.Println(err)
return
}
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
defer conn.Close()
remoteIP := conn.RemoteAddr().String()
buf := make([]byte, 1024)
fmt.Println("--------------------")
fmt.Println(remoteIP)
for {
reqLen, err := conn.Read(buf)
if err != nil {
//fmt.Println(err)
break
}
if reqLen > 0 {
fmt.Printf("%s(%d)\n", string(buf[:reqLen]), reqLen)
}
}
conn.Close()
fmt.Println("socket closed")
}
TCPSend - DOS (僅列出修改部份,其他都是原本的)
int sendTCP(char *msg, int len)
{
int sendLen = 0;
int rc;
while (sendLen < len)
{
rc = sock->send( (uint8_t *)(msg+sendLen), len-sendLen);
PACKET_PROCESS_SINGLE;
Arp::driveArp( );
Tcp::drivePackets( );
if (rc > 0) {
sendLen += rc;
}
else if ( rc == 0 ) {
// Out of send buffers maybe? Loop around to process packets
printf("sock->send error ?\n");
return -1;
}
else {
return -1;
}
}
return 0;
}
int main( int argc, char *argv[] ) {
// Initialize TCP/IP
if ( Utils::parseEnv( ) != 0 ) {
exit(1);
}
if ( Utils::initStack( 1, TCP_SOCKET_RING_SIZE ) ) {
fprintf( stderr, "\nFailed to initialize TCP/IP - exiting\n" );
exit(1);
}
// From this point forward you have to call the shutdown( ) routine to
// exit because we have the timer interrupt hooked.
// Start
Utils::Debugging |= 0xff;
ServerPort = 8080;
strcpy(Hostname, "192.168.11.9");
fprintf( stderr, "Server: %s:%u\n", Hostname, ServerPort);
if ( resolve(Hostname, HostAddr) ) shutdown( 1 );
if ( connectSocket( ) ) shutdown( 1 );
// send
int rc;
char data[64];
int sent_bytes;
int sendstrlen;
printf("input message to send or 'q' to exit \n\n");
while (1)
{
memset(data, 0x00, sizeof(data));
fgets(data, sizeof(data) - 1, stdin);
if (data[0] == 'q')
{
printf("ready to exit connection\n");
break;
}
sendstrlen = strlen(data);
if (sendstrlen > 0 && sendstrlen < 64)
{
rc = sendTCP(data, sendstrlen);
printf("rc = %d \n", rc);
}
}
shutdown( rc );
}