Imagine I have the following string :
set(SEXY_STRING "I love CMake")
then I want to obtain SEXY_LIST from SEXY_STRING so I can do
list(LENGTH SEXY_LIST len)
and len is equal 3.
I've found several macros on web, but I really want to know how to do it in "natural" way. This operation seems to be very basic and widely used.
Replace your separator by a ;. I don't see any other way to do it.
cmake_minimum_required(VERSION 2.8)
set(SEXY_STRING "I love CMake")
string(REPLACE " " ";" SEXY_LIST ${SEXY_STRING})
message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake
message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake
list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3
You can use the separate_arguments command.
cmake_minimum_required(VERSION 2.6)
set(SEXY_STRING "I love CMake")
message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake
set( SEXY_LIST ${SEXY_STRING} )
separate_arguments(SEXY_LIST)
message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake
list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3
string(REGEX MATCHALL "[a-zA-Z]+\ |[a-zA-Z]+$" SEXY_LIST "${SEXY_STRING}")
Related
I created a python program and I used import.os... so I want to convert it but not with import.os
can someone help me?
So the main goal is the user to be able to search a path and also to change the file name but i only know the import.os method.
tree.py
import os
import sys
import time
#logo
print("_______ _______________ ______ ___")
print("___ |___ __/__ __ \___ |/ /")
print("__ /| |__ / _ / / /__ /|_/ /")
print("_ ___ |_ / / /_/ / _ / / /")
print("/_/ |_|/_/ \____/ /_/ /_/")
#os.getcwd() Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python.
path = os.chdir('/root')
bl = os.getcwd()
#To change our current working directories in python, we use the chdir() method.
print(os.listdir())
os.chdir(bl)
print("your current location is: ", path)
change = input("Do you want to change your directory (yes/no): ")
if change == "yes":
dir = input("Add new Location: ")
if dir == bl and dir == path:
print("cant go to the same directory")
else:
print("please wait")
time.sleep(2)
os.chdir(dir)
print(os.path.exists(dir))
print(os.getcwd())
prDIR = input("Do you want to print the files (yes/no) : ")
if prDIR == "yes":
for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name.split('-'))
change2 = input("Do you want to change again your DIR: ")
if change2 == "yes":
dir = input("Add a new location: ")
if dir == bl:
print("cant go to the same place")
else:
print("please wait")
time.sleep(1)
os.chdir(dir)
print(os.path.exists(dir))
print(os.getcwd())
print("your current location is: ", path, dir)
pat = input("Do you want to rename this Dir (yes/no) : ")
if pat == "yes":
ch = input("Enter the path but renamed: ")
time.sleep(2)
os.rename(dir, ch)
print(ch)
I get a MissingInputException when I run the following snakemake code:
import re
import os
glob_vars = glob_wildcards(os.path.join(os.getcwd(), "inputs","{fileName}.{ext}"))
rule end:
input:
expand(os.path.join(os.getcwd(), "inputs", "{fileName}_rename.fas"), fileName=glob_vars.fileName)
rule rename:
'''
rename fasta file to avoid problems
'''
input:
expand("inputs/{{fileName}}.{ext}", ext=glob_vars.ext)
output:
os.path.join(os.getcwd(), "inputs", "{fileName}_rename.fas")
run:
list_ = []
with open(str(input)) as f2:
line = f2.readline()
while line:
while not line.startswith('>') and line:
line = f2.readline()
fas_name = re.sub(r"\W", "_", line.strip())
list_.append(fas_name)
fas_seq = ""
line = f2.readline()
while not line.startswith('>') and line:
fas_seq += re.sub(r"\s","",line)
line = f2.readline()
list_.append(fas_seq)
with open(str(output), "w") as f:
f.write("\n".join(list_))
My Inputs folder contains these files:
G.bullatarudis.fasta
goldfish_protein.faa
guppy_protein.faa
gyrodactylus_salaris.fasta
protopolystoma_xenopodis.fa
salmon_protein.faa
schistosoma_mansoni.fa
The error message is:
Building DAG of jobs...
MissingInputException in line 10 of /home/zhangdong/works/NCBI/BLAST/RHB/test.rule:
Missing input files for rule rename:
inputs/guppy_protein.fasta
inputs/guppy_protein.fa
I assumed that the error is caused by expand function, because only guppy_protein.faa file exists, but expand also generate guppy_protein.fasta and guppy_protein.fa files. Are there any solutions?
By default, expand will produce all combinations of the input lists, so this is expected behavior. You need your input to lookup the proper extension given a fileName. I haven't tested this:
glob_vars = glob_wildcards(os.path.join(os.getcwd(), "inputs","{fileName}.{ext}"))
# create a dict to lookup extensions given fileNames
glob_vars_dict = {fname: ex for fname, ex in zip(glob_vars.fileName, glob_vars.ext)}
def rename_input(wildcards):
ext = glob_vars_dict[wildcards.fileName]
return f"inputs/{wildcards.fileName}.{ext}"
rule rename:
input: rename_input
A few unsolicited style comments:
You don't have to prepend your glob_wildcards with the os.getcwd, glob_wildcards("inputs", "{fileName}.{ext}")) should work as snakemake uses paths relative to the working directory by default.
Try to stick with snake_case instead of camalCase for your variable names in python
In this case, fileName isn't a great descriptor of what you are capturing. Maybe species_name or species would be clearer
Thanks to Troy Comi, I modified my code and it worked:
import re
import os
import itertools
speciess,exts = glob_wildcards(os.path.join(os.getcwd(), "inputs_test","{species}.{ext}"))
rule end:
input:
expand("inputs_test/{species}_rename.fas", species=speciess)
def required_files(wildcards):
list_combination = itertools.product([wildcards.species], list(set(exts)))
exist_file = ""
for file in list_combination:
if os.path.exists(f"inputs_test/{'.'.join(file)}"):
exist_file = f"inputs_test/{'.'.join(file)}"
return exist_file
rule rename:
'''
rename fasta file to avoid problems
'''
input:
required_files
output:
"inputs_test/{species}_rename.fas"
run:
list_ = []
with open(str(input)) as f2:
line = f2.readline()
while line:
while not line.startswith('>') and line:
line = f2.readline()
fas_name = ">" + re.sub(r"\W", "_", line.replace(">", "").strip())
list_.append(fas_name)
fas_seq = ""
line = f2.readline()
while not line.startswith('>') and line:
fas_seq += re.sub(r"\s","",line)
line = f2.readline()
list_.append(fas_seq)
with open(str(output), "w") as f:
f.write("\n".join(list_))
If I write a simple Rnw document containing a figure like e.g.,
\documentclass[11pt]{article}
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(dev = "pdf", comment = NA, fig.path = "figure/", fig.align='center', cache=FALSE, message=FALSE, background='white')
options(replace.assign=TRUE,width=85, digits = 8)
knit_hooks$set(fig=function(before, options, envir){if (before) par(mar=c(4,4,.1,.1),cex.lab=.95,cex.axis=.9,mgp=c(2,.7,0),tcl=-.3)})
#
<<prepare-data, include=FALSE>>=
#
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\begin{document}
A simple plot
\begin{figure}
<< scat, echo = FALSE, fig.width = 4.5, fig.height=3>>=
plot(runif(10), runif(10), pch = 20)
#
\end{figure}
\end{document}
Why does knitr create a PDF file with the filename figure/scat-1.pdf instead of figure/scat.pdf?
The reason was explained in the v1.7 release notes. In the development version (to be v1.8), you can use fig_chunk() to obtain the figure filenames (see package NEWS). Also see a related discussion here.
Recently I want to try some open source solvers instead of CPLEX. I found that PICOS + zibopt may be a good choice. However, I can merely find instruction on how to make zibopt work with python under windows properly. I downloaded the windows libraries (.dll file) of scip, and I try to install python-zibopt according to the command "python setup.py install". The error " blockmemshell/memory.h no such file" always popped out. I felt that it is because my compiler, which is VS120COMNTOOL, doecn't find the scip solver. Is there any chance that I can make scip work under windows now?
Did you have a look at the current python interface of SCIP 3.1.0? It uses the library from the SCIP Optimization Suite so you don't have to link another LP solver to SCIP.
On Windows, please try this modified setup.py file:
import sys, os, readline, glob, platform
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
BASEDIR = os.path.dirname(os.path.abspath(__file__))
BASEDIR = os.path.dirname(BASEDIR)
BASEDIR = os.path.dirname(BASEDIR)
INCLUDEDIR = os.path.join(BASEDIR,'src')
BASEDIR = os.path.dirname(BASEDIR)
#identify compiler version
prefix = "MSC v."
i = sys.version.find(prefix)
if i == -1:
raise Exception('cannot determine compiler version')
i = i + len(prefix)
s, rest = sys.version[i:].split(" ", 1)
majorVersion = int(s[:-2]) - 6
minorVersion = int(s[2:3]) / 10.0
if platform.architecture()[0].find('64')>=0:
LIBDIR = os.path.join(BASEDIR,'vc'+str(majorVersion),'scip_spx','x64','Release')
else:
LIBDIR = os.path.join(BASEDIR,'vc'+str(majorVersion),'scip_spx','Release')
print('BASEDIR='+ BASEDIR)
print('INCLUDEDIR='+ INCLUDEDIR)
print('LIBDIR='+ LIBDIR)
def complete(text, state):
return (glob.glob(text+'*')+[None])[state]
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
libscipopt = 'lib/libscipopt.so'
includescip = 'include/scip'
ext_modules = []
ext_modules += [Extension('pyscipopt.scip', [os.path.join('pyscipopt', 'scip.pyx')],
#extra_compile_args=['-g', '-O0', '-UNDEBUG'],
include_dirs=[INCLUDEDIR],
library_dirs=[LIBDIR],
#runtime_library_dirs=[os.path.abspath('lib')],
libraries=['spx', 'scip_spx'])]
#libraries=['scipopt', 'readline', 'z', 'gmp', 'ncurses', 'm'])]
setup(
name = 'pyscipopt',
version = '0.1',
description = 'wrapper for SCIP in Python',
author = 'Zuse Institute Berlin',
author_email = 'scip#zib.de',
license = 'MIT',
cmdclass = {'build_ext' : build_ext},
ext_modules = ext_modules,
packages=['pyscipopt']
)
In the R scripting language, how do I write lines of text, e.g., the following two lines
Hello
World
to a file named "output.txt"?
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
Actually you can do it with sink():
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
hence do:
file.show("outfile.txt")
# hello
# world
I would use the cat() command as in this example:
> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)
You can then view the results from with R with
> file.show("outfile.txt")
hello
world
What's about a simple writeLines()?
txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")
or
txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
I suggest:
writeLines(c("Hello","World"), "output.txt")
It is shorter and more direct than the current accepted answer.
It is not necessary to do:
fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)
Because the documentation for writeLines() says:
If the con is a character string, the function calls file to obtain
a file connection which is opened for the duration of the function
call.
# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.
You could do that in a single statement
cat("hello","world",file="output.txt",sep="\n",append=TRUE)
Short ways to write lines of text to a file in R could be realised with cat or writeLines as already shown in many answers. Some of the shortest possibilities might be:
cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")
In case you don't like the "\n" you could also use the following style:
cat("Hello
World", file="output.txt")
writeLines("Hello
World", "output.txt")
While writeLines adds a newline at the end of the file what is not the case for cat.
This behaviour could be adjusted by:
writeLines("Hello\nWorld", "output.txt", sep="") #No newline at end of file
cat("Hello\nWorld\n", file="output.txt") #Newline at end of file
cat("Hello\nWorld", file="output.txt", sep="\n") #Newline at end of file
But main difference is that cat uses R objects and writeLines a character vector as argument. So writing out e.g. the numbers 1:10 needs to be casted for writeLines while it can be used as it is in cat:
cat(1:10)
writeLines(as.character(1:10))
and cat can take many objects but writeLines only one vector:
cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))
Append to an existing file is easier with cat.
cat("Hello\n", file="output.txt")
cat("World", file="output.txt", append=TRUE)
writeLines("Hello", "output.txt")
CON <- file("output.txt", "a")
writeLines("World", CON)
close(CON)
On the other hand writeLines is faster than cat.
bench::mark(check=FALSE,
writeLines(c("Hello", "World")),
cat("Hello", "World", sep="\n"),
writeLines(c("Hello", "World"), sep=" "),
cat(c("Hello", "World")),
cat("Hello", "World") )
# expression min median `itr/sec` mem_a…¹
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:b>
#1 writeLines(c("Hello", "World")) 2.27µs 4.77µs 163878. 0B
#2 cat("Hello", "World", sep = "\n") 3.83µs 8.51µs 118708. 0B
#3 writeLines(c("Hello", "World"), sep = " ") 1.99µs 4.25µs 235944. 0B
#4 cat(c("Hello", "World")) 4.1µs 6.84µs 141797. 0B
#5 cat("Hello", "World") 3.46µs 7.06µs 129865. 0B
tidyverse edition with pipe and write_lines() from readr
library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")
What about a simple write.table()?
text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)
The parameters col.names = FALSE and row.names = FALSE make sure to exclude the row and column names in the txt, and the parameter quote = FALSE excludes those quotation marks at the beginning and end of each line in the txt.
To read the data back in, you can use text = readLines("output.txt").
To round out the possibilities, you can use writeLines() with sink(), if you want:
> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World
To me, it always seems most intuitive to use print(), but if you do that the output won't be what you want:
...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"
Based on the best answer:
file <- file("test.txt")
writeLines(yourObject, file)
close(file)
Note that the yourObject needs to be in a string format; use as.character() to convert if you need.
But this is too much typing for every save attempt. Let's create a snippet in RStudio.
In Global Options >> Code >> Snippet, type this:
snippet wfile
file <- file(${1:filename})
writeLines(${2:yourObject}, file)
close(file)
Then, during coding, type wfile and press Tab.
The ugly system option
ptf <- function (txtToPrint,outFile){system(paste(paste(paste("echo '",cat(txtToPrint),sep = "",collapse = NULL),"'>",sep = "",collapse = NULL),outFile))}
#Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile
In newer versions of R, writeLines will preserve returns and spaces in your text, so you don't need to include \n at the end of lines and you can write one big chunk of text to a file. This will work with the example,
txt <- "Hello
World"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)
But you could also use this setup to simply include text with structure (linebreaks or indents)
txt <- "Hello
world
I can
indent text!"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)