HashMap<Character, Character> charMap = new HashMap<Character ,Character>();
charMap['{'] = '}';
charMap['['] = ']';
charMap['('] = ')';
//println charMap.keySet()
Character ch = '{'
println charMap.keySet().contains(ch)
It simply prints false while it is obvious that my set contains '{", any idea why would this happen? (I am using groovy for testing...)
Thanks.
'{' is a String and not a Character in groovy. To prove that, just print this in last line:
println charMap.keySet()*.class
It has to be explicitly type-casted to character:
HashMap<Character, Character> charMap = new HashMap<Character ,Character>();
charMap['{' as char] = '}';
charMap['['] = ']';
charMap['('] = ')';
//println charMap.keySet()
Character ch = '{'
println charMap.keySet().contains(ch)
This is how it works:
//String
assert 'a'.class == String
//Character
def c1= 'a' as char, c2= (char)'b'
def c3= new Character(c2), c4= c2.charValue()
[c1, c2, c3, c4].each { assert it.class == Character }
assert c2 == c3 && c1 != c2
assert c1 < c2 && c1.compareTo(c2) == -1
assert c2.toString().class == String
Related
I want to get arguments from user and use them in function, but the types are different.
Note: a comment is there in bottom of code that is correctly work
but I want to get arguments directly
Thanks for your help
from string import ascii_letters
def encrypt(string , key):
alpha = ascii_letters
result = ''
for ch in string :
if ch not in alpha :
result += ch
else :
new_key = (alpha.index(ch) + key.str() ) % len(alpha)
result += alpha[new_key]
return result
def decrypt(string , key):
key *= -1
return encrypt(string , key)
state = ''
print("please enter 'e' to encrpyt & type 'd' to decrpyt :...")
state = input()
if state == 'e' :
print("please enter the str that you want to encrypt :... ")
c_str1 = input()
print("\nplease enter the key that shifts strings(e.x. 1 to 52):... ")
c_in1=input()
encrypt(c_str1, c_in1)
elif state == 'd':
print("please enter the str that you want to decrypt :... ")
c_str= input('')
print("\nplease enter the key (e.x. 1 to 52):... ")
c_in = input()
decrypt(c_str, c_in )
# print(decrypt('amir',4))
not sure what your question is , here my attempt at making your code run,
not sure runs as you expected:
from string import ascii_letters
def encrypt(string , key):
result = ''
alpha = ascii_letters
for ch in string :
if ch not in alpha :
result += ch
else :
new_key = (alpha.index(ch) + int(key)) % len(alpha)
result += alpha[new_key]
return result
def decrypt(string , key):
key *= -1
return encrypt(string , key)
state = ''
print("please enter 'e' to encrpyt & type 'd' to decrpyt :...")
state = input()
if state == 'e' :
print("please enter the str that you want to encrypt :... ")
c_str1 = input()
print("\nplease enter the key that shifts strings(e.x. 1 to 52):... ")
c_in1 = input()
print(encrypt(c_str1, c_in1))
elif state == 'd':
print("please enter the str that you want to decrypt :... ")
c_str = input()
print("\nplease enter the key (e.x. 1 to 52):... ")
c_in = int(input())
print(decrypt(c_str, c_in ))
thanks for your read and help.
I have download a genebank flat file from NCBI, which contains many entries. I would like to extract three entries from each gene and make them into a table. How to realize it? Thank you much. the file from NCBI---->The table I hope to get
my friend writes it for me with python:
================================================================================
import os
import pandas as pd
from tqdm import tqdm
import sys
def search_line(gene_dict,gene_name,target,info,mode,l):
if '/{}='.format(target) in l:
if len(l.split('"')) == 3:
gene_dict[gene_name][mode].append('{} = '.format(target) + l.split('"')[1].strip('\n'))
keep_read = 0
info = []
else:
info = [l.split('"')[1].strip('\n')]
keep_read = target_list.index(target)
else:
if '"' in l:
info.append(l.strip().strip('"\n'))
if '{} = '.format(target) + ' '.join(info) not in gene_dict[gene_name][mode]:
gene_dict[gene_name][mode].append('{} = '.format(target) + ' '.join(info))
keep_read = 0
info = []
else:
info.append(l.strip())
keep_read = target_list.index(target)
return gene_dict,info,keep_read
def init_frame_dict(gene_dict,ids,mode):
frame_dict = {'gene': gene_dict[ids]['gene'], 'source': mode}
for target in target_list[1:]:
frame_dict[target] = ''
return frame_dict
def gen_frame(gene_dict,flat):
frame = []
for ids in gene_dict.keys():
for mode in gene_dict[ids].keys():
if mode not in extract_list:
continue
# print(mode)
data = gene_dict[ids][mode]
frame_dict = init_frame_dict(gene_dict, ids, mode)
for target_data in data:
for target in target_list[1:]:
if '{} = '.format(target) in target_data:
if frame_dict[target] != '':
frame.append(frame_dict)
# print(frame_dict)
frame_dict = init_frame_dict(gene_dict, ids, mode)
frame_dict[target] = target_data.split('{} = '.format(target))[1]
frame.append(frame_dict)
pd.DataFrame(frame).to_csv('{}.csv'.format(flat[:-5]))
def main():
for flat in os.listdir(path_root):
gene_dict = {}
if flat[-4:] != 'flat':
continue
with open (os.path.join(path_root,flat)) as f:
lines = f.read()
genes = lines.split('/gene=')
skip = False
for gene in tqdm(genes[1:]):
if skip:
break
lines = gene.split('\n')
gene_name = lines[0].split('"')[1]
#init paras
mode = 'init'
target = 'none'
read_mode = 0
info = []
#init dict
if gene_name not in gene_dict:
gene_dict[gene_name] = {'gene':gene_name,'mRNA':[],'ncRNA':[],'CDS':[],'misc_RNA':[],'exon':[],}
#proc lines
for l in lines:
if 'ORIGIN' in l:
skip = True
break
if ' mRNA' in l:
mode = 'mRNA'
elif ' ncRNA' in l:
mode = 'ncRNA'
elif ' CDS' in l:
mode = 'CDS'
elif ' misc_RNA' in l:
mode = 'misc_RNA'
elif ' exon' in l:
mode = 'exon'
# search_line(gene_dict, gene_name, target, info, mode, l)
if '/product=' in l and mode != 'init' or (target == 'product' and read_mode == target_list.index('product')):
target = 'product'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/protein_id=' in l and mode != 'init' or (target == 'protein_id' and read_mode == target_list.index('protein_id')):
target = 'protein_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/note=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('note')):
target = 'note'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
if '/transcript_id=' in l and mode != 'init' or (target == 'note' and read_mode == target_list.index('transcript_id')):
target = 'transcript_id'
gene_dict,info,read_mode = search_line(gene_dict, gene_name, target, info, mode, l)
gen_frame(gene_dict,flat)
if __name__ == '__main__':
target_list = ['none', 'product', 'transcript_id','protein_id','note']
extract_list = ['mRNA']
path_root = 'flats'
if not os.path.exists(path_root):
print('Please put your flat files in flats/ directory !')
sys.exit()
if len(os.listdir(path_root)) == 0:
print('No files found in flats/ directory.')
sys.exit()
main()
hopefully an easy question.. I've been playing around with Nim and have realised I need to pass a table (dictionary, map, in some other languages), but I can't seem to figure out the syntax for declaring it in doStuff()
import tables
proc doStuff(n:int, t:[int, int]) = # How should I declare 't' here?
if n == 0:
return
t[n] = (n * 10)
echo "length of t = " & ($len(t))
doStuff(n+1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & ($len(tbl))
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & ($len(tbl))
main()
The above gets me Error: type expected, but got: [int, int]
Sorry if this is basic, but my Googling hasn't given me an answer yet
Many TIA
You almost got it, it should be like below:
import tables
proc doStuff(n: int, t: var Table[int, int]) =
if n == 0:
return
t[n] = n * 10
echo "length of t = " & $len(t)
doStuff(n + 1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & $len(tbl)
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & $len(tbl)
main()
You have to use var Table[int, int] instead of Table[int, int] because you are mutating the tbl variable recursively, so you need to pass by reference instead of by value.
I have to write a python function that takes two single-line strings as inputs and returns the index where the first difference between the two occurs (and a negative number in the case they're identical). This is the code I wrote so far:
def singleline_diff(line1, line2):
len1 = len(line1)
len2 = len(line2)
if len1 < len2:
min_len = len1
elif len1 > len2:
min_len = len2
else:
min_len = len1
indx1 = 0
indx2 = 0
if line1 == line2:
return IDENTICAL
elif line1 != line2:
if min_len == len1:
for word2 in line2:
word2 = line2 [indx2]
indx2 = indx2+1
if word2 not in line1:
diff_idx_2 = int(indx2)
print (diff_idx_2)
elif min_len == len2:
for word1 in line1:
word1 = line1 [indx1]
indx1=indx1+1
if word1 not in line2:
diff_idx_1 = int(indx1)
print (diff_idx_1)
In the event that line1 != line2, your code prints the integer to the console instead of returning the value, which is what it should be doing according to the documentation. Try return diff_idx_2 instead of print(diff_idx_2) (and the same for diff_idx_1).
def singleline_diff(line1, line2):
min_len = min(len(line1), len(line2))
for i in range(min_len):
if line1[i] != line2[i]:
return i
if min_len == len(line1) and min_len == len(line2):
return -1 # they're identical
return min_len # one of the two lines has terminated, hence they differ
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I am working on a tool that generates HTML from an XML description. I am looking for a library in scala that can help me generate CSS styles for the html elements.
Not sure I understand exactly what you are looking for, but I know http://liftweb.net/ has many tools for dealing with xml, html, and css. You can use the lift libraries without using the full framework.
you are looking for something like this : https://github.com/axiak/scala-css-parser
Run it like that
java -jar CSSRewriter.jar sources/input.css -t where/this/will/go
https://github.com/axiak/scala-css-parser/blob/master/src/SimpleCSSParser.scala
import annotation.tailrec
import collection.mutable.ArrayBuffer
import util.parsing.combinator._
import java.io.File
// See http://www.w3.org/TR/css3-syntax/#grammar0
class SimpleCSSParser extends JavaTokenParsers {
protected override val whiteSpace = """(\s|//.*|(?m)/\*(\*(?!/)|[^*])+\*/)+""".r
// Lexical symbols
def h = "[0-9a-fA-F]".r
def nonascii = "[\200-\377]"
def unicode = "\\[0-9a-fA-F]{1,6}".r
def escape = unicode | "\\[ -~\200-\377]".r
def nmstart = "[a-zA-Z]" | nonascii | escape
def nmchar = "[a-zA-Z0-9-]" | nonascii | escape
override def stringLiteral = ("\""+"""([^"\p{Cntrl}\\]|\\[\\/bfnrt"]|\\u[a-fA-F0-9]{4})*"""+"\"").r | ("\'"+"""([^'\p{Cntrl}\\]|\\[\\/bfnrt']|\\u[a-fA-F0-9]{4})*"""+"\'").r
override def ident = """[*#_]?-?[a-zA-Z_][a-zA-Z0-9_-]*""".r
def name = rep1(nmchar)
def CDO = "<!--"
def CDC = "-->"
def INCLUDES = "~="
def DASHMATCH = "|="
def url = rep("[!#$%&*-~".r | nonascii | escape)
def IMPORT_SYM = "(?i)#import".r
def PAGE_SYM = "(?i)#page".r
def MEDIA_SYM = "(?i)#media".r
def FONT_FACE_SYM = "(?i)#font-face".r
def CHARSET_SYM = "(?i)#charset".r
def NAMESPACE_SYM = "(?i)#namespace".r
def IMPORTANT_SYM = "!important" | ("!" ~ "important")
def EMS = decimalNumber ~ "em"
def EXS = decimalNumber ~ "ex"
def RESOLUTION = decimalNumber ~ "(?i)dpi".r
def LENGTH = decimalNumber ~ "(?i)(?:px|cm|mm|in|pt|pc)".r
def ANGLE = decimalNumber ~ "(?i)(?:deg|rad|grad)".r
def TIME = decimalNumber ~ "(?i)(?:s|ms)".r
def FREQ = decimalNumber ~ "(?i)(?:Hz|kHz)".r
def DIMEN = decimalNumber ~ ident
def PERCENTAGE = decimalNumber ~ "%"
def NUMBER = decimalNumber | "\\" ~ decimalNumber
def URI = "url(" ~ ((stringLiteral | "[^)]+".r) ^^ (URL(_))) ~ ")"
def hexcolor = "#(?:[0-9A-Fa-f]{3}){1,2}".r
def function = "[a-zA-Z:._0-9-]+\\(".r ~ funcexpr ~ ")"
def unary_operator = "-" | "+"
def term: Parser[Any] = unary_operator | ((PERCENTAGE | LENGTH | EMS | EXS | ANGLE | RESOLUTION |
TIME | FREQ | URI | hexcolor | stringLiteral | NUMBER | ie_expression | function | ident) ^^ (NeedsSpace(_)))
def expr = rep1(term ~ opt(operator))
def ie_expression_no_paren = "[^\\(\\)]+".r
def ie_expression_paren: Parser[Any] = "(" ~ rep(ie_expression_no_paren | ie_expression_paren) ~ ")"
def ie_expression = "expression" ~ ie_expression_paren
// This is an extension of the css spec to allow filter: alpha(opacity=xx) syntax (kwargs).
def funcexpr = rep(opt(ident ~ "=") ~ term ~ opt(operator))
def operator = "/" | ","
def combinator = "+" | ">" | "~"
def prio = IMPORTANT_SYM
def declaration = property ~ ":" ~ expr ~ opt(prio)
def transform_declaration = """(?i)(?:from|to)""".r ~ "{" ~ rep1(declaration ~ rep(";")) ~ "}"
def nth_expr = ("\\d+".r ~ "n" ~ opt(("+" | "-") ~ "\\d+".r)) | (opt("\\d+".r ~ "n") ~ ("+" | "-") ~ "\\d+".r) | "\\d+".r
def pseudo = ":" ~ opt((ident ~ "(" ~ (HASH | class_ | ident | nth_expr | (":" ~ ident)) ~ ")") | ident)
def attrib = "[" ~ ident ~ opt(opt("=" | INCLUDES | DASHMATCH) ~ (ident | stringLiteral)) ~ "]"
def element_name = "*" | ident | "/**/"
def class_ = "." ~ ident
def HASH = "#" ~ ident
def selector_modifier = HASH | class_ | attrib | pseudo
def simple_selector = (element_name ~ rep(selector_modifier)) | (rep1(selector_modifier))
def selector = simple_selector ~ opt(combinator | ",")
def declaration_body = "{" ~ rep(transform_declaration | declaration ~ rep(";")) ~ "}"
def ruleset = rep1(selector ^^ (NeedsSpace(_))) ~ declaration_body
def property = ident
def font_face = FONT_FACE_SYM ~ declaration_body
def moz_document = ("(?i)#-moz-document".r ^^ (NeedsSpace(_))) ~ opt(function) ~ "{" ~ rep(ruleset) ~ "}"
def pseudo_page = ":" ~ ident
def medium = ident
def media_qualifier = "(" ~ ident ~ ":" ~ term ~ ")"
def media_term = (ident | media_qualifier) ~ opt(",")
def page = (PAGE_SYM ^^ (NeedsSpace(_))) ~ opt(ident) ~ opt(pseudo_page) ~ "{" ~ rep1sep(declaration, ",") ~ "}"
def media = (MEDIA_SYM ^^ (NeedsSpace(_))) ~ rep1(media_term) ~ "{" ~ rep(ruleset) ~ "}"
def namespace_prefix = ident
def namespace = (NAMESPACE_SYM ^^ (NeedsSpace(_))) ~ opt(namespace_prefix) ~ opt(stringLiteral | URI) ~ ";"
def import_ = (IMPORT_SYM ^^ (NeedsSpace(_))) ~ (stringLiteral | URI) ~ repsep(medium, ",") ~ ";"
def stylesheet = opt((CHARSET_SYM^^ (NeedsSpace(_))) ~ stringLiteral ~ ";") ~
rep(import_) ~ rep(namespace) ~
rep(media | page | font_face | moz_document | ruleset)
}
case class URL(url: String) {
val AbsolutePattern = """^(?i)(?:/|(?:http|ftp|https|spdy)://).*""".r
val InsideQuote = """^(['\"]?)(.+)\1$""".r
def rewrite(prefix: String): String = url match {
case InsideQuote(quote, content) => {
quote + rewriteInside(content, prefix) + quote
}
case _ => rewriteInside(url, prefix)
}
private def rewriteInside(inside: String, prefix: String): String = inside match {
case AbsolutePattern() => inside
case _ => prefix + inside
}
}
case class NeedsSpace(token: Any)
object Main extends SimpleCSSParser {
var prefix: String = ""
def main(args: Array[String]) {
val noSpace = Set(";", "}", ")", "{", "(", ",", ">", "<", "+")
val targetIndex = args.zipWithIndex filter {case (arg, idx) => arg == "-t"}
val target = if (targetIndex.length > 0)
Some(args(targetIndex(0)._2 + 1))
else
None
val sourceIndex = args.zipWithIndex filter {case (arg, idx) => arg == "-s"}
val sourcePath = if (sourceIndex.length > 0)
Some(args(sourceIndex(0)._2 + 1))
else
None
var originalSourcePath = if (sourcePath.isDefined)
Some(sourcePath.get)
else if (args.length > 0 && args(0) != "-t" && args(0) != "-s")
Some(args(0))
else
None
if (originalSourcePath.isDefined && target.isDefined) {
val parent = new File(originalSourcePath.get).getParent
val sourceList = if (parent == null || parent == "")
Nil
else
parent.split(File.separator).toList
val destParent = new File(target.get).getParent
val destList = if (destParent == null || destParent == "")
Nil
else
destParent.split(File.separator).toList
this.prefix = computePrefix(sourceList, destList).mkString("/")
if (!this.prefix.isEmpty)
this.prefix += "/"
}
val input = if (args.length > 0 && args(0) != "-t" && args(0) != "-s") {
io.Source.fromFile(args(0))
} else {
io.Source.stdin
}
val result = parseAll(stylesheet, input.getLines().mkString("\n"))
try {
val flatResult = flatResultList(result)
// Beautify by removing needless spaces.
flatResult.zipWithIndex foreach { case (value, idx) => if (idx > 0 && noSpace.contains(value) && flatResult(idx - 1) == " ") flatResult(idx - 1) = "" }
print(flatResult.mkString(""))
} catch {
case e: Exception => System.err.println(result)
}
}
#tailrec
def computePrefix(sourceDir: List[String], target: List[String], acc: List[String] = List()):
List[String] = (sourceDir, target) match {
case (shead :: srest, thead :: trest) =>
if (shead == thead)
computePrefix(srest, trest, acc)
else
computePrefix(srest, trest, ".." :: acc ::: List(shead))
case (Nil, thead :: trest) => computePrefix(Nil, trest, ".." :: acc)
case (shead :: srest, Nil) => computePrefix(srest, Nil, acc ::: List(shead))
case (Nil, Nil) => acc
}
def flatResultList(result: Any): ArrayBuffer[String] = result match {
case a: Some[Any] => flatResultList(a.get)
case a: ParseResult[Any] => flatResultList(a.get)
case a: ~[Any, Any] => flatResultList(a._1) ++ flatResultList(a._2)
case a :: rest => flatResultList(a) ++ flatResultList(rest)
case a: String => ArrayBuffer(a)
case None => ArrayBuffer()
case List() => ArrayBuffer()
/* Put any rewrite rule here, and annotate the above tokens with ^^ to do it. */
case url: URL => ArrayBuffer(url.rewrite(this.prefix))
case needsSpace: NeedsSpace => flatResultList(needsSpace.token) ++ ArrayBuffer(" ")
}
}
https://github.com/axiak/scala-css-parser/blob/master/src/testurl.sh
#!/bin/bash
curl "$1" | java -cp /opt/scala/lib/scala-library.jar:. Main
Take a look at Hyperscala (http://www.hyperscala.org). It has an incredibly powerful CSS parser built-in (StyleSheet.parse) that can parse multiple selectors.