Search Results

Search found 1472 results on 59 pages for 'harry len'.

Page 21/59 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • Python performance improvement request for winkler

    - by Martlark
    I'm a python n00b and I'd like some suggestions on how to improve the algorithm to improve the performance of this method to compute the Jaro-Winkler distance of two names. def winklerCompareP(str1, str2): """Return approximate string comparator measure (between 0.0 and 1.0) USAGE: score = winkler(str1, str2) ARGUMENTS: str1 The first string str2 The second string DESCRIPTION: As described in 'An Application of the Fellegi-Sunter Model of Record Linkage to the 1990 U.S. Decennial Census' by William E. Winkler and Yves Thibaudeau. Based on the 'jaro' string comparator, but modifies it according to whether the first few characters are the same or not. """ # Quick check if the strings are the same - - - - - - - - - - - - - - - - - - # jaro_winkler_marker_char = chr(1) if (str1 == str2): return 1.0 len1 = len(str1) len2 = len(str2) halflen = max(len1,len2) / 2 - 1 ass1 = '' # Characters assigned in str1 ass2 = '' # Characters assigned in str2 #ass1 = '' #ass2 = '' workstr1 = str1 workstr2 = str2 common1 = 0 # Number of common characters common2 = 0 #print "'len1', str1[i], start, end, index, ass1, workstr2, common1" # Analyse the first string - - - - - - - - - - - - - - - - - - - - - - - - - # for i in range(len1): start = max(0,i-halflen) end = min(i+halflen+1,len2) index = workstr2.find(str1[i],start,end) #print 'len1', str1[i], start, end, index, ass1, workstr2, common1 if (index > -1): # Found common character common1 += 1 #ass1 += str1[i] ass1 = ass1 + str1[i] workstr2 = workstr2[:index]+jaro_winkler_marker_char+workstr2[index+1:] #print "str1 analyse result", ass1, common1 #print "str1 analyse result", ass1, common1 # Analyse the second string - - - - - - - - - - - - - - - - - - - - - - - - - # for i in range(len2): start = max(0,i-halflen) end = min(i+halflen+1,len1) index = workstr1.find(str2[i],start,end) #print 'len2', str2[i], start, end, index, ass1, workstr1, common2 if (index > -1): # Found common character common2 += 1 #ass2 += str2[i] ass2 = ass2 + str2[i] workstr1 = workstr1[:index]+jaro_winkler_marker_char+workstr1[index+1:] if (common1 != common2): print('Winkler: Wrong common values for strings "%s" and "%s"' % \ (str1, str2) + ', common1: %i, common2: %i' % (common1, common2) + \ ', common should be the same.') common1 = float(common1+common2) / 2.0 ##### This is just a fix ##### if (common1 == 0): return 0.0 # Compute number of transpositions - - - - - - - - - - - - - - - - - - - - - # transposition = 0 for i in range(len(ass1)): if (ass1[i] != ass2[i]): transposition += 1 transposition = transposition / 2.0 # Now compute how many characters are common at beginning - - - - - - - - - - # minlen = min(len1,len2) for same in range(minlen+1): if (str1[:same] != str2[:same]): break same -= 1 if (same > 4): same = 4 common1 = float(common1) w = 1./3.*(common1 / float(len1) + common1 / float(len2) + (common1-transposition) / common1) wn = w + same*0.1 * (1.0 - w) return wn

    Read the article

  • Retrieving dll version info via Win32 - VerQueryValue(...) crashes under Win7 x64

    - by user256890
    The respected open source .NET wrapper implementation (SharpBITS) of Windows BITS services fails identifying the underlying BITS version under Win7 x64. Here is the source code that fails. NativeMethods are native Win32 calls wrapped by .NET methods and decorated via DllImport attribute. private static BitsVersion GetBitsVersion() { try { string fileName = Path.Combine( System.Environment.SystemDirectory, "qmgr.dll"); int handle = 0; int size = NativeMethods.GetFileVersionInfoSize(fileName, out handle); if (size == 0) return BitsVersion.Bits0_0; byte[] buffer = new byte[size]; if (!NativeMethods.GetFileVersionInfo(fileName, handle, size, buffer)) { return BitsVersion.Bits0_0; } IntPtr subBlock = IntPtr.Zero; uint len = 0; if (!NativeMethods.VerQueryValue(buffer, @"\VarFileInfo\Translation", out subBlock, out len)) { return BitsVersion.Bits0_0; } int block1 = Marshal.ReadInt16(subBlock); int block2 = Marshal.ReadInt16((IntPtr)((int)subBlock + 2 )); string spv = string.Format( @"\StringFileInfo\{0:X4}{1:X4}\ProductVersion", block1, block2); string versionInfo; if (!NativeMethods.VerQueryValue(buffer, spv, out versionInfo, out len)) { return BitsVersion.Bits0_0; } ... The implementation follows the MSDN instructions by the letter. Still during the second VerQueryValue(...) call, the application crashes and kills the debug session without hesitation. Just a little more debug info right before the crash: spv = "\StringFileInfo\040904B0\ProductVersion" buffer = byte[1900] - full with binary data block1 = 1033 block2 = 1200 I looked at the targeted "C:\Windows\System32\qmgr.dll" file (The implementation of BITS) via Windows. It says that the Product Version is 7.5.7600.16385. Instead of crashing, this value should return in the verionInfo string. Any advice?

    Read the article

  • Parse and read data frame in C?

    - by user253656
    I am writing a program that reads the data from the serial port on Linux. The data are sent by another device with the following frame format: |start | Command | Data | CRC | End | |0x02 | 0x41 | (0-127 octets) | | 0x03| ---------------------------------------------------- The Data field contains 127 octets as shown and octet 1,2 contains one type of data; octet 3,4 contains another data. I need to get these data I know how to write and read data to and from a serial port in Linux, but it is just to write and read a simple string (like "ABD") My issue is that I do not know how to parse the data frame formatted as above so that I can: get the data in octet 1,2 in the Data field get the data in octet 3,4 in the Data field get the value in CRC field to check the consistency of the data Here the sample snip code that read and write a simple string from and to a serial port in Linux: int writeport(int fd, char *chars) { int len = strlen(chars); chars[len] = 0x0d; // stick a <CR> after the command chars[len+1] = 0x00; // terminate the string properly int n = write(fd, chars, strlen(chars)); if (n < 0) { fputs("write failed!\n", stderr); return 0; } return 1; } int readport(int fd, char *result) { int iIn = read(fd, result, 254); result[iIn-1] = 0x00; if (iIn < 0) { if (errno == EAGAIN) { printf("SERIAL EAGAIN ERROR\n"); return 0; } else { printf("SERIAL read error %d %s\n", errno, strerror(errno)); return 0; } } return 1; } Does anyone please have some ideas? Thanks all.

    Read the article

  • PHP Encrypt/Decrypt with TripleDes, PKCS7, and ECB

    - by Brandon Green
    I've got my encryption function working properly however I cannot figure out how to get the decrypt function to give proper output. Here is my encrypt function: function Encrypt($data, $secret) { //Generate a key from a hash $key = md5(utf8_encode($secret), true); //Take first 8 bytes of $key and append them to the end of $key. $key .= substr($key, 0, 8); //Pad for PKCS7 $blockSize = mcrypt_get_block_size('tripledes', 'ecb'); $len = strlen($data); $pad = $blockSize - ($len % $blockSize); $data .= str_repeat(chr($pad), $pad); //Encrypt data $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb'); return base64_encode($encData); } Here is my decrypt function: function Decrypt($data, $secret) { $text = base64_decode($data); $data = mcrypt_decrypt('tripledes', $secret, $text, 'ecb'); $block = mcrypt_get_block_size('tripledes', 'ecb'); $pad = ord($data[($len = strlen($data)) - 1]); return substr($data, 0, strlen($data) - $pad); } Right now I am using a key of test and I'm trying to encrypt 1234567. I get the base64 output from encryption I'm looking for, but when I go to decrypt I get a blank response. I'm not very well versed in encryption/decryption so any help is much appreciated!!

    Read the article

  • Getting size of a specific byte array from an array of pointers to bytes

    - by Pat James
    In the following example c code, used in an Arduino project, I am looking for the ability to get the size of a specific byte array within an array of pointers to bytes, for example void setup() { Serial.begin(9600); // for debugging byte zero[] = {8, 169, 8, 128, 2,171,145,155,141,177,187,187,2,152,2,8,134,199}; byte one[] = {8, 179, 138, 138, 177 ,2,146, 8, 134, 8, 194,2,1,14,199,7, 145, 8,131, 8,158,8,187,187,191}; byte two[] = {29,7,1,8, 169, 8, 128, 2,171,145,155,141,177,187,187,2,152,2,8,134,199, 2, 2, 8, 179, 138, 138, 177 ,2,146, 8, 134, 8, 194,2,1,14,199,7, 145, 8,131, 8,158,8,187,187,191}; byte* numbers[3] = {zero, one, two }; function(numbers[1], sizeof(numbers[1])/sizeof(byte)); //doesn't work as desired, always passes 2 as the length function(numbers[1], 25); //this works } void loop() { } void function( byte arr[], int len ) { Serial.print("length: "); Serial.println(len); for (int i=0; i<len; i++){ Serial.print("array element "); Serial.print(i); Serial.print(" has value "); Serial.println((int)arr[i]); } } In this code, I understand that sizeof(numbers1)/sizeof(byte)) doesn't work because numbers1 is a pointer and not the byte array value. Is there a way in this example that I can, at runtime, get at the length of a specific (runtime-determined) byte array within an array of pointers to bytes? Understand that I am limited to developing in c (or assembly) for an Arduino environment. Also open to other suggestions rather than the array of pointers to bytes. The overall objective is to organize lists of bytes which can be retrieved, with length, at runtime.

    Read the article

  • Django Querysets -- need a less expensive way to do this..

    - by rh0dium
    Hi all, I have a problem with some code and I believe it is because of the expense of the queryset. I am looking for a much less expensive (in terms of time) way to to this.. log.info("Getting Users") employees = Employee.objects.filter(is_active = True) log.info("Have Users") if opt.supervisor: if opt.hierarchical: people = getSubs(employees, " ".join(args)) else: people = employees.filter(supervisor__name__icontains = " ".join(args)) else: log.info("Filtering Users") people = employees.filter(name__icontains = " ".join(args)) | \ employees.filter(unix_accounts__username__icontains = " ".join(args)) log.info("Filtered Users") log.info("Processing data") np = [] for person in people: unix, p4, bugz = "No", "No", "No" if len(person.unix_accounts.all()): unix = "Yes" if len(person.perforce_accounts.all()): p4 = "Yes" if len(person.bugzilla_accounts.all()): bugz = "Yes" if person.cell_phone != "": exphone = fixphone(person.cell_phone) elif person.other_phone != "": exphone = fixphone(person.other_phone) else: exphone = "" np.append({ 'name':person.name, 'office_phone': fixphone(person.office_phone), 'position': person.position, 'location': person.location.description, 'email': person.email, 'functional_area': person.functional_area.name, 'department': person.department.name, 'supervisor': person.supervisor.name, 'unix': unix, 'perforce': p4, 'bugzilla':bugz, 'cell_phone': fixphone(exphone), 'fax': fixphone(person.fax), 'last_update': person.last_update.ctime() }) log.info("Have data") Now this results in a log which looks like this.. 19:00:55 INFO phone phone Getting Users 19:00:57 INFO phone phone Have Users 19:00:57 INFO phone phone Processing data 19:01:30 INFO phone phone Have data As you can see it's taking over 30 seconds to simply iterate over the data. That is way too expensive. Can someone clue me into a more efficient way to do this. I thought that if I did the first filter that would make things easier but seems to have no effect. I'm at a loss on this one. Thanks To be clear this is about 1500 employees -- Not too many!!

    Read the article

  • How can i zip files in Java and not include files paths

    - by Ignacio
    For example, i want to zip a file stored in /Users/me/Desktop/image.jpg I maded this method: public static Boolean generateZipFile(ArrayList<String> sourcesFilenames, String destinationDir, String zipFilename){ // Create a buffer for reading the files byte[] buf = new byte[1024]; try { // VER SI HAY QUE CREAR EL ROOT PATH boolean result = (new File(destinationDir)).mkdirs(); String zipFullFilename = destinationDir + "/" + zipFilename ; System.out.println(result); // Create the ZIP file ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFullFilename)); // Compress the files for (String filename: sourcesFilenames) { FileInputStream in = new FileInputStream(filename); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(filename)); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Complete the ZIP file out.close(); return true; } catch (IOException e) { return false; } } But when i extract the file, the unzipped files have the full path. I don't want the full path of each file in the zip i only want the filename. How can i made this?

    Read the article

  • Call Python From PHP And Get Return Code

    - by seaboy
    Hello everyone, I am calling a python script from PHP. The python program has to return some value according to the arguments passed to it. Here is a sample python program, which will give you a basic idea of what i am doing currently: #!/usr/bin/python import sys #get the arguments passed argList = sys.argv #Not enough arguments. Exit with a value of 1. if len(argList) < 3: #Return with a value of 1. sys.exit(1) arg1 = argList[1] arg2 = argList[2] #Check arguments. Exit with the appropriate value. if len(arg1) > 255: #Exit with a value of 4. sys.exit(4) if len(arg2) < 2: #Exit with a value of 8. sys.exit(8) #Do further coding using the arguments------ #If program works successfully, exit with a value of 0 As you can see from the above code, my basic aim is for the python program to return some values (0,1,4,8 etc) depending on the arguments. And then the calling PHP program to access these returned values and do the appropriate operation. Currently i have used "sys.exit(n)", for that purpose. Am i right in using sys.exit, or do I need to use something else? And also what method exists in PHP so that I can access the return code from python? Sorry for the long question, but hopefully it will help in you understanding my dilemma Thanks a ton

    Read the article

  • Counting entries in a list of dictionaries: for loop vs. list comprehension with map(itemgetter)

    - by Dennis Williamson
    In a Python program I'm writing I've compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach? Here is a greatly simplified and shortened data structure: list = [ {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'}, {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'}, {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'}, {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'}, {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'} ] Here is the for loop version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True key1 = key2 = 0 for dictionary in list: if dictionary["key1"]: key1 += 1 if dictionary["key2"]: key2 += 1 print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above: Counts: key1: 3, subset key2: 2 Here is the other, perhaps more Pythonic, version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True from operator import itemgetter KEY1 = 0 KEY2 = 1 getentries = itemgetter("key1", "key2") entries = map(getentries, list) key1 = len([x for x in entries if x[KEY1]]) key2 = len([x for x in entries if x[KEY1] and x[KEY2]]) print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above (same as before): Counts: key1: 3, subset key2: 2 I'm a tiny bit surprised these take the same amount of time. I wonder if there's something faster. I'm sure I'm overlooking something simple. One alternative I've considered is loading the data into a database and doing SQL queries, but the data doesn't need to persist and I'd have to profile the overhead of the data transfer, etc., and a database may not always be available. I have no control over the original form of the data. The code above is not going for style points.

    Read the article

  • JSP Upload File Java.lang.NullPointer

    - by newbie123
    I want to develope upload and download file from server. Upload.html <form action="/UploadFile/UploadFile" method="POST" enctype="multipart/form-data">Select a file: <input type="submit" name="button" /> <input type="file" name="first"></form> UploadFile.servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String temp = request.getParameter("first"); System.out.println(temp); File origFile = new File(temp); FileOutputStream out = new FileOutputStream(request.getContextPath() + "pdtImages/" + "FirstFile"); InputStream ins = new FileInputStream(origFile); try { System.out.println(request.getContextPath()); byte[] buf = new byte[1024]; int len; while ((len = ins.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } When I submitted the file I got null pointer error message. I not very familiar with jsp can anybody help me? I want to store the file to the server directory.

    Read the article

  • How to implement a simple queue properly?

    - by Stephen Hsu
    The current Go library doesn't provide the queue container. To implement a simple queue, I use circle array as the underlying data structure. It follows algorithms mentioned in TAOCP: Insert Y into queue X: X[R]<-Y; R<-(R+1)%M; if R=F then OVERFLOW. Delete Y from queue X: if F=R then UNDERFLOW; Y<-X[F]; F<-(F+1) % M. F: Front, R: Rear, M: Array length. Following is the code: package main import ( "fmt" ) type Queue struct { len int head, tail int q []int } func New(n int) *Queue { return &Queue{n, 0, 0, make([]int, n)} } func (p *Queue) Enqueue(x int) bool { p.q[p.tail] = x p.tail = (p.tail + 1) % p.len return p.head != p.tail } func (p *Queue) Dequeue() (int, bool) { if p.head == p.tail { return 0, false } x := p.q[p.head] p.head = (p.head + 1) % p.len return x, true } func main() { q := New(10) for i := 1; i < 13; i++ { fmt.Println(i, q.Enqueue(i)) } fmt.Println() for i := 1; i < 13; i++ { fmt.Println(q.Dequeue()) } } But the output is obviously wrong: 1 true 2 true 3 true 4 true 5 true 6 true 7 true 8 true 9 true 10 false 11 true 12 true 11 true 12 true 0 false 0 false 0 false 0 false 0 false 0 false 0 false 0 false 0 false 0 false I think I need one more field to make the code work properly. What do you suggest?

    Read the article

  • Can an application affect TCP retransmits

    - by sipwiz
    I'm troubleshooting some communications issues and in the network traces I am occasionally coming across TCP sequence errors. One example I've got is: Server to Client: Seq=3174, Len=50 Client to Server: Ack=3224 Server to Client: Seq=3224, Len=50 Client to Server: Ack=3224 Server to Client: Seq=3274, Len=10 Client to Server: Ack=3224, SLE=3274, SRE=3284 Packets 4 & 5 are recorded in the trace (which is from a router in between the client and server) at almost exactly the same time so they most likely crossed in transit. The TCP session has got out of sync with the client missing the last two transmissions from the server. Those two packets should have been retransmitted but they weren't, the next log in the trace is a RST packet from the Client 24 seconds after packet 6. My question is related to what could be responsible for the failure to retransmit the server data from packets 3 & 5? I would assume that the retransmit would be at the operating system level but is there anyway the application could influence it and stop it being sent? A thread blocking or put to sleep or something like that?

    Read the article

  • Printing a DataTable to textbox/textfile in .NET

    - by neodymium
    Is there a predefined or "easy" method of writing a datatable to a text file or TextBox Control (With monospace font) such as DataTable.Print(): Column1| Column2| --------|--------| v1| v2| v3| v4| v5| v6| Edit Here's an initial version (vb.net) - in case anyone is interested or wants to build their own: Public Function BuildTable(ByVal dt As DataTable) As String Dim result As New StringBuilder Dim widths As New List(Of Integer) Const ColumnSeparator As Char = "|"c Const HeadingUnderline As Char = "-"c ' determine width of each column based on widest of either column heading or values in that column For Each col As DataColumn In dt.Columns Dim colWidth As Integer = Integer.MinValue For Each row As DataRow In dt.Rows Dim len As Integer = row(col.ColumnName).ToString.Length If len > colWidth Then colWidth = len End If Next widths.Add(CInt(IIf(colWidth < col.ColumnName.Length, col.ColumnName.Length + 1, colWidth + 1))) Next ' write column headers For Each col As DataColumn In dt.Columns result.Append(col.ColumnName.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() ' write heading underline For Each col As DataColumn In dt.Columns Dim horizontal As String = New String(HeadingUnderline, widths(col.Ordinal)) result.Append(horizontal.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() ' write each row For Each row As DataRow In dt.Rows For Each col As DataColumn In dt.Columns result.Append(row(col.ColumnName).ToString.PadLeft(widths(col.Ordinal))) result.Append(ColumnSeparator) Next result.AppendLine() Next Return result.ToString() End Function

    Read the article

  • Dealing with array of IntPtr

    - by Padu Merloti
    I think I'm close and I bet the solution is something stupid. I have a C++ native DLL where I define the following function: DllExport bool __stdcall Open(const char* filePath, int *numFrames, void** data); { //creates the list of arrays here... don't worry, lifetime is managed somewhere else //foreach item of the list: { BYTE* pByte = GetArray(i); //here's where my problem lives *(data + i * sizeofarray) = pByte; } *numFrames = total number of items in the list return true; } Basically, given a file path, this function creates a list of byte arrays (BYTE*) and should return a list of pointers via the data param. Each pointing to a different byte array. I want to pass an array of IntPtr from C# and be able to marshal each individual array in order. Here's the code I'm using: [DllImport("mydll.dll",EntryPoint = "Open")] private static extern bool MyOpen( string filePath, out int numFrames, out IntPtr[] ptr); internal static bool Open( string filePath, out int numFrames, out Bitmap[] images) { var ptrList = new IntPtr[512]; MyOpen(filePath, out numFrames, out ptrList); images = new Bitmap[numFrames]; var len = 100; //for sake of simplicity for (int i=0; i<numFrames;i++) { var buffer = new byte[len]; Marshal.Copy(ptrList[i], buffer, 0, len); images[i] = CreateBitmapFromBuffer(buffer, height, width); } return true; } Problem is in my C++ code. When I assign *(data + i * sizeofarray) = pByte; it corrupts the array of pointers... what am I doing wrong?

    Read the article

  • Exercise for exam about comparing string on file

    - by Telmo Vaz
    I'm trying to do this exercise for my exam tomorrow. I need to compare a string of my own input and see if that string is appearing on the file. This needs to be done directly on the file, so I cannot extract the string to my program and compare them "indirectly". I found this way but I'm not getting it right, and I don't know why. The algorithm sounds good to me. Any help, please? I really need to focus on this one. Thanks in advance, guys. #include<stdio.h> void comp(); int main(void) { comp(); return 0; } void comp() { FILE *file = fopen("e1.txt", "r+"); if(!file) { printf("Not possible to open the file"); return; } char src[50], ch; short i, len; fprintf(stdout, "What are you looking for? \nwrite: "); fgets(src, 200, stdin); len = strlen(src); while((ch = fgetc(file)) != EOF) { i = 0; while(ch == src[i]) { if(i <= len) { printf("%c - %c", ch, src[i]); fseek(file, 0, SEEK_CUR + 1); i++; } else break; } } }

    Read the article

  • Trying to output a list using class

    - by captain morgan
    Am trying to get the moving average of a price..but i keep getting an attribute error in my Moving_Average class. ('Moving_Average' object has no attribute 'days'). Here is what I have: class Moving_Average: def calculation(self, alist:list,days:int): m = self.days prices = alist[1::2] average = [0]* len(prices) signal = ['']* len(prices) for m in range(0,len(prices)-days+1): average[m+2] = sum(prices[m:m+days])/days if prices[m+2] < average[m+2]: signal[m+2]='SELL' elif prices[m+2] > average[m+2] and prices[m+1] < average[m+1]: signal[m+2]='BUY' else: signal[m+2] ='' return average,signal def print_report(symbol:str,strategy:str): print('SYMBOL: ', symbol) print('STRATEGY: ', strategy) print('Date Closing Strategy Signal') def user(): strategy = ''' Which of the following strategy would you like to use? * Simple Moving Average [S] * Directional Indicator[D] Please enter your choice: ''' if signal_strategy in 'Ss': days = input('Please enter the number of days for the average') days = int(days) strategy = 'Simple Moving Average {}-days'.format(str(days)) m = Moving_Average() ma = m.calculation(gg, days) print(ma) gg is an list that contains date and prices. [2013-10-01,60,2013-10-02,60] The output is supposed to look like: Date Price Average Signal 2013-10-01 60.0 2013-10-02 60.0 60.00 BUY

    Read the article

  • Array indexOf implementation for Internet Explorer

    - by Daemon
    There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far. Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now: // indexOf support for IE (from MDC) if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var i = [1,2,3,4]; for (j in i) { alert(i[j]); } I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code. What can be done to avoid this?

    Read the article

  • pyOpenSSL and the WantReadError

    - by directedition
    I have a socket server that I am trying to move over to SSL on python 2.5, but I've run into a snag with pyOpenSSL. I can't find any good tutorials on using it, so I'm operating largely on guesses. Here is how my server sets up the socket: ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey_file ("mykey.pem") ctx.use_certificate_file("mycert.pem") sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) addr = ('', int(8081)) sock.bind(addr) sock.listen(5) Here is how it accepts clients: sock.setblocking(0) while True: if len(select([sock], [], [], 0.25)[0]): client_sock, client_addr = sock.accept() client = ClientGen(client_sock) And here is how it sends/receives from the connected sockets: while True: (r, w, e) = select.select([sock], [sock], [], 0.25) if len(r): bytes = sock.recv(1024) if len(w): n_bytes = sock.send(self.message) It's compacted, but you get the general idea. The problem is, once the send/receive loop starts, it dies right away, before anything has been sent or received (that I can see anyway): Traceback (most recent call last): File "ClientGen.py", line 50, in networkLoop n_bytes = sock.send(self.message WantReadError The manual's description of the 'WantReadError' is very vague, saying it can come from just about anywhere. What am I doing wrong?

    Read the article

  • How to find which delimiter was used during string split (VB.NET)

    - by typoknig
    Hi all, lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question? Dim linePunctuation as Integer = 0 Dim myString As String = "some text. with punctuation! in it?" For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1 Next For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1 Next For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1 Next Dim delimiters(3) As Char delimiters(0) = "." delimiters(1) = "!" delimiters(2) = "?" currentLineSplit = myString.Split(delimiters) Dim sentenceArray(linePunctuation) As String Dim count As Integer = 0 While linePunctuation > 0 sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.' count += 1 linePunctuation -= 1 End While

    Read the article

  • Looking for Go equivalent of scanf.

    - by Stephen Hsu
    I'm looking for the Go equivalent of scanf(). I tried with following code: 1 package main 2 3 import ( 4 "scanner" 5 "os" 6 "fmt" 7 ) 8 9 func main() { 10 var s scanner.Scanner 11 s.Init(os.Stdin) 12 s.Mode = scanner.ScanInts 13 tok := s.Scan() 14 for tok != scanner.EOF { 15 fmt.Printf("%d ", tok) 16 tok = s.Scan() 17 } 18 fmt.Println() 19 } I run it with input from a text with a line of integers. But it always output -3 -3 ... And how to scan a line composed of a string and some integers? Changing the mode whenever encounter a new data type? The Package documentation: Package scanner A general-purpose scanner for UTF-8 encoded text. But it seems that the scanner is not for general use. Updated code: func main() { n := scanf() fmt.Println(n) fmt.Println(len(n)) } func scanf() []int { nums := new(vector.IntVector) reader := bufio.NewReader(os.Stdin) str, err := reader.ReadString('\n') for err != os.EOF { fields := strings.Fields(str) for _, f := range fields { i, _ := strconv.Atoi(f) nums.Push(i) } str, err = reader.ReadString('\n') } r := make([]int, nums.Len()) for i := 0; i < nums.Len(); i++ { r[i] = nums.At(i) } return r }

    Read the article

  • Go and a bad prime number algorithm

    - by anonymous
    I wrote this prime number sieving algorithm and it doesn't run properly. I can't find the error in the algorithm itself. Could someone help me? This is what it's supposed to print: [2 3 5 7 11 13 17 19 23 29] Versus what it actually prints: [3 5 7 11 13 17 19 23 25 29] . package main import "fmt" func main() { var primes = sieve(makeNumbers(29)) fmt.Printf("%d\n", primes); } func makeNumbers(n int) []int { var numbers = make([]int, n - 1) for i := 0; i < len(numbers); i++ { numbers[i] = i + 2 } return numbers } func sieve(numbers []int) []int { var numCopy = numbers var max = numbers[len(numbers)-1] var sievedNumbers = make([]int, 0) for i := 0; numCopy[i]*numCopy[i] <= max; i++ { for j := i; j < len(numCopy); j++ { if numCopy[j] % numCopy[i] != 0 || j == i { sievedNumbers = append(sievedNumbers, numCopy[j]) } } numCopy = sievedNumbers sievedNumbers = make([]int, 0) } return numCopy }

    Read the article

  • sendto is returning ENOBUF

    - by user338159
    Hi, I am currently running an old system on Tru64 which involves lots of UDP sockets using the sendto() function. The sockets are used in our code to send messages to/from various processes and then eventually on to a thick client app that is connected remotely. Occasionally the socket to the thick client gets stuck, this can cause some of these messages to get built up. My question is how can I determine the current buffer size, and how do I determine the maximum message buffer. The code below gives a snippet of how I set up the port and use the sendto function. /* need to adjust the maximum size we can send on this / / as it needs to be able to cope with the biggest / / messages we send / lenlen = sizeof(len) ; / allow double for when the system is under load */ len = 2 * C_MAX_MESSAGE_DATA_SIZE ; lpos_setsockopt(FATAL, msg_socket,SOL_SOCKET, SO_SNDBUF, &len, lenlen, &error_no) ; result = sendto( msg_socket, (char *)message, (int)message_len, flags, dest_addr, addrlen); Note. We have ported this application to Linux and the problem does not seem to appear there. Any help would be greatly appreciated. Regards

    Read the article

  • Array indexOf implentation for Internet Explorer

    - by Daemon
    There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far. Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now: // indexOf support for IE (from MDC) if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var i = [1,2,3,4]; for (j in i) { alert(i[j]); } I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code. What can be done to avoid this?

    Read the article

  • streaming xml pretty printer in C/C++ using expat or libxml2?

    - by Mark Zeren
    I have a library that outputs xml without whitespace all on one line. In some cases I'd like to pretty print that output. I'm looking for a BSD-ish licensed C/C++ library or sample code that will take a raw xml byte stream and pretty print it. Here's some pseudo code showing one way that I might use this functionality: void my_write(const char* buf, int len); PrettyPrinter pp(bind(&my_write)); while (...) { // ... get some more xml ... const char* buf = xmlSource.get_buf(); int len = xmlSource.get_buf_len(); int written = pp.write(buf, len); // calls my_write with pretty printed xml // ... error handling, maybe call write again, etc. ... } I'd like to avoid instantiating a DOM representation. I already have dependencies on the expat and libxml2 shared libraries, and I'd rather not add any more shared library dependencies.

    Read the article

  • Getting a "for each" loop in Java to run in different order everytime

    - by R Stokes
    Hi, Basically my problem is that I'm trying to write a method that finds a random path in a graph of strings, which takes as it's parameters a start string, an integer length and a Vector of strings that will store the path. I'm attempting to do this by first adding the starting string to our blank vector, recursing through its neighbors until the vector's length (not including the start node) is the same as the integer length specified in the parameters. I've provided my code so far here: public Vector<String> findRandomPathFrom(String n, int len, Vector<String> randomPath){ randomPath.add(n); if (randomPath.size() == len + 1) return randomPath; for (String m : this.neighbours(n)){ if (!randomPath.contains(m) && findRandomPathFrom(m, len, randomPath) != null) return randomPath; } path.setSize(path.size() - 1); return null; } It seems to be working fine, returning a path with exactly the number of strings specified after the given start string. However, for any given starting string it generates the EXACT same path everytime, which kind of defeats the purpose of it being a random path generator. I'm guessing this problem is related to my "for each" loop, which loops through all the neighbouring strings of your current string. It seems to just be going with the first string in the neighbours vector every single time. Can anyone help me fix this problem so that it will choose a random neighbour instead of going in order? tl;dr - Any way of getting a "for each" loop in java to process a collection in a random order as oppoosed to start-to-finsih? Thanks in advance

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >