Search Results

Search found 2122 results on 85 pages for 'yoav str'.

Page 14/85 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • WCF streaming files

    - by Pinu
    I need to pass a memory stream to the WCF server , how do i need to add this data type in my data contract. I will eventually need to convert this to a memory stream and pass it on to my service layer. datacontact[DataMember] Stream str = null; public Stream File { get { return str; } set { str = value; } }

    Read the article

  • A better JavaScript version of addslashes and stripslashes?

    - by karlthorwald
    I am using these 2 functions: http://javascript.about.com/library/bladdslash.htm But JSLint complains 'Bad Escapement' on this line: str=str.replace(/\\0/g,'\0'); [Edit] I converted to 2 lines, and now the first line is the one that fails JLint: var rep = '\0'; str=str.replace(/\\0/g,rep); So it is the '\0' can you help? I could try something but I want to understand what is going on. [/Edit] Can you make a better version and explain? I would like a version that passes JSLint and still works.

    Read the article

  • How to prevent C6284 when using CString::Format?

    - by Sorin Sbarnea
    The following code is generating warning C6284 when compiled with /analyze on MSVC 2008 : object passed as parameter '%s' when string is required in call to function. CString strTmp, str; str = L"aaa.txt" strTmp.Format (L"File: %s", str); I'm looking for a nice solution for this that would not require static_cast

    Read the article

  • How to limit JTextArea max Rows and Coloums?

    - by Billbo bug
    I am using JTextArea in JScrollPane I want to limit the maximum number of lines possible and the maximum chars in each line. I need that the string will be exactly like on the screen, each line will end with '\n' (if there another line after it) and the user will be able to insert only X lines and Y chars in each line. I tried to limit the lines but i don't know exactly how many lines do i have because of the line wrapping, The line wrapping is starting new line visualy on the screen(because of the width of the JTextArea) but in the string of the component it is really the same line with no '\n' to indicate new line. I do not have an idea how to limit the max chars in each line while typing. There are 2 stages: The typing of the string- keep that the user will not be able to type more then X lines and Y chars in each line. (even if the line wrap only visualy or the user typed '/n') Insert the string to the DB- after cliking 'OK' convert the string that every line will end with "/n" even if the user did not typed it and the line was wrapped only visualy. There are few problems if i will count the chars in the line and insert '/n' in the end of the line, thats why i decided to do it in two stages. In the first stage ehile the user is typing i would rather only limit it visualy and force line wrpping or something similar. Only in the second stage when i save string i will add the '/n' even if the user did not typed it in the end of the lines! Does anyone have an idea? I know that i will have to use DocumentFilter OR StyledDocument. Here is sample code that limit only the lines to 3:(but not the chars in row to 19) private JTextArea textArea ; textArea = new JTextArea(3,19); textArea .setLineWrap(true); textArea .setDocument(new LimitedStyledDocument(3)); JScrollPane scrollPane = new JScrollPane(textArea public class LimitedStyledDocument extends DefaultStyledDocument /** Field maxCharacters */ int maxLines; public LimitedStyledDocument(int maxLines) { maxCharacters = maxLines; } public void insertString(int offs, String str, AttributeSet attribute) throws BadLocationException { Element root = this.getDefaultRootElement(); int lineCount = getLineCount(str); if (lineCount + root.getElementCount() <= maxLines){ super.insertString(offs, str, attribute); } else { Toolkit.getDefaultToolkit().beep(); } } /** * get Line Count * * @param str * @return the count of '\n' in the String */ private int getLineCount(String str){ String tempStr = new String(str); int index; int lineCount = 0; while (tempStr.length() > 0){ index = tempStr.indexOf("\n"); if(index != -1){ lineCount++; tempStr = tempStr.substring(index+1); } else{ break; } } return lineCount; } }

    Read the article

  • regexp uppercase to lowercase

    - by luccio
    Hi, is it possible to transform regexp pattern match to lowercase? var pattern:RegExp; var str:String = "HI guys"; pattern = /([A-Z]+)/g; str = str.replace(pattern, thisShouldBeLowerCase); Output should look like this: "hi guys" Thx

    Read the article

  • XSL-FO: Force Wrap on Table Entries

    - by Ace
    I'm having an issue where when I publish my modspecs to pdf (XSL-FO). My tables are having issues, where the content of a cell will overflow its column into the next one. How do I force a break on the text so that a new line is created instead? I can't manually insert zero-space characters since the table entries are programmatically entered. I'm looking for a simple solution that I can just simply add to docbook_pdf.xsl (either as a xsl:param or xsl:attribute) EDIT: Here is where I'm at currently: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:import href="urn:docbkx:stylesheet"/> ...(the beginning of my stylesheet for pdf generation, e.g. header and footer content stuff) <xsl:template match="text()"> <xsl:call-template name="intersperse-with-zero-spaces"> <xsl:with-param name="str" select="."/> </xsl:call-template> </xsl:template> <xsl:template name="intersperse-with-zero-spaces"> <xsl:param name="str"/> <xsl:variable name="spacechars"> &#x9;&#xA; &#x2000;&#x2001;&#x2002;&#x2003;&#x2004;&#x2005; &#x2006;&#x2007;&#x2008;&#x2009;&#x200A;&#x200B; </xsl:variable> <xsl:if test="string-length($str) &gt; 0"> <xsl:variable name="c1" select="substring($str, 1, 1)"/> <xsl:variable name="c2" select="substring($str, 2, 1)"/> <xsl:value-of select="$c1"/> <xsl:if test="$c2 != '' and not(contains($spacechars, $c1) or contains($spacechars, $c2))"> <xsl:text>&#x200B;</xsl:text> </xsl:if> <xsl:call-template name="intersperse-with-zero-spaces"> <xsl:with-param name="str" select="substring($str, 2)"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> With this, the long words are successfully broken up in the table cells! Unfortunately, the side effect is that normal text elsewhere (like in a under sextion X) now breaks up words so that they appear on seperate lines. Is there a way to isolate the above process to just tables? EDIT #2 here is what the fo spits out for a single table... <fo:table-row><fo:table-cell padding-start="2pt" padding-end="2pt" padding-top="2pt" ... </fo:block></fo:table-cell></fo:table-row>

    Read the article

  • Javascript replace last occurence of text in a string

    - by Ruth
    Hi all see my code snippet below: var list = ['one', 'two', 'three', 'four']; var str = 'one two, one three, one four, one]; for ( var i = 0; i < list.length; i++) { if (str.endsWith(list[i]) { str = str.replace(list[i], 'finsih') } } I want to replace the last occurence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one' Thank you Ruth

    Read the article

  • Taking User Input in Java

    - by jdbeverly87
    I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome { public static void main(String args[]) { String s=""; int i; int n=s.length(); String str=""; for(i=n-1;i>=0;i--) str=str+s.charAt(i); if(str.equals(s)) System.out.println(s+ " is a palindrome"); else System.out.println(s+ " is not a palindrome"); } }

    Read the article

  • Blackjack game reshuffling problem-edited

    - by Jam
    I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than once, and I can't figure out why. Help, please. Here's what I have so far: (P.S. the imported cards and games modules aren't part of the problem, I'm fairly sure my problem lies in the deal() function of my BJ_Deck class.) import cards, games class BJ_Card(cards.Card): """ A Blackjack Card. """ ACE_VALUE = 1 def get_value(self): if self.is_face_up: value = BJ_Card.RANKS.index(self.rank) + 1 if value > 10: value = 10 else: value = None return value value = property(get_value) class BJ_Deck(cards.Deck): """ A Blackjack Deck. """ def populate(self): for suit in BJ_Card.SUITS: for rank in BJ_Card.RANKS: self.cards.append(BJ_Card(rank, suit)) def deal(self, hands, per_hand=1): for rounds in range(per_hand): if len(self.cards)>=7*(len(hands)): print "Reshuffling the deck." self.cards=[] self.populate() self.shuffle() for hand in hands: top_card=self.cards[0] self.give(top_card, hand) class BJ_Hand(cards.Hand): """ A Blackjack Hand. """ def __init__(self, name): super(BJ_Hand, self).__init__() self.name = name def __str__(self): rep = self.name + ":\t" + super(BJ_Hand, self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep def get_total(self): # if a card in the hand has value of None, then total is None for card in self.cards: if not card.value: return None # add up card values, treat each Ace as 1 total = 0 for card in self.cards: total += card.value # determine if hand contains an Ace contains_ace = False for card in self.cards: if card.value == BJ_Card.ACE_VALUE: contains_ace = True # if hand contains Ace and total is low enough, treat Ace as 11 if contains_ace and total <= 11: # add only 10 since we've already added 1 for the Ace total += 10 return total total = property(get_total) def is_busted(self): return self.total > 21 class BJ_Player(BJ_Hand): """ A Blackjack Player. """ def is_hitting(self): response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ") return response == "y" def bust(self): print self.name, "busts." self.lose() def lose(self): print self.name, "loses." def win(self): print self.name, "wins." def push(self): print self.name, "pushes." class BJ_Dealer(BJ_Hand): """ A Blackjack Dealer. """ def is_hitting(self): return self.total < 17 def bust(self): print self.name, "busts." def flip_first_card(self): first_card = self.cards[0] first_card.flip() class BJ_Game(object): """ A Blackjack Game. """ def __init__(self, names): self.players = [] for name in names: player = BJ_Player(name) self.players.append(player) self.dealer = BJ_Dealer("Dealer") self.deck = BJ_Deck() self.deck.populate() self.deck.shuffle() def get_still_playing(self): remaining = [] for player in self.players: if not player.is_busted(): remaining.append(player) return remaining # list of players still playing (not busted) this round still_playing = property(get_still_playing) def __additional_cards(self, player): while not player.is_busted() and player.is_hitting(): self.deck.deal([player]) print player if player.is_busted(): player.bust() def play(self): # deal initial 2 cards to everyone self.deck.deal(self.players + [self.dealer], per_hand = 2) self.dealer.flip_first_card() # hide dealer's first card for player in self.players: print player print self.dealer # deal additional cards to players for player in self.players: self.__additional_cards(player) self.dealer.flip_first_card() # reveal dealer's first if not self.still_playing: # since all players have busted, just show the dealer's hand print self.dealer else: # deal additional cards to dealer print self.dealer self.__additional_cards(self.dealer) if self.dealer.is_busted(): # everyone still playing wins for player in self.still_playing: player.win() else: # compare each player still playing to dealer for player in self.still_playing: if player.total > self.dealer.total: player.win() elif player.total < self.dealer.total: player.lose() else: player.push() # remove everyone's cards for player in self.players: player.clear() self.dealer.clear() def main(): print "\t\tWelcome to Blackjack!\n" names = [] number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) for i in range(number): name = raw_input("Enter player name: ") names.append(name) print game = BJ_Game(names) again = None while again != "n": game.play() again = games.ask_yes_no("\nDo you want to play again?: ") main() raw_input("\n\nPress the enter key to exit.") Since someone decided to call this 'psychic-debugging', I'll go ahead and tell you what the modules are then. Here's the cards module: class Card(object): """ A playing card. """ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] def __init__(self, rank, suit, face_up = True): self.rank = rank self.suit = suit self.is_face_up = face_up def __str__(self): if self.is_face_up: rep = self.rank + self.suit else: rep = "XX" return rep def flip(self): self.is_face_up = not self.is_face_up class Hand(object): """ A hand of playing cards. """ def init(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: rep = "<empty>" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) class Deck(Hand): """ A deck of playing cards. """ def populate(self): for suit in Card.SUITS: for rank in Card.RANKS: self.add(Card(rank, suit)) def shuffle(self): import random random.shuffle(self.cards) def deal(self, hands, per_hand = 1): for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print "Can't continue deal. Out of cards!" if name == "main": print "This is a module with classes for playing cards." raw_input("\n\nPress the enter key to exit.") And here's the games module: class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): self.name = name self.score = score def __str__(self): rep = self.name + ":\t" + str(self.score) return rep def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(raw_input(question)) return response if name == "main": print "You ran this module directly (and did not 'import' it)." raw_input("\n\nPress the enter key to exit.")

    Read the article

  • sharpziplib + Whenever i try to add a file to existing archive, it overwrites previous contents

    - by schmoopy
    I am trying to add files to an existing zip file. Whenever i do, the new one contains the new list of files im passing in, but all of the previous ones are wiped out. I have also tried the code here: http://stackoverflow.com/questions/1356003/c-sharpziplib-adding-file-to-existing-archive -- same results Any idea why i cannot add files to an existing zip while maintaining the previous files? Here is the code: public static void AddFileToZip(string currentZipPath, List<string> files, bool includeFullPathInEntry, int compressionLevel) { ZipOutputStream zipStrm = new ZipOutputStream(File.Open(currentZipPath, FileMode.Open, FileAccess.ReadWrite)); zipStrm.SetLevel(compressionLevel); foreach (string str in files) { string entryName = str; if (!includeFullPathInEntry) entryName = new FileInfo(str).Name; ZipEntry entry = new ZipEntry(entryName); zipStrm.PutNextEntry(entry); Byte[] b = File.ReadAllBytes(str); zipStrm.Write(b, 0, b.Length); } zipStrm.Finish(); zipStrm.Close(); }

    Read the article

  • valgrind complains doing a very simple strtok in c

    - by monkeyking
    Hi I'm trying to tokenize a string by loading an entire file into a char[] using fread. For some strange reason it is not always working, and valgrind complains in this very small sample program. Given an input like test.txt first second And the following program #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> //returns the filesize in bytes size_t fsize(const char* fname){ struct stat st ; stat(fname,&st); return st.st_size; } int main(int argc, char *argv[]){ FILE *fp = NULL; if(NULL==(fp=fopen(argv[1],"r"))){ fprintf(stderr,"\t-> Error reading file:%s\n",argv[1]); return 0; } char buffer[fsize(argv[1])]; fread(buffer,sizeof(char),fsize(argv[1]),fp); char *str = strtok(buffer," \t\n"); while(NULL!=str){ fprintf(stderr,"token is:%s with strlen:%lu\n",str,strlen(str)); str = strtok(NULL," \t\n"); } return 0; } compiling like gcc test.c -std=c99 -ggdb running like ./a.out test.txt thanks

    Read the article

  • Java RegEx find, except when between quotes

    - by user1833511
    I need a Java RegEx to split, or find something in a string, but exclude stuff that's between double quotes. What I do now is this: String withoutQuotes = str.replaceAll("\\\".*?\\\"", "placeholder"); withoutQuotes = withoutQuotes.replaceAll(" ",""); but this doesn't work nice with indexOf, and I also need to be able to split, for example: String str = "hello;world;how;\"are;you?\"" String[] strArray = str.split(/*some regex*/); // strArray now contains: ["hello", "world", "how", "\"are you?\"] quotes are always balanced quotes can be escaped with \" Any help is appreciated

    Read the article

  • How to pass parameters in jquery

    - by Priyanka
    Hello. I am supposed to submit 2values called str and name to another page.But only 1value is getting returned in the next page.When i include name and on next page if i say print_r($_POST),then even the first value is not getting printed. I have written a fuction as follows,which works because there is only one parameter. function sendValue(str) { $.post( "newsletter/subscribe.php", //Ajax file { sendValue: str }, function(data){ $('#display').html(data.returnValue); }, "json" ); } But if i pass 2values in that function and in $.post,i do sendValue:str,name then i am not getting even 1value. Please help me.

    Read the article

  • whats wrong with the following code

    - by giri
    Hi i am trying to send sms to my mobile using java.When I run the application I am getting the the follwing error. package HelloWorld; import java.io.*; import java.util.BitSet; import javax.comm.*; import java.lang.*; public class SerialToGsm { InputStream in; OutputStream out; String lastIndexRead; String senderNum; String smsMsg; SerialToGsm(String porta) { try { // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("serial0"); CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(porta); SerialPort sp = (SerialPort)portId.open("Sms_GSM", 0); sp.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); sp.setFlowControlMode(sp.FLOWCONTROL_NONE); in = sp.getInputStream(); out = sp.getOutputStream(); // modem reset sendAndRecv("+++AT", 30); // delay for 20 sec/10 sendAndRecv("AT&F", 30); sendAndRecv("ATE0", 30); // echo off sendAndRecv("AT +CMEE=1", 30); // verbose error messages sendAndRecv("AT+CMGF=0", 70); // set pdu mode // sendAndRecv("AT V1E0S0=0&D2&C1", 1000000); } catch (Exception e) { System.out.println("Exception " + e); System.exit(1); } } private String sendAndRecv(String s, int timeout) { try { // clean serial port input buffer in.skip(in.available()); System.out.println("=> " + s); s = s + "\r"; // add CR out.write(s.getBytes()); out.flush(); String strIn = new String(); for (int i = 0; i < timeout; i++){ int numChars = in.available(); if (numChars > 0) { byte[] bb = new byte[numChars]; in.read(bb,0,numChars); strIn += new String(bb); } // start exit conditions // --------------------- if (strIn.indexOf(">\r\n") != -1) { break; } if (strIn.indexOf("OK\r\n") != -1){ break; } if (strIn.indexOf("ERROR") != -1) { // if find 'error' wait for CR+LF if (strIn.indexOf("\r\n",strIn.indexOf("ERROR") + 1) != -1) { break; } } Thread.sleep(100); // delay 1/10 sec } System.out.println("<= " + strIn); if (strIn.length() == 0) { return "ERROR: len 0"; } return strIn; } catch (Exception e) { System.out.println("send e recv Exception " + e); return "ERROR: send e recv Exception"; } } public String sendSms (String numToSend, String whatToSend) { ComputSmsData sms = new ComputSmsData(); sms.setAsciiTxt(whatToSend); sms.setTelNum(numToSend); // sms.setSMSCTelNum("+393359609600"); // SC fixed String s = new String(); s = sendAndRecv("AT+CMGS=" + (sms.getCompletePduData().length() / 2) + "\r", 30); // System.out.println("==> AT+CMGS=" + (sms.getCompletePduData().length() / 2)); // System.out.println("<== " + s); if (s.indexOf(">") != -1) { // s = sendAndRecv(sms.getSMSCPduData() + sms.getCompletePduData() + "\u001A"); // usefull one day? // System.out.println("Inviero questo >>>> " + sms.getCompletePduData()); // if this sintax won't work try remove 00 prefix s = sendAndRecv("00" + sms.getCompletePduData() + "\u001A", 150); // System.out.println("<== " + s); return s; } else { return "ERROR"; } } // used to reset message data private void resetGsmObj() { lastIndexRead = null; senderNum = null; smsMsg = null; } public String checkSms (){ String str = new String(); String strGsm = new String(); strGsm = sendAndRecv("AT+CMGL=0", 30); // list unread msg and sign them as read // if answer contain ERROR then ERROR if (strGsm.indexOf("ERROR") != -1) { resetGsmObj(); return strGsm; // error } strGsm = sendAndRecv("AT+CMGL=1", 30); // list read msg // if answer contain ERROR then ERROR if (strGsm.indexOf("ERROR") != -1) { resetGsmObj(); return strGsm; // error } // evaluate message index if (strGsm.indexOf(':') <= 0) { resetGsmObj(); return ("ERROR unexpected answer"); } str = strGsm.substring(strGsm.indexOf(':') + 1,strGsm.indexOf(',')); str = str.trim(); // remove white spaces // System.out.println("Index: " + str); lastIndexRead = str; // find message string // ------------------- // look for start point (search \r, then skip \n, add and one more for right char int startPoint = strGsm.indexOf("\r",(strGsm.indexOf(":") + 1)) + 2; int endPoint = strGsm.indexOf("\r",startPoint + 1); if (endPoint == -1) { // only one message endPoint = strGsm.length(); } // extract string str = strGsm.substring(startPoint, endPoint); System.out.println("String to be decoded :" + str); ComputSmsData sms = new ComputSmsData(); sms.setRcvdPdu(str); // SMSCNum = new String(sms.getRcvdPduSMSC()); senderNum = new String(sms.getRcvdSenderNumber()); smsMsg = new String(sms.getRcvdPduTxt()); System.out.println("SMSC number: " + sms.getRcvdPduSMSC()); System.out.println("Sender number: " + sms.getRcvdSenderNumber()); System.out.println("Message: " + sms.getRcvdPduTxt()); return "OK"; } public String readSmsSender() { return senderNum; } public String readSms() { return smsMsg; } public String delSms() { if (lastIndexRead != "") { return sendAndRecv("AT+CMGD=" + lastIndexRead, 30); } return ("ERROR"); } } ERROR: Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path Caught java.lang.UnsatisfiedLinkError: com.sun.comm.SolarisDriver.readRegistrySerial(Ljava/util/Vector;Ljava/lang/String;)I while loading driver com.sun.comm.SolarisDriver Exception javax.comm.NoSuchPortException

    Read the article

  • Perl : split the string from last occurrence .

    - by kiruthika
    Hi All, my $str="1:2:3:4:5"; my ($a,$b)=split(':',$str,2); In the above code I have used limit as 2 ,so $a will contain 1 and remaining elements will be in $b. Like this I want the last element should be in one variable and the elements prior to the last element should be in another variable. Example $str = "1:2:3:4:5" ; # $a should have "1:2:3:4" and $b should have "5" $str = "2:3:4:5:3:2:5:5:3:2" # $a should have "2:3:4:5:3:2:5:5:3" and $b should have "2"

    Read the article

  • Android: Is it possible to have multiple styles inside a TextView?

    - by Legend
    I was wondering if its possible to set multiple styles for different pieces of text inside a TextView. For instance, I am setting the text as follows: descbox.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3); Now, is it possible to have a different style for each text element? I mean bold for line1, normal for word1 and so on... I found this http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext: // Get our EditText object. EditText vw = (EditText)findViewById(R.id.text); // Set the EditText's text. vw.setText("Italic, highlighted, bold."); // If this were just a TextView, we could do: // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); // to force it to use Spannable storage so styles can be attached. // Or we could specify that in the XML. // Get the EditText's internal text storage Spannable str = vw.getText(); // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); But it uses position numbers inside the text. Is there a cleaner way to do this?

    Read the article

  • Problem with Marshalling char* in c#

    - by chrmue
    I have a problem calling this function from a c++ DLL in c# INT32 WINAPI PM_COM_GetText(INT32 TextId, char* pBuf, INT32 BufSize); It writes a Text in a buffer for a given text id. I try to call it with the following c# code, but I constantly get an access violation and don't undrestand why: public string GetText(Int32 TextId) { Int32 BufSize = 256; StringBuilder Str = new StringBuilder(BufSize); PM_COM_GetText(TextId, Str, BufSize); return Str.ToString(); } [DllImport("ComDll.dll", CharSet = CharSet.Ansi)] private static extern Int32 PM_COM_GetText(Int32 TextId, StringBuilder Str, Int32 BufSize); I don't see what's wrong, it looks to me like many other code snippets I found in the web. Any ideas? Thanks in advance!

    Read the article

  • highlight the word in the string, if it contains the keyword

    - by Syom
    how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following $str = "the bird is funny"; $keyword = "fun"; $str = preg_replace("/($keyword)/i","<b>$1</b>",$str); but it menshions only keyword. the bird is *fun*ny

    Read the article

  • jQuery ajax success not work in codeigniter

    - by softboxkid
    I had a problem with ajax. The trick is, when user click on the top hyperlink, it will send the link id through onclick=getChildMenuLink(str). Then from getChildMenuLink(str) function, it will send the str to the controller (to set the session) thru ajax. here is the code. html code <a href="http://localhost/ejournal/index.php/sysconfig" onclick="getChildMenuLink(1)">Administrator</a> <a href="http://localhost/ejournal/index.php/welcome" onclick="getChildMenuLink(22)">Home</a> jquery ajax function getChildMenuLink(str) { 'use strict'; $.ajax({ type: 'POST', url: "http://localhost/ejournal/index.php/sysconfig/getLink/" + str, success: function () {} // End of success function of ajax form }); // End of ajax call //alert(document.URL); } codeigniter controller function getLink($id='') { $this->session->unset_userdata('parentLink'); $this->session->set_userdata('parentLink',$id); } if i uncomment the alert() function on that script, it work. the PHP session is properly set. please help me

    Read the article

  • Attribute class not calling constructor

    - by Coppermill
    I have created an Attribute, call MyAttribute, which is performing some security and for some reason the Constructor is not being fired, any reason why? public class Driver { // Entry point of the program public static void Main(string[] Args) { Console.WriteLine(SayHello1("Hello to Me 1")); Console.WriteLine(SayHello2("Hello to Me 2")); Console.ReadLine(); } [MyAttribute("hello")] public static string SayHello1(string str) { return str; } [MyAttribute("Wrong Key, should fail")] public static string SayHello2(string str) { return str; } } [AttributeUsage(AttributeTargets.Method)] public class MyAttribute : Attribute { public MyAttribute(string VRegKey) { if (VRegKey == "hello") { Console.WriteLine("Aha! You're Registered"); } else { throw new Exception("Oho! You're not Registered"); }; } }

    Read the article

  • Listing directories in Linux from C

    - by nunos
    I am trying to simulate linux command ls using linux api from c. Looking at the code it does make sense, but when I run it I get "stat error: No such file or directory". I have checked that opendir is working ok. I think the problem is in stat, which is returning -1 even though I think it should return 0. What am I missing? Thanks for your help. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> #include <errno.h> int main(int argc, char *argv[]) { DIR *dirp; struct dirent *direntp; struct stat stat_buf; char *str; if (argc != 2) { fprintf( stderr, "Usage: %s dir_name\n", argv[0]); exit(1); } if ((dirp = opendir( argv[1])) == NULL) { perror(argv[1]); exit(2); } while ((direntp = readdir( dirp)) != NULL) { if (stat(direntp->d_name, &stat_buf)==-1) { perror("stat ERROR"); exit(3); } if (S_ISREG(stat_buf.st_mode)) str = "regular"; else if (S_ISDIR(stat_buf.st_mode)) str = "directory"; else str = "other"; printf("%-25s - %s\n", direntp->d_name, str); } closedir(dirp); exit(0); }

    Read the article

  • Prevent backslash from being parsed by javascript for a string

    - by user286269
    A Flash AS3 IRC application sends me a string like "f\reak" to my javascript. Irc allows the \ in usernames which poses a problem when its passed to javascript. "f\reak" become "feak" in javascript making the \r into a carriage return. Is there a way to read the absolute value of the string instead of parsing a carriage return? These don't methods didn't work str.valueOf() str.toString() str.charAt(position of the \ ) this just sees the carriage return as well and not a backslash

    Read the article

  • I'm making a simulated tv

    - by Jam
    I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please. class Television(object): def __init__(self, __channel=1, volume=1, is_on=0): self.__channel=__channel self.volume=volume self.is_on=is_on def __str__(self): if self.is_on==1: print "The tv is on" print self.__channel print self.volume else: print "The television is off." def toggle_power(self): if self.is_on==1: self.is_on=0 return self.is_on if self.is_on==0: self.is_on=1 return self.is_on def get_channel(self): return channel def set_channel(self, choice): if self.is_on==1: if choice>=0 and choice<=499: channel=self.__channel else: print "Invalid channel!" else: print "The television isn't on!" channel=property(get_channel, set_channel) def raise_volume(self, up=1): if self.is_on==1: self.volume+=up if self.volume>=10: self.volume=10 print "Max volume!" else: print "The television isn't on!" def lower_volume(self, down=1): if self.is_on==1: self.volume-=down if self.volume<=0: self.volume=0 print "Muted!" else: print "The television isn't on!" def main(): tv=Television() choice=None while choice!="0": print \ """ Television 0 - Exit 1 - Toggle Power 2 - Change Channel 3 - Raise Volume 4 - Lower Volume """ choice=raw_input("Choice: ") print if choice=="0": print "Good-bye." elif choice=="1": tv.toggle_power() tv.__str__() elif choice=="2": change=raw_input("What would you like to change the channel to?") tv.set_channel(change) tv.__str__() elif choice=="3": tv.raise_volume() tv.__str__() elif choice=="4": tv.lower_volume() tv.__str__() else: print "\nSorry, but", choice, "isn't a valid choice." main() raw_input("Press enter to exit.")

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >