I am working on a small script which uses bufio.Scanner and http.Request as well as go routines to count words and lines in parallel.
package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"time"
)
func main() {
err := request("http://www.google.com")
if err != nil {
log.Fatal(err)
}
// just keep main alive with sleep for now
time.Sleep(2 * time.Second)
}
func request(url string) error {
res, err := http.Get(url)
if err != nil {
return err
}
go scanLineWise(res.Body)
go scanWordWise(res.Body)
return err
}
func scanLineWise(r io.Reader) {
s := bufio.NewScanner(r)
s.Split(bufio.ScanLines)
i := 0
for s.Scan() {
i++
}
fmt.Printf("Counted %d lines.\n", i)
}
func scanWordWise(r io.Reader) {
s := bufio.NewScanner(r)
s.Split(bufio.ScanWords)
i := 0
for s.Scan() {
i++
}
fmt.Printf("Counted %d words.\n", i)
}
Source
As more or less expected from streams scanLineWise will count a number while scalWordWise will count zero. This is because scanLineWise already reads everything from req.Body.
I would know like to know: How to solve this elegantly?
My first thought was to build a struct which implements io.Reader and io.Writer. We could use io.Copy to read from req.Body and write it to the writer. When the scanners read from this writer then writer will copy the data instead of reading it. Unfortunately this will just collect memory over time and break the whole idea of streams...
The options are pretty straightforward -- you either maintain the "stream" of data, or you buffer the body.
If you really do need to read over the body more then once sequentially, you need to buffer it somewhere. There's no way around that.
There's a number of way you could stream the data, like having the line counter output lines into the word counter (preferably through channels). You could also build a pipeline using io.TeeReader and io.Pipe, and supply a unique reader for each function.
...
pipeReader, pipeWriter := io.Pipe()
bodyReader := io.TeeReader(res.Body, pipeWriter)
go scanLineWise(bodyReader)
go scanWordWise(pipeReader)
...
That can get unwieldy with more consumers though, so you could use io.MultiWriter to multiplex to more io.Readers.
...
pipeOneR, pipeOneW := io.Pipe()
pipeTwoR, pipeTwoW := io.Pipe()
pipeThreeR, pipeThreeW := io.Pipe()
go scanLineWise(pipeOneR)
go scanWordWise(pipeTwoR)
go scanSomething(pipeThreeR)
// of course, this should probably have some error handling
io.Copy(io.MultiWriter(pipeOneW, pipeTwoW, pipeThreeW), res.Body)
...
You could use channels, do the actual reading in your scanLineWise then pass the lines to scanWordWise, for example:
func countLines(r io.Reader) (ch chan string) {
ch = make(chan string)
go func() {
s := bufio.NewScanner(r)
s.Split(bufio.ScanLines)
cnt := 0
for s.Scan() {
ch <- s.Text()
cnt++
}
close(ch)
fmt.Printf("Counted %d lines.\n", cnt)
}()
return
}
func countWords(ch <-chan string) {
cnt := 0
for line := range ch {
s := bufio.NewScanner(strings.NewReader(line))
s.Split(bufio.ScanWords)
for s.Scan() {
cnt++
}
}
fmt.Printf("Counted %d words.\n", cnt)
}
func main() {
r := strings.NewReader(body)
ch := countLines(r)
go countWords(ch)
time.Sleep(1 * time.Second)
}
Related
I have a problem. I want to write something similar to a turnstile, with face recognition. I use gocv and kagami/go-face for this. I have a stream from a webcam. The problem is that it recognizes the image too quickly and every time it recognizes a face, it opens a passage for it. That is, it pulls the opening function 10 times per second, for example. And I want him to open it once. So I have 2 functions readStream and opener. Maybe you can somehow not read the stream or stop the stream until another person appears in the frame? The goroutine go readStream() is called first, and then go opener()
func readStream(c chan int) {
recognizer, err := face.NewRecognizer(config.Recognizer.ModelsDir)
if err != nil {
log.Fatalf("Can't init face recognizer: %v", err)
}
webcam, err := gocv.OpenVideoCapture(videoSrc)
if err != nil {
log.Fatalf("Error opening capture device: %v", videoSrc)
}
img := gocv.NewMat()
defer img.Close()
window := gocv.NewWindow("videosourse")
defer window.Close()
for {
if ok := webcam.Read(&img); !ok || img.Empty() {
fmt.Printf("Device closed: %v\n", videoSrc)
return
}
jpgImageBuffer, err := gocv.IMEncode(gocv.JPEGFileExt, img)
if err != nil {
log.Errorf("ERROR: %s", err.Error())
}
f, err := recognizer.RecognizeSingle(jpgImageBuffer.GetBytes())
if err == nil && f != nil {
catID := recognizer.ClassifyThreshold(f.Descriptor, config.Recognizer.Tolerance)
if catID > 0 {
c <- catID
}
}
window.IMShow(img)
window.WaitKey(1)
}
}
func opener(c chan int) {
timeout := time.After(5 * time.Second)
for {
select {
case id := <-c:
fmt.Printf("####### OPENED for %d #######\n", id)
case <-timeout:
<-c
fmt.Println("Time's up! All data read in nothing")
break
}
}
}
i tried to use sync.once , but it stopped the webcam video stream after 1st recognition
I have a Delphi dll that needs to be called from golang (go). I can load and call the dll using syscall.Syscall, or windows.Call. Both methods execute the dll correctly. The dll returns its result by changing a string buffer that is passed to it. When I later inspect the string, it is empty (in syscall) or panics in windows.Call. I have tried several permutations but haven't had any luck getting my value out of the variable that should store the result.
Example using windows.Call:
// Package getSID calls SIDgenerator and generates a SID for Retail Pro
package main
import (
"fmt"
"unsafe"
"golang.org/x/sys/windows"
"unicode/utf16"
)
var (
sidgeneratorDLL, _ = windows.LoadDLL("sidgenerator64.dll")
getRandomSID, _ = sidgeneratorDLL.FindProc("GetRandomSID")
)
// StringToCharPtr converts a Go string into pointer to a null-terminated cstring.
// This assumes the go string is already ANSI encoded.
func StringToCharPtr(str string) *uint8 {
chars := append([]byte(str), 0) // null terminated
return &chars[0]
}
// GetRandomSID generates random SID, UPC SID or ALU SID
func GetRandomSID(Buffer []uint16, BufSize uint64) (result byte) {
// var nargs uintptr = 2
fmt.Println(Buffer)
ret, _, callErr := getRandomSID.Call(uintptr(unsafe.Pointer(&Buffer)),
uintptr(unsafe.Pointer(&BufSize)))
// fmt.Println("Buffer", Buffer)
if callErr != nil {
fmt.Println("===== CallErr =====")
fmt.Println(ret, callErr)
// fmt.Println("Buffer", Buffer)
}
result = byte(ret)
return
}
func main() {
defer sidgeneratorDLL.Release()
buffer := utf16.Encode([]rune("12345678901234567890\000"))
bufSize := uint64(len(buffer))
fmt.Printf("Result in: %v\n", buffer)
err := GetRandomSID(buffer, bufSize)
fmt.Printf("Result in: %v\n", buffer)
fmt.Println("Err =", err)
fmt.Println("Called GetRandomSID")
fmt.Printf("Result out: %v\n", buffer)
}
func init() {
fmt.Print("Starting Up\n")
}
Example using syscall:
// Package getSID calls SIDgenerator and generates a SID for Retail Pro
package main
import (
"fmt"
"syscall"
"unsafe"
)
var (
sidgeneratorDLL, _ = syscall.LoadLibrary("sidgenerator64.dll")
getRandomSID, _ = syscall.GetProcAddress(sidgeneratorDLL, "GetRandomSID")
)
// GetRandomSID generates random SID, UPC SID or ALU SID
func GetRandomSID(Buffer *[]byte, BufSize *uint32) (result byte) {
var nargs uintptr = 2
fmt.Println(*Buffer)
ret, _, callErr := syscall.Syscall(uintptr(getRandomSID),
nargs, 0,
uintptr(unsafe.Pointer(Buffer)),
uintptr(unsafe.Pointer(BufSize)),
)
fmt.Println(*Buffer)
if callErr != 0 {
fmt.Println("===== CallErr =====")
fmt.Println(callErr)
}
result = byte(ret)
return
}
func main () {
defer syscall.FreeLibrary(sidgeneratorDLL)
buffer := []byte("1234567890123456789012")
bufSize := uint32(len(buffer))
fmt.Printf("Result in: %s\n", string(buffer))
err := GetRandomSID(&buffer, &bufSize)
fmt.Println("Err =", err)
fmt.Println("Called GetRandomSID")
fmt.Printf("Result out: %s\n", string(buffer))
}
func init() {
fmt.Print("Starting Up\n")
}
Any help will be greatly appreciated. Thanks in advance!
C# external declarations: --------------------------------
[DllImport("SIDGenerator.dll", CharSet = CharSet.Ansi)] static extern Boolean GetSIDFromALU(string ALU, StringBuilder SID, ref int buflen);
[DllImport("SIDGenerator.dll", CharSet = CharSet.Ansi)] static extern Boolean GetSIDFromUPC( string UPC, StringBuilder SID, ref int buflen);
[DllImport("SIDGenerator.dll", CharSet = CharSet.Ansi)] static extern Boolean GetRandomSID(StringBuilder SID, ref int buflen);
Delphi external declarations: -----------------------------------
function GetSIDFromALU( ALU: Pchar; Buffer: PChar; var BufSize : integer ): LongBool; stdcall; external ‘SIDGenerator.dll’;
function GetSIDFromUPC( UPC: PChar; Buffer: PChar; var BufSize : integer ): LongBool; stdcall; external ‘SIDGenerator.dll’;
function GetRandomSID( Buffer: PChar; var BufSize : integer ): LongBool; stdcall; external ‘SIDGenerator.dll’;
In Python I call it with this code and it works beautifully:
# Get Retail Pro SID using dll
from ctypes import windll, create_string_buffer, c_int, byref
# os.chdir("c:\\Users\\irving\\Documents\\gitHub\\POImport")
# print(os.getcwd())
# getSID is a Retail Pro dll use to generate SIDs
getSID = windll.SIDGenerator64
randomSID = getSID.GetRandomSID
aluSID = getSID.GetSIDFromALU
upcSID = getSID.GetSIDFromUPC
# Set this by hand now, later set it interactively or by parameter
subsidiary = "1"
def getRandomSID():
""" Genera un SID aleatorio """
# Generate a new random SID
newSID = create_string_buffer(str.encode("12345678901234567890"))
size = c_int(len(newSID))
randomSID(newSID, byref(size))
return newSID.value
def getALUSID(alu):
""" Genera un SID basado en ALU """
# Generate a new ALU base SID
ALU = create_string_buffer(str.encode(alu))
newSID = create_string_buffer(str.encode("12345678901234567890"))
size = c_int(len(newSID))
aluSID(ALU, newSID, byref(size))
return newSID.value
def getUPCSID(upc):
""" Genera un SID basado en UPC """
# Generate a new UPC based SID
UPC = create_string_buffer(str.encode(upc))
newSID = create_string_buffer(str.encode("12345678901234567890"))
size = c_int(len(newSID))
upcSID(UPC, newSID, byref(size))
return newSID.value
You are passing the pointer to the slice, instead of a pointer to the backing array of the slice.
With your windows.Call code it should be.
ret, _, callErr := getRandomSID.Call(uintptr(unsafe.Pointer(&Buffer[0])),
uintptr(unsafe.Pointer(&BufSize)))
Or your syscall.Syscall version, where its a pointer to the slice.
ret, _, callErr := syscall.Syscall(uintptr(getRandomSID),
nargs, 0,
uintptr(unsafe.Pointer(&(*Buffer)[0])),
uintptr(unsafe.Pointer(BufSize)),
)
I need to build a tree structure recursively of only directories for a given root/parent path. something like "browse for folder" dialog.
Delphi's FindFirst (FindFirstFile API) is not working with faDirectory and FindNext will get all files (it uses faAnyFile regardless of the specified faDirectory) not only directories. which make the process of building the tree very slow.
Is there a fast way to get a directory list (tree) without using FindFirst/FindNext?
the absolute fastest way, use the NtQueryDirectoryFile api. with this we can query not single file but many files at once. also select what information will be returned (smaller info - higher speed). example (with full recursion)
// int nLevel, PSTR prefix for debug only
void ntTraverse(POBJECT_ATTRIBUTES poa, int nLevel, PSTR prefix)
{
enum { ALLOCSIZE = 0x10000 };//64kb
if (nLevel > MAXUCHAR)
{
DbgPrint("nLevel > MAXUCHAR\n");
return ;
}
NTSTATUS status;
IO_STATUS_BLOCK iosb;
UNICODE_STRING ObjectName;
OBJECT_ATTRIBUTES oa = { sizeof(oa), 0, &ObjectName };
DbgPrint("%s[<%wZ>]\n", prefix, poa->ObjectName);
if (0 <= (status = NtOpenFile(&oa.RootDirectory, FILE_GENERIC_READ, poa, &iosb, FILE_SHARE_VALID_FLAGS,
FILE_SYNCHRONOUS_IO_NONALERT|FILE_OPEN_REPARSE_POINT|FILE_OPEN_FOR_BACKUP_INTENT)))
{
if (PVOID buffer = new UCHAR[ALLOCSIZE])
{
union {
PVOID pv;
PBYTE pb;
PFILE_DIRECTORY_INFORMATION DirInfo;
};
while (0 <= (status = NtQueryDirectoryFile(oa.RootDirectory, NULL, NULL, NULL, &iosb,
pv = buffer, ALLOCSIZE, FileDirectoryInformation, 0, NULL, FALSE)))
{
ULONG NextEntryOffset = 0;
do
{
pb += NextEntryOffset;
ObjectName.Buffer = DirInfo->FileName;
switch (ObjectName.Length = (USHORT)DirInfo->FileNameLength)
{
case 2*sizeof(WCHAR):
if (ObjectName.Buffer[1] != '.') break;
case sizeof(WCHAR):
if (ObjectName.Buffer[0] == '.') continue;
}
ObjectName.MaximumLength = ObjectName.Length;
if (DirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
ntTraverse(&oa, nLevel + 1, prefix - 1);
}
} while (NextEntryOffset = DirInfo->NextEntryOffset);
}
delete [] buffer;
if (status == STATUS_NO_MORE_FILES)
{
status = STATUS_SUCCESS;
}
}
NtClose(oa.RootDirectory);
}
if (0 > status)
{
DbgPrint("---- %x %wZ\n", status, poa->ObjectName);
}
}
void ntTraverse()
{
BOOLEAN b;
RtlAdjustPrivilege(SE_BACKUP_PRIVILEGE, TRUE, FALSE, &b);
char prefix[MAXUCHAR + 1];
memset(prefix, '\t', MAXUCHAR);
prefix[MAXUCHAR] = 0;
STATIC_OBJECT_ATTRIBUTES(oa, "\\systemroot");
ntTraverse(&oa, 0, prefix + MAXUCHAR);
}
but if you use interactive tree - you not need expand all tree at once, but only top level, handle TVN_ITEMEXPANDING with TVE_EXPAND and TVN_ITEMEXPANDED with TVE_COLLAPSE for expand/ collapse nodes on user click and set cChildren
if use FindFirstFileExW with FIND_FIRST_EX_LARGE_FETCH and FindExInfoBasic this give to as near NtQueryDirectoryFile perfomance, but little smaller:
WIN32_FIND_DATA fd;
HANDLE hFindFile = FindFirstFileExW(L"..\\*", FindExInfoBasic, &fd, FindExSearchLimitToDirectories, 0, FIND_FIRST_EX_LARGE_FETCH);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (fd.cFileName[0] == '.')
{
switch (fd.cFileName[1])
{
case 0:
continue;
case '.':
if (fd.cFileName[2] == 0) continue;
break;
}
}
DbgPrint("%S\n", fd.cFileName);
}
} while (FindNextFile(hFindFile, &fd));
FindClose(hFindFile);
}
unfortunately FindExSearchLimitToDirectories not implemented currently
Find(First|Next)/File() is a viable solution, especially in Delphi 7. Just filter out the results you don't need, eg:
if FindFirst(Root, faDirectory, sr) = 0 then
try
repeat
if (sr.Attr and faDirectory <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then
begin
// ...
end;
until FindNext(sr) <> 0;
finally
FindClose(sr);
end;
If that is not fast enough for you, then other options include:
On Win7+, use FindFirstFileEx() with FindExInfoBasic and FIND_FIRST_EX_LARGE_FETCH. That will provide speed improvements over FindFirstFile().
access the filesystem metadata directly. On NTFS, you can use DeviceIoControl() to enumerate the Master File Table directly.
If you have Delphi XE2 or newer, the fastest way is to use the TDirectory.GetDirectories defined in th System.IOUtils.
Sample code:
procedure TVideoCamera.GetInterfaceNameList(
const AInterfaceNameList: TInterfaceNameList);
const
SEARCH_OPTION = TSearchOption.soTopDirectoryOnly;
PREDICATE = nil;
var
interfaceList: TStringDynArray;
idxInterface: Integer;
interfaceName: String;
begin
interfaceList := TDirectory.GetDirectories(GetCameraDirectory, SEARCH_OPTION,
PREDICATE);
AInterfaceNameList.Clear;
for idxInterface := Low(interfaceList) to High(interfaceList) do
begin
interfaceName := ExtractFileName(InterfaceList[idxInterface]);
AInterfaceNameList.Add(interfaceName);
end;
end;
I have the following function below that gathers the document properties of a PDF that I am printing.
For some reason, in Delphi 7 (running XP), this works great...however, when I try to recompile with Delphi XE using Windows 7, the function always seems to exit failing...dwRet = IDOK!
I noticed that my dwNeeded object in Delphi 7 was 7332, and in XE it is 4294967295!!
Any idea how I can quickly fix this?
Function TPrintPDF.GetPrinterDevMode ( pDevice: PChar ): PDevMode;
Var
pDevModeVar : PDevMode;
pDevModeVar2 : PDevMode;
dwNeeded : DWord;
dwRet : DWord;
Begin
{ Start by opening the printer }
If (Not OpenPrinter (pDevice, PrinterHandle, Nil))
Then Result := Nil;
{ Step 1: Allocate a buffer of the correct size }
dwNeeded := DocumentProperties (0,
PrinterHandle, { Handle to our printer }
pDevice, { Name of the printer }
pDevModevar^, { Asking for size, so these are not used }
pDevModeVar^,
0); { Zero returns buffer size }
GetMem (pDevModeVar, dwNeeded);
{ Step 2: Get the default DevMode for the printer }
dwRet := DocumentProperties (0,
PrinterHandle,
pDevice,
pDevModeVar^, { The address of the buffer to fill }
pDevModeVar2^, { Not using the input buffer }
DM_OUT_BUFFER); { Have the output buffer filled }
{ If failure, cleanup and return failure }
If (dwRet <> IDOK) Then Begin
FreeMem (pDevModeVar);
ClosePrinter (PrinterHandle);
Result := Nil;
End;
{ Finished with the printer }
ClosePrinter (PrinterHandle);
{ Return the DevMode structure }
Result := pDevModeVar;
End; { GetPrinterDevMode Function }
Here are the problems that I can see with your code:
The return value of DocumentProperties is a signed 32 bit integer. It's declared as LONG. A negative value means an error occurred and that's what's happening to you. Only you don't see the negative value because you've stuffed the value into an unsigned integer. Unfortunately XE fails to declare LONG. So change your code to use Integer instead.
You don't check for errors when DocumentProperties returns. If an error occurs, a negative value is returned. Make sure you check for that.
You are passing random garbage in the 4th and 5th parameters to DocumentProperties. I suspect that you can pass nil for both parameters the first time that you call DocumentProperties. You can certainly pass nil for the 5th parameter both times you call the function since you never set DM_IN_BUFFER.
When errors occur you set Result to nil, but you continue executing the rest of the function. Don't do that. Call exit to break out of the function. Assigning to Result does not terminate execution in the way that return does in C-like languages does.
Use a try/finally block to ensure that you call CloseHandle. That allows you to write CloseHandle once only.
Here's the solution that David suggested...Thanks David!
{ ---------------------------------------------------------------------------- }
Function TPrintPDF.GetPrinterDevMode ( pDevice: PChar ): PDevMode;
Var
pDevModeVar : PDevMode;
pDevModeVar2 : PDevMode;
dwNeeded : Long64;
dwRet : Long64;
Begin
Result := Nil;
{ Start by opening the printer }
If (OpenPrinter (pDevice, PrinterHandle, Nil)) Then Begin
Try
{ Step 1: Allocate a buffer of the correct size }
dwNeeded := DocumentProperties (0,
PrinterHandle, { Handle to our printer }
pDevice, { Name of the printer }
Nil, { Asking for size, so these are not used }
Nil,
0); { Zero returns buffer size }
{ Exit if this fails }
If (dwNeeded < 0)
Then Exit;
GetMem (pDevModeVar, dwNeeded);
{ Step 2: Get the default DevMode for the printer }
dwRet := DocumentProperties (0,
PrinterHandle,
pDevice,
pDevModeVar^, { The address of the buffer to fill }
pDevModeVar2^, { Not using the input buffer }
DM_OUT_BUFFER); { Have the output buffer filled }
{ If failure, cleanup and return failure }
If (dwRet <> IDOK) Then Begin
FreeMem (pDevModeVar);
ClosePrinter (PrinterHandle);
Result := Nil;
End;
{ Finished with the printer }
Finally
ClosePrinter (PrinterHandle);
End; { Try }
{ Return the DevMode structure }
Result := pDevModeVar;
End; { If we could open the printer }
End; { GetPrinterDevMode Function }
For example, having basic packet protocol, like:
[packetType int][packetId int][data []byte]
And making a client and server doing simple things with it (egx, chatting.)
Here's a client and server with sloppy panic error-handling. They have some limitations:
The server only handles one client connection at a time. You could fix this by using goroutines.
Packets always contain 100-byte payloads. You could fix this by putting a length in the packet somewhere and not using encoding/binary for the entire struct, but I've kept it simple.
Here's the server:
package main
import (
"encoding/binary"
"fmt"
"net"
)
type packet struct {
// Field names must be capitalized for encoding/binary.
// It's also important to use explicitly sized types.
// int32 rather than int, etc.
Type int32
Id int32
// This must be an array rather than a slice.
Data [100]byte
}
func main() {
// set up a listener on port 2000
l, err := net.Listen("tcp", ":2000")
if err != nil {
panic(err.String())
}
for {
// start listening for a connection
conn, err := l.Accept()
if err != nil {
panic(err.String())
}
handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer conn.Close()
// a client has connected; now wait for a packet
var msg packet
binary.Read(conn, binary.BigEndian, &msg)
fmt.Printf("Received a packet: %s\n", msg.Data)
// send the response
response := packet{Type: 1, Id: 1}
copy(response.Data[:], "Hello, client")
binary.Write(conn, binary.BigEndian, &response)
}
Here's the client. It sends one packet with packet type 0, id 0, and the contents "Hello, server". Then it waits for a response, prints it, and exits.
package main
import (
"encoding/binary"
"fmt"
"net"
)
type packet struct {
Type int32
Id int32
Data [100]byte
}
func main() {
// connect to localhost on port 2000
conn, err := net.Dial("tcp", ":2000")
if err != nil {
panic(err.String())
}
defer conn.Close()
// send a packet
msg := packet{}
copy(msg.Data[:], "Hello, server")
err = binary.Write(conn, binary.BigEndian, &msg)
if err != nil {
panic(err.String())
}
// receive the response
var response packet
err = binary.Read(conn, binary.BigEndian, &response)
if err != nil {
panic(err.String())
}
fmt.Printf("Response: %s\n", response.Data)
}
Check out Jan Newmarch's "Network programming with Go".