I am trying to remove all spaces from the following string:
howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan
and from the place where there are multiple spaces it is removed only one space and the result is:
replaceAll('\s+', '');
replaceAll('[ ]+', '');
replace(' ', '');
and few more similar expressions.
At the moment I'm using the following source code:
String domain = accountObj.Domain__c;
System.debug('domain ' + domain);
integer spaceInd = domain.indexOf(' ');
System.debug('spaceInd1: ' + spaceInd);
while (spaceInd > -1) {
domain = domain.replace(' ', '');
spaceInd = domain.indexOf(' ');
System.debug('spaceInd: ' + spaceInd);
}
System.debug('domain1 ' + domain);
When I start the code in debug log I get the following:
USER_DEBUG|[198]|DEBUG|domain howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan
USER_DEBUG|[203]|DEBUG|spaceInd1: 75
USER_DEBUG|[207]|DEBUG|spaceInd: -1
USER_DEBUG|[209]|DEBUG|domain1 howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;; ;;;:: :::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan
Could you please advise how to remove all spaces from the String or replace them with a single space in apex?
Regards,
Diyan
Have you tried the deleteWhiteSpace string method?
This unit test passes for me :
#isTest
private class StringTest
{
static testMethod void myStringTest()
{
String test = 'howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan';
String noSpaces = test.deleteWhitespace();
System.assertEquals(noSpaces, 'howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;;;;;:::::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan');
}
}
Related
OK, so the use case here is I am taking a list of FQDN's (one per line) that are in a plain text file and feeding that into a list. The Goal is to iterate through the list and output a static-stub DNS zone statement per list element instance. This is the code I have thus far:
with open('/stubtest.txt') as f:
staticstubs=list(f)
i = 0
while i < len(staticstubs) :
print 'zone ' + '"' + staticstubs[i] + '"' + ' {'
print ' type static-stub;'
print ' server-addresses { 10.10.10.1, 10.10.10.2 };'
print ' };'
print ' '
i += 1
The problem is the format of the output is not correct. I wind up with this:
zone "domain1.com
" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
zone "domain2.com
" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
zone "domain3.net
" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
However, if I define an array statically within the actual script file instead of reading in the file, I get the correct output with the same code:
staticstubs = ["domain1.com", "domain2.com", "domain3.com"]
i = 0
while i < len(staticstubs) :
print 'zone ' + '"' + staticstubs[i] + '"' + ' {'
print ' type static-stub;'
print ' server-addresses { 10.10.10.1, 10.10.10.2 };'
print ' };'
print ' '
i += 1
Static array output:
zone "domain1.com" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
zone "domain2.com" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
zone "domain3.com" {
type static-stub;
server-addresses { 10.10.10.1, 10.10.10.2 };
};
I need to be able to feed the FQDN list file into an array/list and get the same output format as when using the statically defined array. I'm racking my brain on this a bit. Any help would be much appreciated (python version is 2.7.5)
When you read from the file the end of the line has a new line. Try stripping the new line with staticstubs[i].replace("\n", "")
Another option would be to use
f.read().splitlines()
To create the list
In my test script I try to process 100 lines data from csv data feed via following statement:
private val scn = scenario("test_scn").feed(insertFeeder, 100).exec(httpReq)
But I always get an error:
[ERROR] HttpRequestAction - 'httpRequest-1' failed to execute: No attribute named 'name' is defined
Could you please help me to find out the root cause? thank you.
Here is the script:
private val insertFeeder = csv("test_data.csv").queue
private val csvHeader = GeneralUtil.readFirstLine(""test_data.csv"")
private val httpConf = http .baseURL("http://serviceURL") .disableFollowRedirect .disableWarmUp .shareConnections
private var httpReq = http("insert_request") .post("/insert")
for (i <- 0 to 99) {
val paramsInArray = csvHeader.split(",")
for (param <- paramsInArray) {
if (param.equalsIgnoreCase("name")) {
httpReq = httpReq.formParam(("name" + "[" + i +"]").el[String] , "${name}")
}
if (param.equalsIgnoreCase("url")) {
httpReq = httpReq.formParam(("url" + "[" + i +"]").el[String] , "${url}")
}
if (!param.equalsIgnoreCase("name") && !param.equalsIgnoreCase("url")) {
val firstArg = param + "[" + i + "]"
val secondArg = "${" + param + "}"
httpReq = httpReq.formParam(firstArg, secondArg)
}
}
}
private val scn = scenario("test_scn") .feed(insertFeeder, 100) .exec(httpReq)
setUp( scn.inject( constantUsersPerSec(1) during (1200 seconds) ).protocols(httpConf) ).assertions(global.failedRequests.count.lte(5))
And the data in test_data.csv is:
name,url,price,size,gender
image_1,http://image_1_url,100,xl,male
image_2,http://image_2_url,90,m,female
image_3,http://image_3_url,10,s,female
...
image_2000,http://image_2000_url,200,xl,male
By the way, if I process only 1 line, it works well.
Read the document again, and fixed the issue. If feed multiple records all at once, the attribute names will be suffixed from 1.
https://gatling.io/docs/current/session/feeder/#csv-feeders
How to save string to file to specify place ? I use path << 'string' to save, but it give it on end of file. In destination to xml(path) file have </databaseChangeLog>. I want to save to file before that word occurs.
There is java solution click, but it is static line. My file will be dynamic, I don't know with line it will be.
def add_to_version() {
def path = new File('C:/groovy/version-1.xml')
def branchId = "Promt"
def lineCount = 0
def count = path.eachLine { line ->
if(line.contains('<include file="' + branchId + '/' + branchId + '.xml" ')){
wordCount++
}else if(lineCount == 1 ){
println "package is there"
}
}
if(lineCount == 0){
path << '<include file="' + branchId + '/' + branchId + '.xml" ' + 'relativeToChangelogFile="true"/>'
}
}
code above do that :
and I want to get xml like that :
you can use xml parser like this:
def add_to_version(String branchId) {
def path = new File('C:/groovy/version-1.xml')
def xml = new XmlParser().parse(path)
xml.appendNode("include", [
file:"${branchId}/${branchId}.xml",
relativeToChangelogFile:"true"
])
groovy.xml.XmlUtil.serialize(xml, path.newOutputStream())
}
this variant will not keep the xml formatting and comments
however xml will be valid
I am looking for Fortran examples (also interface function) to pass arrays as arguments to lua functions. I was able to use fortlua project to start. But the example provided passes one element at a time. Appreciate any help.
--Lua code
local q1
local q2
function getoutput( qout1, qout2)
-- qout1 and qout2 are arrays with some dimension
q1 = qout1
q2 = qout2
end
-- in fortran I used
config_function('getoutput', args, 2, cstatus)
But setting the args is where I am looking for some help. The following code does the job for scalar argument variable not an array I guess.
!> Evaluate a function in the config file and get its result.
FUNCTION config_function(name,args,nargs,status)
REAL :: config_function
CHARACTER(LEN=*) :: name
REAL, DIMENSION(nargs) :: args
REAL(KIND=c_double) :: anarg
INTEGER :: nargs
INTEGER :: status
INTEGER :: iargs
INTEGER(c_int) :: stackstart
stackstart = lua_gettop(mluastate)
config_function = 0
status = 0
CALL lua_getglobal(mluastate,TRIM(name)//C_NULL_CHAR)
IF ( lua_type(mluastate,-1) .eq. LUA_TFUNCTION ) THEN
DO iargs = 1,nargs
anarg = args(iargs)
CALL lua_pushnumber(mluastate,anarg)
ENDDO
IF (lua_pcall(mluastate,nargs,1,0) .eq. 0) THEN
if (lua_isnumber(mluastate,-1) .ne. 0) THEN
config_function = lua_tonumber(mluastate,-1)
CALL lua_settop(mluastate,-2)
ELSE
! Nothing to pop here
status=-3
ENDIF
ELSE
CALL lua_settop(mluastate,-2)
status=-2
ENDIF
ELSE
CALL lua_settop(mluastate,-2)
status=-1
ENDIF
IF (stackstart .ne. lua_gettop(mluastate)) THEN
WRITE(*,*) 'The stack is a different size coming out of config_function'
ENDIF
END FUNCTION config_function
To expand a little bit on my comment, here is a small program implementing an array argument with the help of Aotus:
program aot_vecarg_test
use flu_binding, only: flu_State, flu_settop
use aotus_module, only: open_config_file, close_config
use aot_fun_module, only: aot_fun_type, aot_fun_do, &
& aot_fun_put, aot_fun_open, &
& aot_fun_close
use aot_references_module, only: aot_reference_for, aot_reference_to_top
use aot_table_module, only: aot_table_open, aot_table_close, &
& aot_table_from_1Darray
implicit none
type(flu_State) :: conf
type(aot_fun_type) :: luafun
integer :: iError
character(len=80) :: ErrString
real :: args(2)
integer :: argref
integer :: arghandle
args(1) = 1.0
args(2) = 2.0
call create_script('aot_vecarg_test_config.lua')
write(*,*)
write(*,*) 'Running aot_vecarg_test...'
write(*,*) ' * open_config_file (aot_vecarg_test_config.lua)'
call open_config_file(L = conf, filename = 'aot_vecarg_test_config.lua', &
& ErrCode = iError, ErrString = ErrString)
if (iError /= 0) then
write(*,*) ' : unexpected FATAL Error occured !!!'
write(*,*) ' : Could not open the config file aot_ref_test_config.lua:'
write(*,*) trim(ErrString)
STOP
end if
write(*,*) ' : success.'
! Create a table with data
call aot_table_from_1Darray( L = conf, &
& thandle = arghandle, &
& val = args )
! Create a reference to this table
call flu_setTop(L = conf, n = arghandle)
argref = aot_reference_for(L = conf)
! Start the processing of the function
call aot_fun_open(L = conf, fun = luafun, key = 'print_array')
! Put the previously defined table onto the stack by using the reference
call aot_reference_to_top(L = conf, ref = argref)
! Put the top of the stack to the argument list of the Lua function
call aot_fun_put(L = conf, fun = luafun)
! Execute the Lua function
call aot_fun_do(L = conf, fun = luafun, nresults = 0)
call aot_fun_close(L = conf, fun = luafun)
write(*,*) ' * close_conf'
call close_config(conf)
write(*,*) ' : success.'
write(*,*) '... Done with aot_vecarg_test.'
write(*,*) 'PASSED'
contains
subroutine create_script(filename)
character(len=*) :: filename
open(file=trim(filename), unit=22, action='write', status='replace')
write(22,*) '-- test script for vectorial argument'
write(22,*) 'function print_array(x)'
write(22,*) ' for i, num in ipairs(x) do'
write(22,*) ' print("Lua:"..num)'
write(22,*) ' end'
write(22,*) 'end'
close(22)
end subroutine create_script
end program aot_vecarg_test
This makes use of a little helping routine aot_table_from_1Darray that creates a Lua table for an array of real numbers. Have a look at its code to see how data can be put into a table.
We then create a reference to this table to easily look it up later on and pass it as an argument to the Lua function.
The example creates the corresponding Lua script itself, which defines a simple function that expects a single table as input and prints each of the tables entries. Running this yields the following output:
Running aot_vecarg_test...
* open_config_file (aot_vecarg_test_config.lua)
: success.
Lua:1.0
Lua:2.0
* close_conf
: success.
... Done with aot_vecarg_test.
PASSED
Where the two lines starting with Lua are written by the Lua function print_array.
There are other possible solutions, but I hope this gives at least some idea on how this could be done. We could also think about extending the aot_fun_put interface to take care of arrays itself.
I'm trying to make a simple Vim script that would create very compact top-level folds for c files. Ideally, if it was run on this code:
static void funca(...)
{
...
}
/* Example comment */
static void funcb(...)
{
...
}
Then it would create folds which would look like this when closed:
+-- x Lines: static void funca(...)----------------------
+-- x Lines: static void funcb(...)----------------------
So basically it would be like foldmethod=syntax with foldlevel=1, except that each fold would start one line further up, and would extend further down to include all following blank lines.
I know how to make one of these folds (assuming foldmethod=manual):
/^{<cr>kVnn?^$<cr>zf
But I'm not sure how to put it into a function. This is my effort:
function Cfold()
set foldmethod=manual " Manual folds
ggzE " Delete all folds
while (/^{<cr>) " Somehow loop through each match
kVnn?^$<cr>zf " This would work fine except for the last function
endwhile
endfunction
map <Leader>f :call Cfold()<cr>
But it isn't valid, I'm not entirely sure how functions work. Also, it won't work for the last function in the file, since it won't find '^{' again. If someone could help me get this working, and somehow add a case for the last function in a file, I would be extremely grateful.
Thanks in advance :)
You can create folds programmatically using the foldexpr and foldtext. Try this, though you may have to tweak CFoldLevel so it doesn't swallow non-function parts of the code:
function! CFoldLevel(lnum)
let line = getline(a:lnum)
if line =~ '^/\*'
return '>1' " A new fold of level 1 starts here.
else
return '1' " This line has a foldlevel of 1.
endif
endfunction
function! CFoldText()
" Look through all of the folded text for the function signature.
let signature = ''
let i = v:foldstart
while signature == '' && i < v:foldend
let line = getline(i)
if line =~ '\w\+(.*)$'
let signature = line
endif
let i = i + 1
endwhile
" Return what the fold should show when folded.
return '+-- ' . (v:foldend - v:foldstart) . ' Lines: ' . signature . ' '
endfunction
function! CFold()
set foldenable
set foldlevel=0
set foldmethod=expr
set foldexpr=CFoldLevel(v:lnum)
set foldtext=CFoldText()
set foldnestmax=1
endfunction
See :help 'foldexpr' for more details.