func lexChar(l *Lexer) stateFn { Loop: for { switch l.next() { case '"': fmt.Println(string(l.input[l.pos-2])) if l.input[l.pos-2] != '\\' { return l.errorf("unescaped char %s", string(l.input[l.pos-1])) } case '\\': if ok := runeIsEscape(l.peek()); !ok { return l.errorf("Not an escape character %s", strconv.QuoteRuneToASCII(l.next())) } else { l.next() break } fallthrough case eof, '\n': return l.errorf("unterminated character constant") case '\'': break Loop } } l.emit(CHARACTER) return lexInsideProgram }
func ExampleQuoteRuneToASCII() { s := strconv.QuoteRuneToASCII('☺') fmt.Println(s) // Output: // '\u263a' }
// Create normalized array of rows from mixed data (interface{}) func createFromMixed(data [][]interface{}, format byte) []*TabulateRow { rows := make([]*TabulateRow, len(data)) for index_1, element := range data { normalized := make([]string, len(element)) for index, el := range element { switch el.(type) { case int32: quoted := strconv.QuoteRuneToASCII(el.(int32)) normalized[index] = quoted[1 : len(quoted)-1] case int: normalized[index] = strconv.Itoa(el.(int)) case int64: normalized[index] = strconv.FormatInt(el.(int64), 10) case bool: normalized[index] = strconv.FormatBool(el.(bool)) case float64: normalized[index] = strconv.FormatFloat(el.(float64), format, -1, 64) case uint64: normalized[index] = strconv.FormatUint(el.(uint64), 10) case nil: normalized[index] = "nil" default: normalized[index] = fmt.Sprintf("%s", el) } } rows[index_1] = &TabulateRow{Elements: normalized} } return rows }
func main() { file, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() //scan line number line ln, err := strconv.Atoi(scanner.Text()) if err != nil { log.Fatal(err) } var s string for i := 1; i <= ln; i++ { scanner.Scan() tmp := scanner.Text() tmp = strings.ToLower(tmp) for _, r := range tmp { //rc := strconv.QuoteRuneToASCII(r) if r >= 'a' && r <= 'z' { s += strconv.QuoteRuneToASCII(r) } } } if s == reverse(s) { fmt.Println("Palindrome") } else { fmt.Println("Not a Palindrome") } }
// fmt_qc formats the integer as a single-quoted, escaped Go character constant. // If the character is not valid Unicode, it will print '\ufffd'. func (f *fmt) fmt_qc(c int64) { var quoted string if f.plus { quoted = strconv.QuoteRuneToASCII(int(c)) } else { quoted = strconv.QuoteRune(int(c)) } f.padString(quoted) }
// Print a byte as ASCII, using escape sequences where necessary. func printAsciiByte(b uint8) { r := rune(b) if unicode.IsPrint(r) || unicode.IsSpace(r) { fmt.Print(string(r)) } else { charStr := strconv.QuoteRuneToASCII(r) fmt.Print(charStr[1 : len(charStr)-1]) } }
func (z *ConstNumber) StringShow0i(show0i bool) string { if z.Type == ConstRune && z.Value.Re.Num().BitLen() <= 32 { r, _, _ := z.Value.Int(32) return strconv.QuoteRuneToASCII(rune(r)) } else if z.Type == ConstComplex { return z.Value.StringShow0i(show0i) } else { return z.Value.StringShow0i(false) } }
// Create normalized array from ints32 func createFromInt32(data [][]int32) []*TabulateRow { rows := make([]*TabulateRow, len(data)) for index_1, arr := range data { row := make([]string, len(arr)) for index, el := range arr { quoted := strconv.QuoteRuneToASCII(el) row[index] = quoted[1 : len(quoted)-1] } rows[index_1] = &TabulateRow{Elements: row} } return rows }
func (filter *ScenarioFilterBasedOnTags) getOperatorsAndOperands() ([]string, []string) { listOfOperators := make([]string, 0) listOfTags := strings.FieldsFunc(filter.tagExpression, func(r rune) bool { isValidOperator := r == '&' || r == '|' || r == '(' || r == ')' || r == '!' if isValidOperator { operator, _ := strconv.Unquote(strconv.QuoteRuneToASCII(r)) listOfOperators = append(listOfOperators, operator) return isValidOperator } return false }) return listOfOperators, listOfTags }
func Decode(code string) (lat, lon float64) { var _decode = func(character []rune) float64 { var loc float64 first := strconv.QuoteRuneToASCII(character[0]) second := strconv.QuoteRuneToASCII(character[1]) val, _ := strconv.ParseInt("0x"+first[3:7]+second[3:7], 0, 32) sval := strconv.FormatInt(val, 10) loc = 1 if val < 2000000000 { loc = -1 } if val > 1000000000 { val, _ = strconv.ParseInt(sval[2:], 0, 0) } fval := math.Mod(float64(val), 1000000000) if sval[1] == 1 || sval[1] == 3 { fval += 90 } return fval / 10000000 * loc } return _decode([]rune(code)[:2]), _decode([]rune(code)[2:]) }
func (w *Worker) NextKey(f rune) uint64 { if !w.PreAllocated { w.next++ x := uint64(w.next<<16) | uint64(w.ID)<<8 | uint64(w.next%CHUNKS) return x } if w.LastKey[f] == w.CurrKey[f] { log.Fatalf("%v Ran out of preallocated keys for %v; %v %v", w.ID, strconv.QuoteRuneToASCII(f), w.CurrKey[f], w.LastKey[f]) } y := uint64(w.CurrKey[f] + w.start) x := uint64(y<<16) | uint64(w.ID)<<8 | y%CHUNKS w.CurrKey[f]++ return x }
func getCenter(w string) string { result := "" for idx, letter := range w { sideA, sideB := w[:idx], w[(idx+1):] sumA, sumB := sumSides(sideA, sideB) if sumA-sumB == 0 { result = fmt.Sprint(sideA, " ", strconv.QuoteRuneToASCII(letter), " ", sideB, " - ", sumA) break } } if result == "" { result = fmt.Sprint(w, " DOES NOT BALANCE") } return result }
// http://play.golang.org/p/pKPEeNWsjD // 用来escape 特殊字符 "Hello, '世界'" => E'Hello, \'\u4e16\u754c\'' func HexBuffer1(input string) string { output := make([]byte, 0, 3+len(input)) output = append(output, "E'"...) for _, r := range input { var s string switch r { case '\'': s = `\'` case '\\': s = `\\` default: s = strconv.QuoteRuneToASCII(r) // get rid of surrounding single quote s = s[1 : len(s)-1] } output = append(output, s...) } return string(append(output, '\'')) }
func Solution(expression string) int { // write your code in Go 1.4 stack := Stack{} fmt.Println(expression) for _, element := range expression { value, err := strconv.Atoi(string(element)) if err != nil { operand1, err := stack.Pop() if err != nil { return -1 } operand2, err := stack.Pop() if err != nil { return -1 } operation := strconv.QuoteRuneToASCII(element) if operation == "'+'" { total := operand1 + operand2 stack.Push(total) } else if operation == "'*'" { total := operand1 * operand2 stack.Push(total) } else { return -1 } } else { stack.Push(value) } } finalValue, err := stack.Pop() if err != nil { return -1 } else { return finalValue } }
func rtoa(r rune) string { return strconv.QuoteRuneToASCII(r) }
func (k Key) String() string { x, y := UndoCKey(k) return fmt.Sprintf("[%v%v]", strconv.QuoteRuneToASCII(y), x) }
// tokenize takes an expression and returns corresponding tokens. func (lexer *Lexer) tokenize(expression string) ([]token, error) { var tokens []token lexer.expression = expression lexer.currentPos = 0 lexer.lastWidth = 0 loop: for { r := lexer.next() if identifierStartBits&(1<<(uint64(r)-64)) > 0 { t := lexer.consumeUnquotedIdentifier() tokens = append(tokens, t) } else if val, ok := basicTokens[r]; ok { // Basic single char token. t := token{ tokenType: val, value: string(r), position: lexer.currentPos - lexer.lastWidth, length: 1, } tokens = append(tokens, t) } else if r == '-' || (r >= '0' && r <= '9') { t := lexer.consumeNumber() tokens = append(tokens, t) } else if r == '[' { t := lexer.consumeLBracket() tokens = append(tokens, t) } else if r == '"' { t, err := lexer.consumeQuotedIdentifier() if err != nil { return tokens, err } tokens = append(tokens, t) } else if r == '\'' { t, err := lexer.consumeRawStringLiteral() if err != nil { return tokens, err } tokens = append(tokens, t) } else if r == '`' { t, err := lexer.consumeLiteral() if err != nil { return tokens, err } tokens = append(tokens, t) } else if r == '|' { t := lexer.matchOrElse(r, '|', tOr, tPipe) tokens = append(tokens, t) } else if r == '<' { t := lexer.matchOrElse(r, '=', tLTE, tLT) tokens = append(tokens, t) } else if r == '>' { t := lexer.matchOrElse(r, '=', tGTE, tGT) tokens = append(tokens, t) } else if r == '!' { t := lexer.matchOrElse(r, '=', tNE, tNot) tokens = append(tokens, t) } else if r == '=' { t := lexer.matchOrElse(r, '=', tEQ, tUnknown) tokens = append(tokens, t) } else if r == '&' { t := lexer.matchOrElse(r, '&', tAnd, tExpref) tokens = append(tokens, t) } else if r == eof { break loop } else if _, ok := whiteSpace[r]; ok { // Ignore whitespace } else { return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) } } tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) return tokens, nil }
func main() { fmt.Println(strconv.QuoteRune('中')) fmt.Println(strconv.QuoteRuneToASCII('中')) fmt.Println(strconv.QuoteRuneToASCII(' ')) }
func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Scan() MESSAGE := scanner.Text() length := len(MESSAGE) //var charscode [int(length)]chardata //fmt.Fprintln(os.Stderr, int(length), charscode ) //stemp := []string{"", ""} sreadfrom := "" sans := "" // var slice = make([]string,length) //for key, value := range slice { //slice[key] = MESSAGE[key] //} for l := 0; l < length; l++ { temp1 := int64(MESSAGE[l]) asbin := strconv.FormatInt(temp1, 2) lookat := string(asbin) if len(lookat) == 6 { temp := "0" temp += lookat sreadfrom += temp } else { sreadfrom += lookat } } fmt.Fprintln(os.Stderr, sreadfrom) //0,1, or 2. state := 0 // 1 == true, 0 == false //prev := false count := 0 for j := 0; j < len(sreadfrom); j++ { //fmt.Println(rune(lookat[j])) s, _ := strconv.Unquote(strconv.QuoteRuneToASCII(rune(sreadfrom[j]))) //initial encounter 1 if s == "1" && state == 0 { state = 1 } //initial encounter 0 if s == "0" && state == 0 { state = 2 } //swapped from 0 to 1 if s == "0" && state == 1 { //print sans += "0 " for k := 0; k < count; k++ { sans += "0" } count = 0 state = 2 sans += " " } //swapped from 1 to 0 if s == "1" && state == 2 { //print sans += "00 " for k := 0; k < count; k++ { sans += "0" } count = 0 state = 1 sans += " " } count++ //if reached the end if j == len(sreadfrom)-1 { if state == 1 { sans += "0 " for k := 0; k < count; k++ { sans += "0" } } if state == 2 { sans += "00 " for k := 0; k < count; k++ { sans += "0" } } //sans += " " } } count = 0 state = 0 //sans += " " //} fmt.Println(sans) // Write answer to stdout }
func main() { flag.Parse() runtime.GOMAXPROCS(*nprocs) if *clientGoRoutines == 0 { *clientGoRoutines = *nprocs } if *nworkers == 0 { *nworkers = *nprocs } if *doValidate { if !*ddtxn.Allocate { log.Fatalf("Cannot correctly validate without waiting for results; add -allocate\n") } } var nproducts int if *contention > 0 { nproducts = *nbidders / int(*contention) } else { nproducts = ddtxn.NUM_ITEMS } s := ddtxn.NewStore() coord := ddtxn.NewCoordinator(*nworkers, s) if *ddtxn.CountKeys { for i := 0; i < *nworkers; i++ { w := coord.Workers[i] w.NKeyAccesses = make([]int64, *nbidders) } } rubis := &apps.Rubis{} rubis.Init(nproducts, *nbidders, *nworkers, *clientGoRoutines, *ZipfDist, 0) rubis.PopulateBids(s, coord) // Just creates items to bid on fmt.Printf("Done populating bids\n") if !*ddtxn.Allocate { prealloc := time.Now() tmp := *ddtxn.UseRLocks *ddtxn.UseRLocks = true // Preallocate keys bids_per_worker := 200000.0 if *nworkers == 20 { bids_per_worker *= 20 } if *rounds { parallelism := 10 rounds := *nworkers / parallelism if rounds == 0 { rounds = 1 } for j := 0; j < rounds; j++ { fmt.Printf("Doing round %v\n", j) var wg sync.WaitGroup for i := j * parallelism; i < (j+1)*parallelism; i++ { if i >= *nworkers { break } wg.Add(1) go func(i int) { coord.Workers[i].PreallocateRubis(0, int(bids_per_worker), ddtxn.NUM_ITEMS) wg.Done() }(i) } wg.Wait() } } else { var wg sync.WaitGroup for i := 0; i < *nworkers; i++ { wg.Add(1) go func(i int) { coord.Workers[i].PreallocateRubis(0, int(bids_per_worker), ddtxn.NUM_ITEMS) wg.Done() }(i) } wg.Wait() } *ddtxn.UseRLocks = tmp fmt.Printf("Allocation took %v\n", time.Since(prealloc)) } fmt.Printf("Done initializing rubis\n") p := prof.StartProfile() start := time.Now() gave_up := make([]int64, *clientGoRoutines) var wg sync.WaitGroup for i := 0; i < *clientGoRoutines; i++ { exp := ddtxn.MakeExp(30) wg.Add(1) go func(n int) { retries := make(ddtxn.RetryHeap, 0) heap.Init(&retries) end_time := time.Now().Add(time.Duration(*nsec) * time.Second) var local_seed uint32 = uint32(rand.Intn(1000000)) wi := n % (*nworkers) w := coord.Workers[wi] for { tm := time.Now() if !end_time.After(tm) { break } var t ddtxn.Query if len(retries) > 0 && retries[0].TS.Before(tm) { t = heap.Pop(&retries).(ddtxn.Query) } else { rubis.MakeBid(w.ID, &local_seed, &t) if *ddtxn.Latency { t.S = time.Now() } } if *doValidate { t.W = make(chan struct { R *ddtxn.Result E error }) } committed := false _, err := w.One(t) if err == ddtxn.ESTASH { if *doValidate { x := <-t.W err = x.E } committed = true } else if err == ddtxn.EABORT { committed = false } else { committed = true } t.I++ if !committed { t.TS = tm.Add(time.Duration(ddtxn.RandN(&local_seed, exp.Exp(t.I))) * time.Microsecond) if t.TS.Before(end_time) { heap.Push(&retries, t) } else { gave_up[n]++ } } if committed && *doValidate { rubis.Add(t) } } wg.Done() if len(retries) > 0 { dlog.Printf("[%v] Length of retry queue on exit: %v\n", n, len(retries)) } gave_up[n] = gave_up[n] + int64(len(retries)) }(i) } wg.Wait() coord.Finish() end := time.Since(start) p.Stop() stats := make([]int64, ddtxn.LAST_STAT) nitr, nwait, nwait2 := ddtxn.CollectCounts(coord, stats) _ = nwait2 if *doValidate { rubis.Validate(s, int(nitr)) } for i := 1; i < *clientGoRoutines; i++ { gave_up[0] = gave_up[0] + gave_up[i] } if !*ddtxn.Allocate { keys := []rune{'b', 'c', 'd', 'i', 'k', 'u'} for i := 0; i < *nworkers; i++ { dlog.Printf("w: %v ", i) for _, k := range keys { dlog.Printf("%v %v/%v \t", strconv.QuoteRuneToASCII(k), coord.Workers[i].CurrKey[k], coord.Workers[i].LastKey[k]) } dlog.Printf("\n") } } out := fmt.Sprintf(" nworkers: %v, nwmoved: %v, nrmoved: %v, sys: %v, total/sec: %v, abortrate: %.2f, stashrate: %.2f, nbidders: %v, nitems: %v, contention: %v, done: %v, actual time: %v, throughput: ns/txn: %v, naborts: %v, coord time: %v, coord stats time: %v, total worker time transitioning: %v, nstashed: %v, rlock: %v, wrratio: %v, nsamples: %v, getkeys: %v, ddwrites: %v, nolock: %v, failv: %v, stashdone: %v, nfast: %v, gaveup: %v, epoch changes: %v, potential: %v, coordtotaltime %v, mergetime: %v, readtime: %v, gotime: %v ", *nworkers, ddtxn.WMoved, ddtxn.RMoved, *ddtxn.SysType, float64(nitr)/end.Seconds(), 100*float64(stats[ddtxn.NABORTS])/float64(nitr+stats[ddtxn.NABORTS]), 100*float64(stats[ddtxn.NSTASHED])/float64(nitr+stats[ddtxn.NABORTS]), *nbidders, nproducts, *contention, nitr, end, end.Nanoseconds()/nitr, stats[ddtxn.NABORTS], ddtxn.Time_in_IE, ddtxn.Time_in_IE1, nwait, stats[ddtxn.NSTASHED], *ddtxn.UseRLocks, *ddtxn.WRRatio, stats[ddtxn.NSAMPLES], stats[ddtxn.NGETKEYCALLS], stats[ddtxn.NDDWRITES], stats[ddtxn.NO_LOCK], stats[ddtxn.NFAIL_VERIFY], stats[ddtxn.NDIDSTASHED], ddtxn.Nfast, gave_up[0], ddtxn.NextEpoch, coord.PotentialPhaseChanges, coord.TotalCoordTime, coord.MergeTime, coord.ReadTime, coord.GoTime) fmt.Printf(out) fmt.Printf("\n") fmt.Printf("DD: %v\n", coord.Workers[0].Store().DD()) f, err := os.OpenFile(*dataFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { panic(err) } defer f.Close() ddtxn.PrintStats(out, stats, f, coord, s, *nbidders) x, y := coord.Latency() f.WriteString(x) f.WriteString(y) f.WriteString("\n") }