Search Results

Search found 183 results on 8 pages for 'chr'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • Ruby SerialPorts

    - by Seth Archer
    I'm using the ruby serial port gem. After I open up the port I send the data I want like this. sp.write [200.chr, 30.chr, 7.chr, 5.chr, 1.chr, 2.chr, 0.chr, 245.chr].to_s It doesn't work, but if I put it in a loop of around 200 times: 200.times do sp.write [200.chr, 30.chr, 7.chr, 5.chr, 1.chr, 2.chr, 0.chr, 245.chr].to_s end It works. Any ideas on why this is happening?

    Read the article

  • How do I create JavaScript escape sequences in PHP?

    - by ordinarytoucan
    I'm looking for a way to create valid UTF-16 JavaScript escape sequence characters (including surrogate pairs) from within PHP. I'm using the code below to get the UTF-32 code points (from a UTF-8 encoded character). This works as JavaScript escape characters (eg. '\u00E1' for 'á') - until you get into the upper ranges where you get surrogate pairs (eg '??' comes out as '\u1D715' but should be '\uD835\uDF15')... function toOrdinal($chr) { if (ord($chr{0}) >= 0 && ord($chr{0}) <= 127) { return ord($chr{0}); } elseif (ord($chr{0}) >= 192 && ord($chr{0}) <= 223) { return (ord($chr{0}) - 192) * 64 + (ord($chr{1}) - 128); } elseif (ord($chr{0}) >= 224 && ord($chr{0}) <= 239) { return (ord($chr{0}) - 224) * 4096 + (ord($chr{1}) - 128) * 64 + (ord($chr{2}) - 128); } elseif (ord($chr{0}) >= 240 && ord($chr{0}) <= 247) { return (ord($chr{0}) - 240) * 262144 + (ord($chr{1}) - 128) * 4096 + (ord($chr{2}) - 128) * 64 + (ord($chr{3}) - 128); } elseif (ord($chr{0}) >= 248 && ord($chr{0}) <= 251) { return (ord($chr{0}) - 248) * 16777216 + (ord($chr{1}) - 128) * 262144 + (ord($chr{2}) - 128) * 4096 + (ord($chr{3}) - 128) * 64 + (ord($chr{4}) - 128); } elseif (ord($chr{0}) >= 252 && ord($chr{0}) <= 253) { return (ord($chr{0}) - 252) * 1073741824 + (ord($chr{1}) - 128) * 16777216 + (ord($chr{2}) - 128) * 262144 + (ord($chr{3}) - 128) * 4096 + (ord($chr{4}) - 128) * 64 + (ord($chr{5}) - 128); } } How do I adapt this code to give me proper UTF-16 code points? Thanks!

    Read the article

  • .Net using Chr() to parse text

    - by Marcx
    I'm building a simple client-server chat system. The clients send data to the server and the server resends the data to all the other clients. I'm using the TcpListener and Network stream classes to send the data between the client and the server. The fields I need to send are, for example: name, text, timestamp, etc. I separate them using the ASCII character 29. I'm also using ASCII character 30 to mark the end of the streamed data. The data is encoded with UTF8.. Is this a good approach? Will I run into problems? Are there better methods? UPDATE: Probably my question was misunderstood, so I explain it better.. Suppose to have a list of data to send from client to server, and suppose to send all the data in only one stream, how do you send these data? Using a markup Using a character as a delimiter Using a fixed length for every fields

    Read the article

  • Ruby SerialPorts Gem

    - by Seth Archer
    Using Ruby SerialPorts Gem to interact with hardware. When I write a byte array to the hardware using a program called "Serial Port Monitor" the hardware responds correctly. However, when I write the same byte array using ruby it doesn't work unless I do a read request just before the write request. This device doesn't respond correctly with this sp = SerialPort.new(args) sp.write [200.chr, 30.chr, 6.chr, 5.chr, 1.chr, 2.chr, 0.chr, 244.chr] But it does if I add a read request before the write. Like this sp SerialPort.new(args) sp.read sp.write [200.chr, 30.chr, 6.chr, 5.chr, 1.chr, 2.chr, 0.chr, 244.chr] This works, but I'm at a loss as to why. I should also add that the first snippet does work occasionally maybe 1/10 of the time.

    Read the article

  • How to fix Index out of range exception on idatareader

    - by Phil
    Good morning stack overflow, I have been forced into using the idatareader as opposed to the sqldatareader which has .hasrows available. In my code I am attempting to handle nulls like this: reader = GetContent(pageid) While reader.Read If reader("content") IsNot DBNull.Value Then content = Replace(reader("content"), Chr(38) + Chr(97) + Chr(109) + Chr(112) + Chr(59) + Chr(98) + Chr(104) + Chr(99) + Chr(112) + Chr(61) + Chr(49), "") If reader("id") IsNot DBNull.Value Then contentid = reader("id") End If Else contentid = -1 content = String.Empty End If End While Outputcontent.Text = content I am getting an 'Index Out of Range Exception' here: If reader("content") IsNot DBNull.Value Then The database does 100% contain 'content'

    Read the article

  • Char and Chr in Delphi

    - by JamesB
    The difference between Chr and Char when used in converting types is that one is a function and the other is cast So: Char(66) = Chr(66) I don't think there is any performance difference (at least I've never noticed any, one probably calls the other).... I'm fairly sure someone will correct me on this! Which do you use in your code and why?

    Read the article

  • Crack Protected Excel Sheet

    - by Gino Abraham
    The following snippet will allow you to unprotect an excel sheet which is protected using a password. press Alt + F11 when the excel is open, it will open up VB macro editor. Insert a Module and copy the following code. this will clear the password and you will be free to edit the file. if you want to unprotect the workbook rather the a work sheet change ActiveSheet to ThisWorkbook in the following code. Happy Cracking    Sub CrackPassword()       Dim v1 As Integer, u1 As Integer, w1 As Integer   Dim v2 As Integer, u2 As Integer, w2 As Integer   Dim v3 As Integer, u3 As Integer, w3 As Integer   Dim v4 As Integer, u4 As Integer, w4 As Integer   On Error Resume Next     For v1 = 65 To 66: For u1 = 65 To 66: For w1 = 65 To 66   For v2 = 65 To 66: For u2 = 65 To 66: For w2 = 65 To 66   For v3 = 65 To 66: For u3 = 65 To 66: For w3 = 65 To 66   For v4 = 65 To 66: For u4 = 65 To 66: For w4 = 32 To 126               ActiveSheet.Unprotect Chr(v1) & Chr(u1) & Chr(w1) & _       Chr(v2) & Chr(u2) & Chr(v3) & Chr(u3) & Chr(w3) & _       Chr(v4) & Chr(u4) & Chr(w4) & Chr(w2)          Next: Next: Next: Next: Next: Next   Next: Next: Next: Next: Next: Next End Sub

    Read the article

  • VBS Script Help.

    - by MalsiaPro
    I managed to get this code from you guys here, thanks so much with a collegue of mine, I ran this code a few times and it seems to work but stops after a while due to protected files such as system files, "Permission Denied" and then the script just stops, is there a way to modify the code below so that it can handle such protected files or whether it can pass them. Any advice or help is appreciated. Set objFS=CreateObject("Scripting.FileSystemObject") WScript.Echo Chr(34) & "Full Path" &_ Chr(34) & "," & Chr(34) & "File Size" &_ Chr(34) & "," & Chr(34) & "File Date modified" &_ Chr(34) & "," & Chr(34) & "File Date Created" &_ Chr(34) & "," & Chr(34) & "File Date Accessed" & Chr(34) Set objArgs = WScript.Arguments strFolder = objArgs(0) Set objFolder = objFS.GetFolder(strFolder) Go (objFolder) Sub Go(objDIR) If objDIR <> "\System Volume Information" Then For Each eFolder in objDIR.SubFolders Go eFolder Next End If For Each strFile In objDIR.Files WScript.Echo Chr(34) & strFile.Path & Chr(34) & "," &_ Chr(34) & strFile.Size & Chr(34) & "," &_ Chr(34) & strFile.DateLastModified & Chr(34) & "," &_ Chr(34) & strFile.DateCreated & Chr(34) & "," &_ Chr(34) & strFile.DateLastAccessed & Chr(34) Next End Sub Then call it from the command line like this. c:\test> cscript //nologo myscript.vbs "c:\" > "C:\test\Output.csv" Thank you :)

    Read the article

  • VBScript Issue Help Required.

    - by MalsiaPro
    I need a script that can run and pull information from any drive on a Windows operating system (Windows Server 2003), listing all files and folders which contain the following fields: The server is quite big and is within our domain. The required information is: Full file path (e.g. C:\Documents and Settings\user\My Documents\testPage.doc) File type (e.g. word document, spreadsheet, database etc) Size When Created When last modified When last accessed Also the script will need to convert that data to a CSV file, which later on I can modify and process in Excel. I can imagine that this data will be huge but I still need it. I am logged in as an administrator on the server and the script will need to also process protected files. As in previous posts I have read that the script will stop if such files are processed. I need to make sure that not a single file is skipped. Please note I have asked this question before but still have not got a working script. This is the script I got so far, file Test.vbs: Set objFS=CreateObject("Scripting.FileSystemObject") WScript.Echo Chr(34) & "Full Path" &_ Chr(34) & "," & Chr(34) & "File Size" &_ Chr(34) & "," & Chr(34) & "File Date modified" &_ Chr(34) & "," & Chr(34) & "File Date Created" &_ Chr(34) & "," & Chr(34) & "File Date Accessed" & Chr(34) Set objArgs = WScript.Arguments strFolder = objArgs(0) Set objFolder = objFS.GetFolder(strFolder) Go (objFolder) Sub Go(objDIR) If objDIR <> "\System Volume Information" Then For Each eFolder in objDIR.SubFolders Go eFolder Next End If For Each strFile In objDIR.Files WScript.Echo Chr(34) & strFile.Path & Chr(34) & "," &_ Chr(34) & strFile.Size & Chr(34) & "," &_ Chr(34) & strFile.DateLastModified & Chr(34) & "," &_ Chr(34) & strFile.DateCreated & Chr(34) & "," &_ Chr(34) & strFile.DateLastAccessed & Chr(34) Next End Sub I am currently using the command-line to run it: c:\test> cscript //nologo Test.vbs "c:\" > "C:\test\Output.csv" The script is not working. I don't know why.

    Read the article

  • C++: Chr() and unichr() equivalent?

    - by alex
    I could have sworn I used a chr() function 40 minutes ago but can't find the file. I know it can go up to 256 so I use this: std::string chars = ""; chars += (char) 42; //etc So that's alright, but I really want to access unicode characters. Can I do (w_char) 512? Or maybe something just like the unichr() function in python, I just can't find a way to access any of those characters.

    Read the article

  • How can unrealscript halt event handler execution after an arbitrary number of lines with no return or error?

    - by Dan Cowell
    I have created a class that extends TcpLink and is instantiated in a custom Kismet Sequence Action. It is being instantiated correctly and is making the GET HTTP request that I need it to (I have checked my access log in apache) and Apache is responding to the request with the appropriate content. The problem I have is that I'm using the event receive mode and it appears that somehow the handler for the Opened event is halted after a specific number of lines of code have executed. Here is my code for the Opened event: event Opened() { // A connection was established WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened"); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query"); //The HTTP GET request //char(13) and char(10) are carrage returns and new lines requesttext = "userId="$userId$"&apartmentId="$apartmentId; SendText("GET /"$path$"?"$requesttext$" HTTP/1.0"); SendText(chr(13)$chr(10)); SendText("Host: "$TargetHost); SendText(chr(13)$chr(10)); SendText("Connection: Close"); SendText(chr(13)$chr(10)$chr(13)$chr(10)); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sent request: "$requesttext); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] end HTTP query"); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkState: "$LinkState); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkMode: "$LinkMode); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] ReceiveMode: "$ReceiveMode); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Error: "$string(GetLastError())); } As you can see, a number of the Broadcast calls have been commented out. Initially, only the lines up to the Broadcast containing "[DNomad_TcpLinkClient] Sent request: " were being executed and none of the Broadcasts were commented out. After commenting out that line, the next Broadcast was successful and so on and so forth. As a test, I commented out the very first Broadcast to see if the connection closing had any effect: // A connection was established //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened"); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query"); Upon doing that, an additional Broadcast at the end of the function executed. Thus the inference that there is an upper limit to the number of lines executed. Additionally, my ReceivedText handler is never called, despite Apache returning the correct HTTP 200 response with a body. My working hypothesis is that somehow after the Sequence Action finishes executing the garbage collector cleans up the TcpLinkClient instance. My biggest source of confusion with that is how on earth it does it during the execution of an event handler. Has anyone ever seen anything like this before? My full TcpLinkClient class is below: /* * TcpLinkClient based on an example usage of the TcpLink class by Michiel 'elmuerte' Hendriks for Epic Games, Inc. * */ class DNomad_TcpLinkClient extends TcpLink; var PlayerController PC; var string TargetHost; var int TargetPort; var string path; var string requesttext; var string userId; var string apartmentId; var string statusCode; var string responseData; event PostBeginPlay() { super.PostBeginPlay(); } function DoTcpLinkRequest(string uid, string id) //removes having to send a host { userId = uid; apartmentId = id; Resolve(targethost); } function string GetStatus() { return statusCode; } event Resolved( IpAddr Addr ) { // The hostname was resolved succefully WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] "$TargetHost$" resolved to "$ IpAddrToString(Addr)); // Make sure the correct remote port is set, resolving doesn't set // the port value of the IpAddr structure Addr.Port = TargetPort; //dont comment out this log because it rungs the function bindport WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Bound to port: "$ BindPort() ); if (!Open(Addr)) { WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Open failed"); } } event ResolveFailed() { WorldInfo.Game.Broadcast(self, "[TcpLinkClient] Unable to resolve "$TargetHost); // You could retry resolving here if you have an alternative // remote host. //send failed message to scaleform UI //JunHud(JunPlayerController(PC).myHUD).JunMovie.CallSetHTML("Failed"); } event Opened() { // A connection was established //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened"); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query"); //The HTTP GET request //char(13) and char(10) are carrage returns and new lines requesttext = "userId="$userId$"&apartmentId="$apartmentId; SendText("GET /"$path$"?"$requesttext$" HTTP/1.0"); SendText(chr(13)$chr(10)); SendText("Host: "$TargetHost); SendText(chr(13)$chr(10)); SendText("Connection: Close"); SendText(chr(13)$chr(10)$chr(13)$chr(10)); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sent request: "$requesttext); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] end HTTP query"); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkState: "$LinkState); //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkMode: "$LinkMode); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] ReceiveMode: "$ReceiveMode); WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Error: "$string(GetLastError())); } event Closed() { // In this case the remote client should have automatically closed // the connection, because we requested it in the HTTP request. WorldInfo.Game.Broadcast(self, "Connection closed."); // After the connection was closed we could establish a new // connection using the same TcpLink instance. } event ReceivedText( string Text ) { WorldInfo.Game.Broadcast(self, "Received Text: "$Text); //we dont want the header info, so we split the string after two new lines Text = Split(Text, chr(13)$chr(10)$chr(13)$chr(10), true); WorldInfo.Game.Broadcast(self, "Split Text: "$Text); statusCode = Text; } event ReceivedLine( string Line ) { WorldInfo.Game.Broadcast(self, "Received Line: "$Line); } event ReceivedBinary( int Count, byte B[255] ) { WorldInfo.Game.Broadcast(self, "Received Binary of length: "$Count); } defaultproperties { TargetHost="127.0.0.1" TargetPort=80 //default for HTTP LinkMode=MODE_Text ReceiveMode=RMODE_Event path = "dnomad/datafeed.php" userId = "0"; apartmentId = "0"; statusCode = ""; send = false; }

    Read the article

  • SQL Injection Protection for dynamic queries

    - by jbugeja
    The typical controls against SQL injection flaws are to use bind variables (cfqueryparam tag), validation of string data and to turn to stored procedures for the actual SQL layer. This is all fine and I agree, however what if the site is a legacy one and it features a lot of dynamic queries. Then, rewriting all the queries is a herculean task and it requires an extensive period of regression and performance testing. I was thinking of using a dynamic SQL filter and calling it prior to calling cfquery for the actual execution. I found one filter in CFLib.org (http://www.cflib.org/udf/sqlSafe): <cfscript> /** * Cleans string of potential sql injection. * * @param string String to modify. (Required) * @return Returns a string. * @author Bryan Murphy ([email protected]) * @version 1, May 26, 2005 */ function metaguardSQLSafe(string) { var sqlList = "-- ,'"; var replacementList = "#chr(38)##chr(35)##chr(52)##chr(53)##chr(59)##chr(38)##chr(35)##chr(52)##chr(53)##chr(59)# , #chr(38)##chr(35)##chr(51)##chr(57)##chr(59)#"; return trim(replaceList( string , sqlList , replacementList )); } </cfscript> This seems to be quite a simple filter and I would like to know if there are ways to improve it or to come up with a better solution?

    Read the article

  • Python optimization

    - by Rami Jarrar
    Hi, I do like this: f = open('wl4.txt', 'w') hh = 0 ###################################### for n in range(1,5): for l in range(33,127): if n==1: b = chr(l) + '\n' f.write(b) hh += 1 elif n==2: for s0 in range(33, 127): b = chr(l) + chr(s0) + '\n' f.write(b) hh += 1 elif n==3: for s0 in range(33, 127): for s1 in range(33, 127): b = chr(l) + chr(s0) + chr(s1) + '\n' f.write(b) hh += 1 elif n==4: for s0 in range(33, 127): for s1 in range(33, 127): for s2 in range(33,127): b = chr(l) + chr(s0) + chr(s1) + chr(s2) + '\n' f.write(b) hh += 1 ###################################### print "We Made %d Words." %(hh) ###################################### f.close() So, is there any method to make it faster?

    Read the article

  • I Made Simple Generator,, Is there any faster way ??

    - by Rami Jarrar
    Hi, i do like this: import time f = open('wl4.txt', 'w') hh = 0 ###################################### for n in range(1,5): for l in range(33,127): if n==1: b = chr(l) + '\n' f.write(b) hh += 1 elif n==2: for s0 in range(33, 127): b = chr(l) + chr(s0) + '\n' f.write(b) hh += 1 elif n==3: for s0 in range(33, 127): for s1 in range(33, 127): b = chr(l) + chr(s0) + chr(s1) + '\n' f.write(b) hh += 1 elif n==4: for s0 in range(33, 127): for s1 in range(33, 127): for s2 in range(33,127): b = chr(l) + chr(s0) + chr(s1) + chr(s2) + '\n' f.write(b) hh += 1 ###################################### print "We Made %d Words." %(hh) ###################################### f.close() So, is there any faster method to make it faster,,

    Read the article

  • How to access elements in a complex list?

    - by Martin
    Hi, it's me and the lists again. I have a nice list, which looks like this: tmp = NULL t = NULL tmp$resultitem$count = "1057230" tmp$resultitem$status = "Ok" tmp$resultitem$menu = "PubMed" tmp$resultitem$dbname = "pubmed" t$resultitem$count = "305215" t$resultitem$status = "Ok" t$resultitem$menu = "PMC" t$resultitem$dbname = "pmc" tmp = c(tmp, t) t = NULL t$resultitem$count = "1" t$resultitem$status = "Ok" t$resultitem$menu = "Journals" t$resultitem$dbname = "journals" tmp = c(tmp, t) Which produces: str(tmp) List of 3 $ resultitem:List of 4 ..$ count : chr "1057230" ..$ status: chr "Ok" ..$ menu : chr "PubMed" ..$ dbname: chr "pubmed" $ resultitem:List of 4 ..$ count : chr "305215" ..$ status: chr "Ok" ..$ menu : chr "PMC" ..$ dbname: chr "pmc" $ resultitem:List of 4 ..$ count : chr "1" ..$ status: chr "Ok" ..$ menu : chr "Journals" ..$ dbname: chr "journals" Now I want to search through the elements of each "resultitem". I want to know the "dbname" for every database, that has less then 10 "count" (example). In this case it is very easy, as this list only has 3 elements, but the real list is a little bit longer. This could be simply done with a for loop. But is there a way to do this with some other function of R (like rapply)? My problem with those apply functions is, that they only look at one element. If I do a grep to get all "dbname" elements, I can not get the count of each element. rapply(tmp, function(x) paste("Content: ", x))[grep("dbname", names(rapply(tmp, c)))] Does someone has a better idea than a for loop? Thanx, Martin

    Read the article

  • How to transcode Windows-1251 to UTF-8?

    - by Ole Jak
    How to transcode Windows-1251 to UTF-8? Will such function do it? function win_to_utf($s) { for($i=0, $m=strlen($s); $i<$m; $i++) { $c=ord($s[$i]); if ($c<=127) {$t.=chr($c); continue; } if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; } if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; } if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; } if ($c==184) { $t.=chr(209).chr(209); continue; }; if ($c==168) { $t.=chr(208).chr(129); continue; }; } return $t; }

    Read the article

  • ODI 11g - Cleaning control characters and User Functions

    - by David Allan
    In ODI user functions have a poor name really, they should be user expressions - a way of wrapping common expressions that you may wish to reuse many times - across many different technologies is an added bonus. To illustrate look at the problem of how to remove control characters from text. Users ask these types of questions over all technologies - Microsoft SQL Server, Oracle, DB2 and for many years - how do I clean a string, how do I tokenize a string and so on. After some searching around you will find a few ways of doing this, in Oracle there is a convenient way of using the TRANSLATE and REPLACE functions. So you can convert some text using the following SQL; replace( translate('This is my string'||chr(9)||' which has a control character', chr(3)||chr(4)||chr(5)||chr(9), chr(3) ), chr(3), '' ) If you had many columns to perform this kind of transformation on, in the Oracle database the natural solution you'd go to would be to code this as a PLSQL function since you don't want the code splattered everywhere. Someone tells you that there is another control character that needs added equals a maintenance headache. Coding it as a PLSQL function will incur a context switch between SQL and PLSQL which could prove costly. In ODI user functions let you capture this expression text and reference it many times across your mappings. This will protect the expression from being copy-pasted by developers and make maintenance much simpler - change the expression definition in one place. Firstly define a name and a syntax for the user function, I am calling it UF_STRIP_BAD_CHARACTERS and it has one parameter an input string;  We then can define an implementation for each technology we will use it, I will define Oracle's using the inputString parameter and the TRANSLATE and REPLACE functions with whatever control characters I want to replace; I can then use this inside mapping expressions in ODI, below I am cleaning the ENAME column - a fabricated example but you get the gist.  Note when I use the user function the function name remains in the text of the mapping, the actual expression is not substituted until I generate the scenario. If you generate the scenario and export the scenario you can have a peak at the code that is processed in the runtime - below you can see a snippet of my export scenario;  That's all for now, hopefully a useful snippet of info.

    Read the article

  • Trouble with an depreciated constrictor visual basic visual studio 2010

    - by VBPRIML
    My goal is to print labels with barcodes and a date stamp from an entry to a zebra TLP 2844 when the user clicks the ok button/hits enter. i found what i think might be the code for this from zebras site and have been integrating it into my program but part of it is depreciated and i cant quite figure out how to update it. below is what i have so far. The printer is attached via USB and the program will also store the entered numbers in a database but i have that part done. any help would be greatly Appreciated.   Public Class ScanForm      Inherits System.Windows.Forms.Form    Public Const GENERIC_WRITE = &H40000000    Public Const OPEN_EXISTING = 3    Public Const FILE_SHARE_WRITE = &H2      Dim LPTPORT As String    Dim hPort As Integer      Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String,                                                                           ByVal dwDesiredAccess As Integer,                                                                           ByVal dwShareMode As Integer, <MarshalAs(UnmanagedType.Struct)> ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES,                                                                           ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer,                                                                           ByVal hTemplateFile As Integer) As Integer          Public Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (ByVal hObject As Integer) As Integer      Dim retval As Integer           <StructLayout(LayoutKind.Sequential)> Public Structure SECURITY_ATTRIBUTES          Private nLength As Integer        Private lpSecurityDescriptor As Integer        Private bInheritHandle As Integer      End Structure            Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click          Dim TrNum        Dim TrDate        Dim SA As SECURITY_ATTRIBUTES        Dim outFile As FileStream, hPortP As IntPtr          LPTPORT = "USB001"        TrNum = Me.ScannedBarcodeText.Text()        TrDate = Now()          hPort = CreateFile(LPTPORT, GENERIC_WRITE, FILE_SHARE_WRITE, SA, OPEN_EXISTING, 0, 0)          hPortP = New IntPtr(hPort) 'convert Integer to IntPtr          outFile = New FileStream(hPortP, FileAccess.Write) 'Create FileStream using Handle        Dim fileWriter As New StreamWriter(outFile)          fileWriter.WriteLine(" ")        fileWriter.WriteLine("N")        fileWriter.Write("A50,50,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrNum) 'prints the tracking number variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.Write("A50,100,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrDate) 'prints the date variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.WriteLine("P1")        fileWriter.Flush()        fileWriter.Close()        outFile.Close()        retval = CloseHandle(hPort)          'Add entry to database        Using connection As New SqlClient.SqlConnection("Data Source=MNGD-LABS-APP02;Initial Catalog=ScannedDB;Integrated Security=True;Pooling=False;Encrypt=False"), _        cmd As New SqlClient.SqlCommand("INSERT INTO [ScannedDBTable] (TrackingNumber, Date) VALUES (@TrackingNumber, @Date)", connection)            cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum            cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate            connection.Open()            cmd.ExecuteNonQuery()            connection.Close()        End Using          'Prepare data for next entry        ScannedBarcodeText.Clear()        Me.ScannedBarcodeText.Focus()      End Sub

    Read the article

  • Trouble with an depreciated constructor visual basic visual studio 2010

    - by VBPRIML
    My goal is to print labels with barcodes and a date stamp from an entry to a zebra TLP 2844 when the user clicks the ok button/hits enter. i found what i think might be the code for this from zebras site and have been integrating it into my program but part of it is depreciated and i cant quite figure out how to update it. below is what i have so far. The printer is attached via USB and the program will also store the entered numbers in a database but i have that part done. any help would be greatly Appreciated.   Public Class ScanForm      Inherits System.Windows.Forms.Form    Public Const GENERIC_WRITE = &H40000000    Public Const OPEN_EXISTING = 3    Public Const FILE_SHARE_WRITE = &H2      Dim LPTPORT As String    Dim hPort As Integer      Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String,                                                                           ByVal dwDesiredAccess As Integer,                                                                           ByVal dwShareMode As Integer, <MarshalAs(UnmanagedType.Struct)> ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES,                                                                           ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer,                                                                           ByVal hTemplateFile As Integer) As Integer          Public Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (ByVal hObject As Integer) As Integer      Dim retval As Integer           <StructLayout(LayoutKind.Sequential)> Public Structure SECURITY_ATTRIBUTES          Private nLength As Integer        Private lpSecurityDescriptor As Integer        Private bInheritHandle As Integer      End Structure            Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click          Dim TrNum        Dim TrDate        Dim SA As SECURITY_ATTRIBUTES        Dim outFile As FileStream, hPortP As IntPtr          LPTPORT = "USB001"        TrNum = Me.ScannedBarcodeText.Text()        TrDate = Now()          hPort = CreateFile(LPTPORT, GENERIC_WRITE, FILE_SHARE_WRITE, SA, OPEN_EXISTING, 0, 0)          hPortP = New IntPtr(hPort) 'convert Integer to IntPtr          outFile = New FileStream(hPortP, FileAccess.Write) 'Create FileStream using Handle        Dim fileWriter As New StreamWriter(outFile)          fileWriter.WriteLine(" ")        fileWriter.WriteLine("N")        fileWriter.Write("A50,50,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrNum) 'prints the tracking number variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.Write("A50,100,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrDate) 'prints the date variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.WriteLine("P1")        fileWriter.Flush()        fileWriter.Close()        outFile.Close()        retval = CloseHandle(hPort)          'Add entry to database        Using connection As New SqlClient.SqlConnection("Data Source=MNGD-LABS-APP02;Initial Catalog=ScannedDB;Integrated Security=True;Pooling=False;Encrypt=False"), _        cmd As New SqlClient.SqlCommand("INSERT INTO [ScannedDBTable] (TrackingNumber, Date) VALUES (@TrackingNumber, @Date)", connection)            cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum            cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate            connection.Open()            cmd.ExecuteNonQuery()            connection.Close()        End Using          'Prepare data for next entry        ScannedBarcodeText.Clear()        Me.ScannedBarcodeText.Focus()      End Sub

    Read the article

  • Page_load event firing twice. User control not properly loading

    - by Phil
    Here is the code I am using to pull my usercontrol (content.ascx): Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'load module If TheModule = "content" Then Dim control As UserControl = LoadControl("~\Modules\Content.ascx") Controls.Add(control) End If End Sub Within the usercontrol is the following code (data access taken care of by DAAB and ive replaced sql statements with 'sql'): Imports System.Data.SqlClient Imports System.Data Imports System.Web.Configuration Imports Microsoft.Practices.EnterpriseLibrary.Common Imports Microsoft.Practices.EnterpriseLibrary.Data Partial Class Modules_WebUserControl Inherits System.Web.UI.UserControl Dim db As Database = DatabaseFactory.CreateDatabase() Dim command As SqlCommand 'database Dim reader As IDataReader 'general vars Dim pageid As Integer Dim did As Integer Dim contentid As Integer Dim dotpos As String Dim ext As String Dim content As String Dim folder As String Dim downloadstring As String Function getimage(ByVal strin As String) As String If strin > "" Then dotpos = InStrRev(strin, ".") ext = Right(strin, Len(strin) - dotpos) getimage = ext & ".gif" Else getimage = String.Empty End If Return getimage End Function Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load 'test Response.Write("(1 Test from within page_load)") 'get session vars folder = Session("folder") pageid = Session("pageid") did = Session("did") 'main content command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@pageid", DbType.Int32, pageid) reader = db.ExecuteReader(command) While reader.Read If reader("content") IsNot DBNull.Value Then content = Replace(reader("content"), Chr(38) + Chr(97) + Chr(109) + Chr(112) + Chr(59) + Chr(98) + Chr(104) + Chr(99) + Chr(112) + Chr(61) + Chr(49), "") If reader("id") IsNot DBNull.Value Then contentid = reader("id") End If Else contentid = -1 content = String.Empty End If End While Outputcontent.Text = content 'contacts info If did = 0 Then command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read() Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If If Not did = 0 Then command = (db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) db.AddInParameter(command, "@did", DbType.Int32, did) reader = db.ExecuteReader(command) While reader.Read Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If 'downloads box command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & folder & "/" & reader("filename") & "'>" downloadstring += "<img src=images/" & getimage(reader("filename")) & " border=0 align=absmiddle />" End If If reader("filesize") IsNot DBNull.Value Then downloadstring += Convert.ToInt32((reader("filesize") / 1000)) & "kb - " End If If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & Session("folder") & "/" & reader("filename") & "'>" & reader("description") & "</a><br />" End If End While Dim downloadsarray As ArrayList downloadsarray = New ArrayList If downloadstring IsNot Nothing Then downloadsarray.Add(downloadstring) End If If downloadsarray.Count > 0 Then DownloadsRepeater.DataSource = downloadsarray DownloadsRepeater.DataBind() End If 'get links command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read Linksrepeater.DataSource = reader Linksrepeater.DataBind() End While End Sub End Class Now instead of seeing my page content and what should be within the repeaters on the page all I get is 2 x the output of Response.Write("(1 Test from within page_load)") (1 Test from within page_load)(1 Test from within page_load) This leads me to believe the page_load is firing twice, but not properly displaying all the information. Please can one of you willing experts help me to get this working? Thanks a lot in advance

    Read the article

  • Why is /dev/rfcomm0 giving PySerial problems?

    - by Travis G.
    I am connecting my Ubuntu box to a wireless readout setup over Bluetooth. I wrote a Python script to send the serial information through /dev/rfcomm0. The script connects fine and works for a few minutes, but then Python will start using 100% CPU and the messages stop flowing through. I can open rfcomm0 in a serial terminal and communicate through it by hand just fine. When I open it through a terminal it seems to work indefinitely. Also, I can swap the Bluetooth receiver for a USB cable, and change the port to /dev/ttyUSB0, and I don't get any problems over time. It seems either I'm doing something wrong with rfcomm0 or PySerial doesn't handle it well. Here's the script: import psutil import serial import string import time sampleTime = 1 numSamples = 5 lastTemp = 0 TEMP_CHAR = 't' USAGE_CHAR = 'u' SENSOR_NAME = 'TC0D' gauges = serial.Serial() gauges.port = '/dev/rfcomm0' gauges.baudrate = 9600 gauges.parity = 'N' gauges.writeTimeout = 0 gauges.open() print("Connected to " + gauges.portstr) filename = '/sys/bus/platform/devices/applesmc.768/temp2_input' def parseSensorsOutputLinux(output): return int(round(float(output) / 1000)) while(1): usage = psutil.cpu_percent(interval=sampleTime) gauges.write(USAGE_CHAR) gauges.write(chr(int(usage))) #write the first byte #print("Wrote usage: " + str(int(usage))) sensorFile = open(filename) temp = parseSensorsOutputLinux(sensorFile.read()) gauges.write(TEMP_CHAR) gauges.write(chr(temp)) #print("Wrote temp: " + str(temp)) Any thoughts? Thanks. EDIT: Here is the revised code, using Python-BlueZ instead of PySerial: import psutil import serial import string import time import bluetooth sampleTime = 1 numSamples = 5 lastTemp = 0 TEMP_CHAR = 't' USAGE_CHAR = 'u' SENSOR_NAME = 'TC0D' #gauges = serial.Serial() #gauges.port = '/dev/rfcomm0' #gauges.baudrate = 9600 #gauges.parity = 'N' #gauges.writeTimeout = 0 #gauges.open() gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) gaugeSocket.connect(('00:06:66:42:22:96', 1)) filename = '/sys/bus/platform/devices/applesmc.768/temp2_input' def parseSensorsOutputLinux(output): return int(round(float(output) / 1000)) while(1): usage = psutil.cpu_percent(interval=sampleTime) #gauges.write(USAGE_CHAR) gaugeSocket.send(USAGE_CHAR) #gauges.write(chr(int(usage))) #write the first byte gaugeSocket.send(chr(int(usage))) #print("Wrote usage: " + str(int(usage))) sensorFile = open(filename) temp = parseSensorsOutputLinux(sensorFile.read()) #gauges.write(TEMP_CHAR) gaugeSocket.send(TEMP_CHAR) #gauges.write(chr(temp)) gaugeSocket.send(chr(temp)) #print("Wrote temp: " + str(temp)) It seems either Ubuntu must be closing /dev/rfcomm0 after a certain time or my Bluetooth receiver is messing things up. Even when the BluetoothError arises, the "connected" light on the receiver stays illuminated, and it is not until I power-cycle to receiver that I can reconnect. I'm not sure how to approach this problem. It's odd that the connection would work fine for a few minutes (seemingly a random amount of time) and then seize up. In case it helps, the Bluetooth receiver is a BlueSmirf Silver from Sparkfun. Do I need to be trying to maintain the connection from the receiver end or something?

    Read the article

  • The Excel Column Name assigment problem

    - by Peter Larsson
    Here is a generic algorithm to get the Excel column name according to it's position. By changing the @Base parameter, you can do this for any sequence according to same style as Excel. DECLARE @Value INT = 8839,         @Base TINYINT = 26   ;WITH cteSequence(Value, Delta, Quote, Base, Chr) AS (     SELECT  CAST(@Value AS INT) AS Value,             CAST(1 AS INT) AS Delta,             CAST(@Base AS INT) AS Quote,             CAST(@Base AS INT) AS Base,             CHAR(65 +(@Value - 1) % @Base) AS Chr       UNION ALL       SELECT  Value AS Value,             Quote AS Delta,             26 * Quote AS Quote,             Base AS Base,             CHAR(65 +((Value - Delta)/ Quote - 1) % Base) AS Chr     FROM    cteSequence     WHERE   CHAR(65 +((Value - Delta)/ Quote - 1) % Base) <> '@' ) SELECT  CAST(Msg AS VARCHAR(MAX)) FROM    (             SELECT        '' + Chr             FROM        cteSequence             ORDER BY    Delta DESC             FOR XML        PATH('')         ) AS x(Msg)

    Read the article

  • Why is this statement treated as a string instead of its result?

    - by reve_etrange
    I am trying to perform some composition-based filtering on a large collection of strings (protein sequences). I wrote a group of three subroutines in order to take care of it, but I'm running into trouble in two ways - one minor, one major. The minor trouble is that when I use List::MoreUtils 'pairwise' I get warnings about using $a and $b only once and them being uninitialized. But I believe I'm calling this method properly (based on CPAN's entry for it and some examples from the web). The major trouble is an error "Can't use string ("17/32") as HASH ref while "strict refs" in use..." It seems like this can only happen if the foreach loop in &comp is giving the hash values as a string instead of evaluating the division operation. I'm sure I've made a rookie mistake, but can't find the answer on the web. The first time I even looked at perl code was last Wednesday... use List::Util; use List::MoreUtils; my @alphabet = ( 'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V' ); my $gapchr = '-'; # Takes a sequence and returns letter = occurrence count pairs as hash. sub getcounts { my %counts = (); foreach my $chr (@alphabet) { $counts{$chr} = ( $[0] =~ tr/$chr/$chr/ ); } $counts{'gap'} = ( $[0] =~ tr/$gapchr/$gapchr/ ); return %counts; } # Takes a sequence and returns letter = fractional composition pairs as a hash. sub comp { my %comp = getcounts( $[0] ); foreach my $chr (@alphabet) { $comp{$chr} = $comp{$chr} / ( length( $[0] ) - $comp{'gap'} ); } return %comp; } # Takes two sequences and returns a measure of the composition difference between them, as a scalar. # Originally all on one line but it was unreadable. sub dcomp { my @dcomp = pairwise { $a - $b } @{ values( %{ comp( $[0] ) } ) }, @{ values( %{ comp( $[1] ) } ) }; @dcomp = apply { $_ ** 2 } @dcomp; my $dcomp = sqrt( sum( 0, @dcomp ) ) / 20; return $dcomp; } Much appreciation for any answers or advice!

    Read the article

  • Benchmarking hosting providers IO with Bonnie

    - by Derek Organ
    Ok, because of a bunch of projects I'm working on I've access to dedicated Servers on a 3 hosting providers. As an experiment and for educational purposes I decided to see if I could benchmark how good the IO is with each. Bit of research lead me to Bonnie++ So I installed it on the server and ran this simple command /usr/sbin/bonnie -d /tmp/foo The 3 machines in different hosting providers are all dedicated machines, one is a VPS, other two are on some cloud platform e.g. VMWare / Xen using some kind of clustered SAN for storage This might be a naive thing to do but here are the results I found. HOST A Version 1.03c ------Sequential Output------ --Sequential Input- --Random- -Per Chr- --Block-- -Rewrite- -Per Chr- --Block-- --Seeks-- Machine Size K/sec %CP K/sec %CP K/sec %CP K/sec %CP K/sec %CP /sec %CP xxxxxxxxxxxxxxxx 1G 45081 88 56244 14 19167 4 20965 40 67110 6 67.2 0 ------Sequential Create------ --------Random Create-------- -Create-- --Read--- -Delete-- -Create-- --Read--- -Delete-- files /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP 16 15264 28 +++++ +++ +++++ +++ +++++ +++ +++++ +++ +++++ +++ xxxxxxxx,1G,45081,88,56244,14,19167,4,20965,40,67110,6,67.2,0,16,15264,28,+++++,+++,+++++,+++,+++++,+++,+++++,+++,+++++,+++ HOST B Version 1.03d ------Sequential Output------ --Sequential Input- --Random- -Per Chr- --Block-- -Rewrite- -Per Chr- --Block-- --Seeks-- Machine Size K/sec %CP K/sec %CP K/sec %CP K/sec %CP K/sec %CP /sec %CP xxxxxxxxxxxx 4G 43070 91 64510 15 19092 0 29276 47 39169 0 448.2 0 ------Sequential Create------ --------Random Create-------- -Create-- --Read--- -Delete-- -Create-- --Read--- -Delete-- files /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP 16 24799 52 +++++ +++ +++++ +++ 25443 54 +++++ +++ +++++ +++ xxxxxxx,4G,43070,91,64510,15,19092,0,29276,47,39169,0,448.2,0,16,24799,52,+++++,+++,+++++,+++,25443,54,+++++,+++,+++++,+++ HOST C Version 1.03c ------Sequential Output------ --Sequential Input- --Random- -Per Chr- --Block-- -Rewrite- -Per Chr- --Block-- --Seeks-- Machine Size K/sec %CP K/sec %CP K/sec %CP K/sec %CP K/sec %CP /sec %CP xxxxxxxxxxxxx 1536M 15598 22 85698 13 258969 20 16194 22 723655 21 +++++ +++ ------Sequential Create------ --------Random Create-------- -Create-- --Read--- -Delete-- -Create-- --Read--- -Delete-- files /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP 16 14142 22 +++++ +++ 18621 22 13544 22 +++++ +++ 17363 21 xxxxxxxx,1536M,15598,22,85698,13,258969,20,16194,22,723655,21,+++++,+++,16,14142,22,+++++,+++,18621,22,13544,22,+++++,+++,17363,21 Ok, so first off what is the best way to read the figures and are there any issues with really comparing these numbers? Is this in any way a true representation of IO Speed? If not is there any way for me to test that? Note: these 3 machines are using either Ubuntu or Debian (I presume that doesn't really matter)

    Read the article

1 2 3 4 5 6 7 8  | Next Page >