Regex vs substring,toUpper, toLower, charAt.. etc
what is your creteria for choosing to use a small function of substrings vs doing the same thing with regex?
it seems like from readability and maintainability standpoints (and maybe understandability in some cases) regex should always be used
in my case, i am building a search engine, and for every result the "sniplet text" should always start with a capital letter, and never a symbol.
should i use substrings / toUppercase to accomplish this, or a simple regex?
I dont know what an regex is yet(please fill me in), but I do know that if your gonna do a search engien then you should use equalsIgnoreCase(s) and not toUpperCase or toLowerCase. Also a bit confused about the substring part lol. But I still would recommend to use equalsIgnoreCase(s) as its probably the best way. And I use it on my own page as well..
Also search for parts of the whole word. I guess your gonna make searches against an database in which it should be enough to say: "stri" to find the word "String". If you get what Im saying..
Similar Messages
-
How to use string functions (substr or ltrim or replace) in OLAP universe.
cost element (0COSTELMNT) - 10 CHAR
Controlling area (0CO_AREA) - 4 CHAR
[0COSTELMNT].[LEVEL01].[[20COSTELMNT]].[Value]
cOST ELEMENT is compounded/prefixed with Controlling Area. I just want to see cost element without conrolling area in the BO report.
Currenlty BO unierse is build based on bex query. I am able to suppress the compounding object in bex query by chaning controlling area to 'No display'. But still BO Webi report displaying compounded values in the report. (Bex report works as expected)
eg: Current display in reort.
controlling area/cost element.
AB00/2222
AB00/2223
AB00/2224
Wanted like below:
2222
2223
2224
I think by using string fucntions (substring, ltrim or replace etc.), I can get the required result. But I am having issues with syntax. I have used like below.
substr(0COSTELMNT ; 5 ; 10)
substr(0COSTELMNT; 5 ; Length(0COSTELMNT)-5)
substr(0COSTELMNT; Pos(0COSTELMNT;"/")+1;10)
ltrim(0COSTELMNT,'AB00/')
What is the syntax for substring/replace functions in OLAP universe. Technical name of cost element in OLAP universe is [0COSTELMNT].[LEVEL01].[[20COSTELMNT]].[Value].
I want to fix this at universe level not at report level as i am using cost element in filter/variable section of the report. Please provide me syntax for above example.Hi,
In fact SAP BW MDX supports limited string manipulation and only with NAME and UNIQUENAME attributes.
Here are some samples that you can use in universes:
MID([0COSTELMNT].currentmember.NAME,1,4)
LEFT([0COSTELMNT].currentmember.NAME,2)
RIGHT([0COSTELMNT].currentmember.NAME,3)
MID([0COSTELMNT].currentmember.UNIQUENAME ,1,4)
LEFT([0COSTELMNT].currentmember.UNIQUENAME ,2)
RIGHT([0COSTELMNT].currentmember.UNIQUENAME ,3)
Didier -
Hi all,
I'm trying to get a regular expression used in java to only replace all commas with '#' in a blanket from a specific string.
eg:
original string:"aaa,bbb,to_char(p.sss,'999,999,999.9999') sss,ddd,to_char(eee,'999,999'),fff"
desired output:"aaa,bbb,to_char(p.sss#'999#999#999.9999') sss,ddd,to_char(eee#'999#999'),fff"After some researches,I got this: "(?<=\([^\)]{1,50}),(?=[^\(]{1,100}\))".This one works fine in regex tools such as RegexBuddy..etc..
However the java program(jdk 1.5.0) seems not work correctly:
public static void main(String[] args) {
String str="aaa,bbb,to_char(p.sss,'999,999,999.9999') sss,ddd,to_char(eee,'999,999'),fff";
System.out.println(str);
System.out.println("-------------");
str=str.replaceAll("(?<=\\([^\\)]{1,100}),(?=[^\\(]{1,100}\\))", "#");
System.out.println(str);
}the output still "aaa,bbb,to_char(p.sss,'999,999,999.9999') sss,ddd,to_char(eee,'999,999'),fff"It seems there is something wrong with the "positive lookahead",but as far as I know,java can support this kind of regex: (?<=\\([^\\)]{1,100}?)Any ideas?
Thanks!Right: we consume some of the text with one part of the regex to prevent the other part from seeing it. Here's the breakdown I promised:
With the lookaround approach, we were essentially locating a comma first, then looking backward and forward to figure out whether we should replace it. Since the lookbehind turned out to be unreliable, we need to start matching at some point before the comma, in such a way that all of the ineligible commas either get ignored, or get matched within a capturing group so we can plug them back into the replacement string. The first thing we need to do is match everything up to the first open-parenthesis, because we know we can ignore any commas before that point. As a standalone regex, that part would look like this: "[^(]+\\(" Once we're inside the parens, we can go ahead and match everything up to the next comma. In case we find a set of parentheses with no commas in it, we also add the close-paren to the negated character class: "[^),]+," That works fine for the first match, but it will break down after that because the first part will match everything up to the next open-paren, including the rest of the contents of the first set of parens. That part was meant to fail within parens; that's why it's optional. Since it's required to match an open-paren, and the only way it can reach the next one of those is to match the the intervening close-paren, we can fix it by adding the close-paren to the open-paren in the character class: "[^()]+\\(" And that's all we really need. Once the last comma inside the parens is matched, the first part of the regex takes us up the the next open-paren, where the second part takes over again. The lookbehind turns out not to be necessary once the rest of the regex is properly tuned--it was left over from my earlier attempts to create a working regex. The open-paren in the second character class isn't really needed either, but it doesn't hurt anything and it helps express our intentions. And, as I said earlier, the possessive quantifiers just make the regex a little more efficient. str = str.replaceAll("((?:[^()]++\\()?+[^(),]++),", "$1#"); Although we developed this regex as a replacement for a lookaround-based one, I would encourage everyone to look for non-lookaround solutions first. Despite all the enhancements that have been made to regexes over the years, they still work best when used in a forward-looking, positive-matching style like what we ended up with here. -
Using toString for substring of integer
First post. New to OOP and in my first week of learning Java. Playing around with different class/methods and functions in the API, trying to get a feel for implemetation in code.
Let's say I want to get the length of int iNumber and put it in int iLength. I know I can do this:
iLength = Integer.toString(iNumber).length();
Where Integer.toString(iNumber) creates the string object and then I can invoke the string length method.
Expanding on that, I'm trying to figure out why the compiler is complaining about "incompatible types" on this one (where strTemp is char):
strTemp = Integer.toString(iNumber).substring(1,1);
as well as this, where iTemp is integer:
iTemp = Integer.toString(iNumber).substring(1,1);
Again, total newbie, so apologies if I'm missing something obvious.Or you could have daisy-chained another method.
strTemp = Integer.toString(iNumber).substring(1,1).charAt(0);Or use charAt directly.
strTemp = Integer.toString(iNumber).charAt(0);Also, you should read the API for the substring method and what the parameters do. (1,1) will not produce the results you were expecting. -
Setting text of a JLabel in an array
Hey everyone. Im making a spreadsheet type program, but i have hit a brickwall and for the life of me i can't figure out what is wrong. What i'm trying to do, is check if the input in a cell is in the form e.g "=A3". Then i want the program to goto A3, copy what is in that cell and put it in the active cell. I've done the first bit, which is checking the input is in the form of e.g "=A3" using regex, and that works fine, the actual method doesn't seem to work for me, even though i manage to get the position of A3.
Here is my code:
String s = inputdata.getText();
String regexp = "=[A-Z]{1,2}[1-9]{1}[0-9]*";
if (s.matches(regexp)){
String temp = s.substring(1,2); //extracts the letter from the regex
char letter = temp.charAt(0); //converts the extracted letter to char indirecting using charAt
String temp2 = s.substring(2); //extracts the number from the regex
int number = (int)temp2.charAt(0); //stores the number from the regex in a int variable this is the row number
System.out.println(temp);
System.out.println(temp2);
int ascii = (int)letter; //converts the char letter to its ASCII code
int i = ascii - 64; //gets the number of the column
System.out.println(i);
String textHolder = cell[number].getText(); //gets the text in [row][column] typed in
System.out.println(textHolder);
tempcell.setText(textHolder); //sets the text of the active cell to the contents of the cell reference entered.
}I get an arrayindexoutofbounds error.
i don't see why its an array index out of bounds. My array cells is size [51][31]. Tempcell is the current active cell determined by another method.
Any ideas?
Edited by: kev_x on Apr 30, 2008 6:28 AMWhen you get an index out of bounds error, it tells you what index it tried to access. Like:
ArrayIndexOutOfBoundsException: -1That would mean that you tried to access index -1.
So what does your error tell you? -
Aliases - A question about services which are known by more than one name
If I create a tuxedo alias for an existing service, does the 'original' service simply answer to either name OR does the server end up with one more service than it used to have? i.e does aliasing create a clone.I dont want to discuss the implications of cloning etc, I just want to if a service then bears two name plates or whether I get a clone of a service. I just want to know what the truth is.TIA(I have had two conflicting explanations from experienced developers - nice guys but who is right?)
Allan Moore wrote:
If I create a tuxedo alias for an existing service, does the 'original' service simply answer to either name OR does the server end up with one more service than it used to have? i.e does aliasing create a clone.I dont want to discuss the implications of cloning etc, I just want to if a service then bears two name plates or whether I get a clone of a service. I just want to know what the truth is.TIA(I have had two conflicting explanations from experienced developers - nice guys but who is right?)When you write a service, you write a Function, for example TOUPPER. When you compile the function into a server, you specify a mapping that service TOUPPER will be processed by function TOUPPER. When you boot the server and use the -A option, your telling the server to advertise all services in its mapping table, hence service TOUPPER is advertised. If I use the -s option to alias, then I am overriding the compiled mapping table and dynamically creating a new one. So by saying
-sTOUPPER:TOUPPERV2 I am saying that service TOUPPER will be processed by function TOUPPERV2 (version 2). Whatever was compiled into the server is overridden.
If you put a -A and a -s on the CLOPT line, then things COULD get weird. If I said "-A -sTOUPPER:TOUPPERV2": then I'm saying TOUPPER is processed by both functions TOUPPER and TOUPPERV2. I don't know if this is even legal, and I can't think of a reason to do this. The Tuxedo service table just scans linearly looking for a string match on TOUPPER. Which ever function entry comes first is the function that will be called.
If I said "-A -s TOLOWER:TOUPPER" then I'm adding a new service that uses an existing function. This is very legal, though a little cryptic for administrators. A better choice is "-s TOUPPER,TOLOWER:TOUPPER" so that it is explicit what services the service offers and what function is processing them.
Hope this helps.
Brian Douglass
Transaction Processing Solutions, Inc.
8555 W. Sahara
Suite 112
Las Vegas, NV 89117
Voice: 702-254-5485
Fax: 702-254-9449
e-mail: [email protected] -
I need to delegate adding contacts to clerical staff
Exchange 2013 running on 2012 R2, Windows 8.1 desktops.
We have a Powershell script the domain admins use to add Exchange contacts. It simply asks for the name of the contact, formats the name, adds the user as a contact, and then adds the contact email address to a MessageLabs import file.
I want to hand this off to the same clerical person that sends the email saying, "add Joe Smith - [email protected]".
What permissions (or anything else) does this user need? The script is below. (And even though I have been dabbling in Powershell for years, I feel I still am a Powershell newbie, so any constructive criticism of the script is welcome, knowing I err
on the side of self-documentation over concise - formerly writing in COBOL is a factor here.) :^)
Rob
# add exchange snap-in
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
$today = (get-date).Date
# create messagelabs import file when run on new day
$msglabs = "C:\Users\administrator.MIAT\Desktop\messagelabs.csv"
$lastWriteTime = ((Get-Item $msglabs).LastWriteTime).date
if ($lastWriteTime -ne $today) {New-Item $msglabs -type file -force}
Write-Output "To keep going hit enter, else any key + enter to quit."
$keep_going = ""
do
# get student info interactively
$contact_fname = Read-Host "First name"
$contact_fname = $contact_fname.Trim();
$contact_lname = Read-Host "Last name"
$contact_lname = $contact_lname.Trim();
$contact_forwd = Read-Host "Forward to"
$contact_forwd = $contact_forwd.Trim();
# set up mail alias
$contact_fname = $contact_fname.Substring(0,1).ToUpper()+$contact_fname.Substring(1).ToLower()
$contact_lname = $contact_lname.Substring(0,1).ToUpper()+$contact_lname.Substring(1).ToLower()
$contact_finit = $contact_fname.Substring(0,1)
$contact_cname = $contact_fname + " " + $contact_lname
$contact_alias = $contact_finit + $contact_lname
# create mail contact and messagelabs address record
New-MailContact -ExternalEmailAddress $contact_forwd -Name $contact_cname -Alias $contact_alias -FirstName $contact_fname -Initials '' -LastName $contact_lname
Set-MailContact $contact_forwd -HiddenFromAddressListsEnabled $True
Write-Output (Get-Mailcontact -Filter {DisplayName -eq $contact_cname}).emailaddresses | Select-String "domain.ext"
Add-Content $msglabs ($contact_alias + "@domain.ext")
$keep_going = Read-Host “Keep going?"
while ($keep_going -eq "")
$upload_contacts = read-host "Upload new accounts to filtering service daily. Login to messagelabs, services, platform, upload, browse for messagelabs.csv...hit enter when ready"
# go to the messagelabs web site for uploading the new student email contacts
start "https://clients.messagelabs.com"Martin,
Thank you for your reply - I needed three things to get it to work.
First of all, thank you for your -OrganizationalUnit parameter suggestion. That allowed me to direct the contact to the OU I desired.
I also stumbled across Don Jones' excellent post on implicit vs. explicit remoting:
http://blogs.technet.com/b/heyscriptingguy/archive/2012/01/23/learn-how-to-use-powershell-to-run-exchange-server-commands-remotely.aspx
Using implicit remoting, I was able to get the script to work from a client workstation, without loading any exchange tools on the client, but logged in as an administrator.
And, giving the user Organization Mangement privileges from the Exchange admin center allowed the script to run on the client logged in as the user.
I am very excited about being able to delegate this to the staff.
One question: when I add a user on the exchange server, it returns one line of output; when I do it on the client, I get two full scrolled pages of data. Why the expanded output?
Rob
Here is the new script:
# create implicit remote powershell session on exchange server
$cred = Get-Credential domain\administrator
$session = New-PSSession -ConfigurationName microsoft.exchange -connectionuri http://canexch1/powershell -Credential $cred
Import-PSSession $session
# create messagelabs import file when run on new day
$today = (get-date).Date
$msglabs = "M:\department\admissions\messagelabs.csv"
$lastWriteTime = ((Get-Item $msglabs).LastWriteTime).date
if ($lastWriteTime -ne $today) {New-Item $msglabs -type file -force}
Write-Output "To keep going hit enter, else any key + enter to quit."
$keep_going = ""
do
# get student info interactively
$contact_fname = Read-Host "First name"
$contact_fname = $contact_fname.Trim()
$contact_lname = Read-Host "Last name"
$contact_lname = $contact_lname.Trim()
$contact_forwd = Read-Host "Forward to"
$contact_forwd = $contact_forwd.Trim()
# set up mail alias
$contact_fname = $contact_fname.Substring(0,1).ToUpper()+$contact_fname.Substring(1).ToLower()
$contact_lname = $contact_lname.Substring(0,1).ToUpper()+$contact_lname.Substring(1).ToLower()
$contact_finit = $contact_fname.Substring(0,1)
$contact_cname = $contact_fname + " " + $contact_lname
$contact_alias = $contact_finit + $contact_lname
# create mail contact and messagelabs address record
New-MailContact -ExternalEmailAddress $contact_forwd -Name $contact_cname -Alias $contact_alias -FirstName $contact_fname -LastName $contact_lname -organizationalunit 'domain.local/Student Users and Computers/Forwards'
Set-MailContact $contact_forwd -HiddenFromAddressListsEnabled $True
Write-Output (Get-Mailcontact -Filter {DisplayName -eq $contact_cname}).emailaddresses | Select-String "domain.edu"
Add-Content $msglabs ($contact_alias + "@domain.edu")
$keep_going = Read-Host “Keep going?"
while ($keep_going -eq "")
$upload_contacts = read-host "Upload new accounts to filtering service daily. Login to messagelabs, services, platform, upload, browse for messagelabs.csv...hit enter when ready"
# go to the messagelabs web site for uploading the new student email contacts
start "https://clients.messagelabs.com" -
What the best way to call twenty tuxedo domains from one weblogic server use WTC
I need to call twenty tuxedo domains from one weblogic server use
WTC. the Service be called in the twenty tuxdo domains are same, do I need to
write twenty EJB in the weblogic server to call the same service? who have good
adea to deal with this problem?Hi,
I have a question on the second case. When the client doesn't care of which
Tuxedo domain it is hitting. What happens if one of the Tux domain is down ? What
happens to the client request to that domain ?
Another question is lets say i have a Tuxedo configuration as MP mode( Multi
machine mode) how does WTC load balance between the Tuxedo domains.
Thanks,
Srinivas
"A. Honghsi Lo" <[email protected]> wrote:
Hi xcjing,
One way to handle your needs is to use local service name to remote
reservice name translation. For instance,
(in 6.1,6.0 WLS)
<T_DM_IMPORT ResourceName="TOUPPER1" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM1">
<RemoteName>TOUPPER</RemoteName>
</T_DM_IMPORT>
<T_DM_IMPORT ResourceName="TOUPPER2" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM2">
<RemoteName>TOUPPER</RemoteName>
</T_DM_IMPORT>
<T_DM_IMPORT ResourceName="TOUPPER3" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM3">
<RemoteName>TOUPPER</RemoteName>
</T_DM_IMPORT>
etc
With this configuration if your client have to call "TOUPPER" service
in
TUX-DOM1 then you code your client to call "TOUPPER1" and the request
will be routed to TUX-DOM1. The same way for request has to go to
TUX-DOM3, your client calls "TOUPPER3" service and WTC will route it
to
TUX-DOM3. In this remote name translation you may have to write 20 EJB
although they are almost the same. However, if your EJB can analyze
your client input to decide which Remote Tuxedo Domain to send the
service request to then you probably only need one EJB.
In the case that your client does not care which remote Tuxedo Domain
provides the service then adding
<T_DM_IMPORT ResourceName="TOLOWER" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM1">
<RemoteName>TOLOWER</RemoteName>
</T_DM_IMPORT>
<T_DM_IMPORT ResourceName="TOLOWER" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM2">
<RemoteName>TOLOWER</RemoteName>
</T_DM_IMPORT>
<T_DM_IMPORT ResourceName="TOLOWER" LocalAccessPoint="WTC"
RemoteAccessPointList="TUX-DOM3">
<RemoteName>TOLOWEr</RemoteName>
</T_DM_IMPORT>
etc
Will load balance your client "TOLOWER" service request among your 20
remote Tuxedo Domain.
However, there is a bug in WTC that causes the Remote Service Name
translation functionality not working properly. It is fixed in the
upcoming release of WLS.
Honghsi :-)
xcjing wrote:
Thank you very much! But I still have question, give an example,
twenty Tuxedo domain is named domain1,domain2,....domain20. The
same Tuxedo Service: TOUPPER is deploy on those twenty Tuxedo domains,some time
I need call the TOUPPER Service on domain1,saome time I need call theTOUPPER
Service on domain3 or
other domain depend on the input from client. you mean I need to importThe TOUPPER
Service from twenty Tuxedo domains in the console,then write one EJBto call the
TOUPPER Service,but how can the EJB know which Tuxedo domain's TOUPPERto call
from?
Thank you!
"A. Honghsi Lo" <[email protected]> wrote:
hi xcjing,
You don't have to write 20 beans or deploy 20 beans because there
are
20
remote Tuxedo TDomain you need get the service from. Of course, WLSand
WTC does not prohibit you from doing it though. Whether you need20
beans or not depend more on you architecture.
To access 20 remote Tuxedo Domain from one single WLS with singleWTC
you can configure 20 remote Tuxedo Domain in the BDMCONFIG (6.1,6.0)
or
from the console (7.0). You import 20 services one from each remote
Tuxedo domain. You write one bean, and deploy one bean. Your WLS
clients will be able to access THE ejb, the EJB will access the WTC
service, and WTC will load balanced the service requests among the20
remote Tuxedo Domain.
Regards,
honghsi :-)
xcjing wrote:
I need to call twenty tuxedo domains from one weblogic server use
WTC. the Service be called in the twenty tuxdo domains are same,
do
I need to
write twenty EJB in the weblogic server to call the same service?
who
have good
adea to deal with this problem? -
Conform to SAP address format settings, is there an object or service?
Is there any object or service available that implements the SAP Business One address formatting feature--i.e. we would like to have something that puts the address in the proper format given the following parameters:
Address Format (Code or Name from OADF), street, block, city, county, state, zip, country
Also, how does the system know what address format code to use for the company address (stored in Administration->System Initialization->Company Details)?It was not too tricky:
[code] Dim strSQL As String
Dim strFormat As String
Dim strFormattedAddress As String
Dim str_1_Street As String
Dim str_2_City As String
Dim str_3_PostCode As String
Dim str_4_County As String
Dim str_5_State As String
Dim str_6_Country As String
Dim str_7_Block As String
Dim arr() As String
Dim i As Integer
Dim s As String
With oAddress
str_1_Street = .Street
str_2_City = .City
str_3_PostCode = .ZipCode
str_4_County = .County
str_5_State = .State
str_6_Country = .Country
str_7_Block = .Block
PostalAddress.strCountryCode = .Country
strSQL = "SELECT Format FROM OADF T0 JOIN OCRY T1 ON T0.Code = T1.AddrFormat WHERE T1.Code = '_Country_'"
strSQL = Replace(strSQL, "_Country_", .Country)
gsboRS.DoQuery(strSQL)
If gsboRS.RecordCount = 1 Then
strFormat = gsboRS.Fields.Item(0).Value
If InStr(strFormat, "$6[D") Or InStr(strFormat, "$6[UD") Or InStr(strFormat, "$6[OD") Or InStr(strFormat, "$6[PD") Then
' Get Country Name
str_6_Country = SBOGetBySQL("CountryName", str_6_Country)
End If
If InStr(strFormat, "$5[D") Or InStr(strFormat, "$5[UD") Or InStr(strFormat, "$5[OD") Or InStr(strFormat, "$6[PD") Then
' Get State Name
str_5_State = SBOGetBySQL("StateName", str_5_State)
End If
' UPPERCASE
If InStr(strFormat, "$1[U") Then str_1_Street = str_1_Street.ToUpper
If InStr(strFormat, "$2[U") Then str_2_City = str_2_City.ToUpper
If InStr(strFormat, "$3[U") Then str_3_PostCode = str_3_PostCode.ToUpper
If InStr(strFormat, "$4[U") Then str_4_County = str_4_County.ToUpper
If InStr(strFormat, "$5[U") Then str_5_State = str_5_State.ToUpper
If InStr(strFormat, "$6[U") Then str_6_Country = str_6_Country.ToUpper
If InStr(strFormat, "$7[U") Then str_7_Block = str_7_Block.ToUpper
' lowercase
If InStr(strFormat, "$1[O") Then str_1_Street = str_1_Street.ToLower
If InStr(strFormat, "$2[O") Then str_2_City = str_2_City.ToLower
If InStr(strFormat, "$3[O") Then str_3_PostCode = str_3_PostCode.ToLower
If InStr(strFormat, "$4[O") Then str_4_County = str_4_County.ToLower
If InStr(strFormat, "$5[O") Then str_5_State = str_5_State.ToLower
If InStr(strFormat, "$6[O") Then str_6_Country = str_6_Country.ToLower
If InStr(strFormat, "$7[O") Then str_7_Block = str_7_Block.ToLower
' Capitalized
If InStr(strFormat, "$1[P") Then str_1_Street = str_1_Street.Substring(1, 1).ToUpper & str_1_Street.Substring(2).ToLower
If InStr(strFormat, "$2[P") Then str_2_City = str_2_City.Substring(1, 1).ToUpper & str_2_City.Substring(2).ToLower
If InStr(strFormat, "$3[P") Then str_3_PostCode = str_3_PostCode.Substring(1, 1).ToUpper & str_3_PostCode.Substring(2).ToLower
If InStr(strFormat, "$4[P") Then str_4_County = str_4_County.Substring(1, 1).ToUpper & str_4_County.Substring(2).ToLower
If InStr(strFormat, "$5[P") Then str_5_State = str_5_State.Substring(1, 1).ToUpper & str_5_State.Substring(2).ToLower
If InStr(strFormat, "$6[P") Then str_6_Country = str_6_Country.Substring(1, 1).ToUpper & str_6_Country.Substring(2).ToLower
If InStr(strFormat, "$7[P") Then str_7_Block = str_7_Block.Substring(1, 1).ToUpper & str_7_Block.Substring(2).ToLower
arr = strFormat.Split("$")
For i = 0 To arr.Length - 1
s = arr(i)
If s.StartsWith("1") Then
strFormattedAddress &= str_1_Street & " "
ElseIf s.StartsWith("2") Then
strFormattedAddress &= str_2_City & " "
ElseIf s.StartsWith("3") Then
strFormattedAddress &= str_3_PostCode & " "
ElseIf s.StartsWith("4") Then
strFormattedAddress &= str_4_County & " "
ElseIf s.StartsWith("5") Then
strFormattedAddress &= str_5_State & " "
ElseIf s.StartsWith("6") Then
strFormattedAddress &= str_6_Country & " "
ElseIf s.StartsWith("7") Then
strFormattedAddress &= str_7_Block & " "
ElseIf s.StartsWith("N") Then
strFormattedAddress &= vbCrLf
ElseIf Not s.StartsWith("L") Then
strFormattedAddress &= strFormattedAddress & " "
End If
Next
End If
End With
[/code]
Juha
Message was edited by: Juha Lassila -
Requesting help in extracting user comments from a forum ( HTML WEBSITE)
hello experts,
As i m new to java and i got this college project in hand which has to completed in few days i require some expert advise.
Basically what my job is to extract all the user comments from a forum and make a text file.. for example this is one of the website http://www.gsmarena.com where user have posted many reviews and comments about mobile phones . ex : http://www.gsmarena.com/nokia_n97-reviews-2615p2.php .
now looking at source code , all user comment are inside <P class="uopin"> tag under <DIV class="user-thread"> element.
So i want to ask if there is any method in java that can extract all contents from class "uopin" directly ?
i have no problem opening URL connection and reading the webpage but i m not able to extract that specific content . please enlighten me in this regard.
Actually i m searching this forum since last 3 hours trying to find an answer and i found that i have to learn Regex , indexOf() subString() , HTMLEditorKit() etc.
I ma planning to learn them in detail but as i have very less time ( 2 days to be specific) , i want help from you experts to solve this problem. plz guide me with some code snippets .
Thankyou for your advises in advance :)ok.. sorry for asking that way.
Here is my work till now....
i wrote this code :
import java.io.*;
import java.io.Console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyRobot3
public static void main(String[] args) throws IOException
BufferedReader in = new BufferedReader(new FileReader("MyRobot3.txt"));
String inputLine , nextLine,kutta;
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
out = new FileOutputStream("myfile3.txt");
p = new PrintStream( out );
while ((inputLine = in.readLine()) != null)
Pattern p1 = Pattern.compile("(<p\\sclass=\"uopin\">)(.*$)" );
// Pattern p1 = Pattern.compile("(<p\\sclass=\"uopin\">)(.*$\r\n.*$)" , Pattern.MULTILINE | Pattern.UNIX_LINES); //not working
//Pattern p1 = Pattern.compile("(<p\\sclass=\"uopin\">)(.*\\s)" , Pattern.MULTILINE );
Matcher m1 = p1.matcher(inputLine);
boolean found = false;
while (m1.find())
p.println(m1.group(2));
}I am testing with a little file MyRobot3.txt which contains
<p class="uopin">Although they didn't announce any winner here. But to me the winner is <br/>
N900. Then opera is in second position. (overall averare result)</p>And i am getting output in a file : myfile3.txt
Although they didn't announce any winner here. But to me the winner is <br/>which is just the first line , but i need to match that line break also. i m not able to figure it out .please help me fixing this code so that it can match all the text and remove the <br> tag .. -
I'm a legacy programmer rather new to java. The company I'm working for has decided (finally) to get more involved with the www.
One thing I am working on, is providing customer information online. I'm using the legacy database that currently holds customer info. My problem is that everything is in all caps. How can I make this:
555 MEMORIAL DRIVE
ANYWHERE US 35555-5555
Look like this:
555 Memorial Drive
Anywhere, US 35555-5555
I used the following code for the name, which was relitively easy:
fullName = firstName.charAt(0) + firstName.trim().toLowerCase().substring(1) + " " +
lastName.charAt(0) + lastName.trim().toLowerCase().substring(1);
I'll be continuing my online research but I thought someone here might have some good advice for me.
Thanks in advance for the info!
bfrmbamaRather than using strings, I created a character array and then manipulated the array elements. It seems to have more flexibility. I accomodated all of your example (except the comma following the state, which your code also doesn't handle) and DrClap's suggestion. The handling of the state abbreviation is not pretty, but unless you have some additional information such as positional information, word count location, etc, or an external source to identify state abbreviations, I doubt that much more can be done.
The best solution might be a combination of character array and string processing.
public class AddressFix
public static void main(String[] args)
// sample data
String[] input = new String[2];
input[0] = "555 n. MEMoRiAL dRIVE";
input[1] = "ANYWHERE-viLLE us 35555-5555";
AddressFix addr = new AddressFix();
for (int n = 0; n < input.length; n++)
System.out.println(addr.fixup(input[n]));
String fixup(String in)
String line = in.toLowerCase();
// remove multiple spaces
line = line.replaceAll(" +", " ");
char[] lineArray = line.toCharArray();
char priorChar = ' ';
for (int n = 0; n < lineArray.length; n++)
char letter = lineArray[n];
// this char is a letter
if (Character.isLetter(letter))
// prior char is not a letter
if (!Character.isLetter(priorChar))
lineArray[n] = Character.toUpperCase(letter);
// so, prior char is a letter and if these 2 letters
// are surrounded by spaces, assume a state abbrev.
else if (n > 1 // needed to keep array in bounds
&& n < (lineArray.length - 1) // ditto
&& lineArray[n - 2] == ' '
&& lineArray[n + 1] == ' ')
lineArray[n] = Character.toUpperCase(letter);
priorChar = letter;
return new String(lineArray);
}OUTPUT:
555 N. Memorial Drive
Anywhere-Ville US 35555-5555 -
Hey All,
I have created a runbook to create new user, our company uses last name and first initial for user name, how can I get that generated in a runbook, I tried random text generator but it didn't work. any ideas pleaseHi, best should be to use PowerShell for that, here is a sample Script.
Depends on how you want to create the Username, but should help
<#
.SYNOPSIS
This is a Powershell script to clean up the Sid-History of Users in a specified Organization Unit.
.DESCRIPTION
Parameters:
-Verbose
> Set Verbose to $true for Testing mode
> Set Verbose to $false for Productive mode
> Default Value: $true
-DistinguishedNameOU
> Set DistinguishedNameOU to define the scope
> Default Value: "DC=voestalpine,DC=root,DC=local"
-RecreateDatabaseEntries
> Set RecreateDatabaseEntries to $true for Database Rebuild (necessary after Domain Migration), Duration: approx. 1 Week
By setting RecreateDatabaseEntries to $true all other Parameters will be ignored.
> Set RecreateDatabaseEntries to $false; using existing DatabaseValues
> Default Value: $false
-UserReportLoggingPath
> Set UserReportLoggingPath to change Logging Path for User-Report
> Default Value: "C:\Temp\"
-FullLoggingPath
> Set FullLoggingPath to change Logging Path for User-Report
> Default Value: "C:\Temp\"
.EXAMPLE
Clean SID-History of Users and Groups in OU "OU=Stahl,DC=voestalpine,DC=root,DC=local"
./AD_SID_CleanUP_SCRIPT_V0.2.ps1 -DistinguishedNameOU "OU=Stahl,DC=voestalpine,DC=root,DC=local" -Verbose:$true
Rebuild Database Entries
./AD_SID_CleanUP_SCRIPT_V0.2.ps1 -RecreateDatabaseEntries:$true
#>
##################Section: Parameters###################
#Parameters for Script-Mode:
param(
#[Parameter(Mandatory=$True)]
[string]$OU,
#[Parameter(Mandatory=$True)]
[string]$GivenName="MiChàel",
#[Parameter(Mandatory=$True)]
[string]$LastName="SeiDl",
#[Parameter(Mandatory=$True)]
[ValidateSet("A", "B")]
[string]$Mode,
#[Parameter(Mandatory=$True)]
[string]$Domain="ad.base-it.at",
#[Parameter(Mandatory=$True)]
[string]$FullLoggingPath = "C:\Users\Michael\SkyDrive\3-Work\3 - TECH\Scripts\PowerShell\ActiveDirectory\GetUsername ",
#[Parameter(Mandatory=$True)]
[ValidateSet("Yes", "No")]
[string]$Cleaning = "Yes"
$FullLoggingFileName = "FullLog"+"_"+$GivenName+"_"+$lastname+".txt"
#Settings Mode A
$A_CharLastName=3
$A_CharGivenName=2
$B_CharLastName=3
$B_CharGivenName=2
##################Section: Functions####################
# Function Get-MyModule:
# Function Get-MyModule imports the given $name Module or PSSnapin.
# Return Values:
# $true => success
# $false => error
Function Get-MyModule ($name)
if(-not(Get-Module -name $name))
if(Get-Module -ListAvailable | Where-Object { $_.name -eq $name })
Import-Module -Name $name
return $true
else {
if(-not(Get-PSSnapin | where { $_.Name -eq $name })){
if(Get-PSSnapin -Registered | Where-Object { $_.name -eq $name })
Add-PSSnapin $name
return $true
else{
return $false
else { return $true }
else { return $true }
# Function Write-LogAppendLine ($Text, $Public):
# Function Write-LogAppendLine adds the formated Text to the Log-File ("<current Date> - $F_Text - $F_Value")
# No return Value
function Write-LogAppendLine ($Text, $Public) {
if (!(Test-Path -Path $FullLoggingPath)) {
New-Item -Path $FullLoggingPath -ItemType Directory
if (!(Test-Path -Path $FullLoggingPath\$FullLoggingFileName)) {
New-Item -Path $FullLoggingPath\$FullLoggingFileName -ItemType File
$Datum=Get-Date -format dd.MM.yyyy-HH:mm:ss
$Log="$Datum - $Text"
add-Content -Path $FullLoggingPath\$FullLoggingFileName -Value $Log
if ($Public -eq "Yes") {
Write-Host $Text
if ($Text -match "Error") {
Write-Host "Script stoped"
#exit
# Function Clean-Akzent ($Name):
# Function Clean-Akzent cleans all Names from Akzent
# No return Value
function Clean-Akzent ($Name) {
Try
$Value=$Name.replace('à','a').replace('á','a').replace('é','e').replace('è','e').replace('ó','o').replace('ò','o').replace('ú','u').replace('ù','u').replace('í','i').replace('ì','i')
Write-LogAppendLine "Info: Name cleaned from Akzent => $Value." "Yes"
return $Value
Catch
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-LogAppendLine "Error: Failed on cleaning Akzent." "Yes"
Write-LogAppendLine "Error: Failed Item => $FailedItem" "No"
Write-LogAppendLine "Error: ErrorMessage => $ErrorMessage" "No"
return $false
# Function Clean-Size ($Name):
# Function Clean-Size uppers the first Character and lowers all others
# No return Value
function Clean-Size ($Name) {
Try
$NameArray=$Name.Split(' ')
$givenName=$null
$CountNameArray=1
foreach ($Entry in $NameArray) {
if ($CountNameArray -gt 1) {
$Value+=" "
$Value+=$Entry.Substring(0,1).ToUpper()+$Entry.Substring(1).ToLower()
$CountNameArray++
Write-LogAppendLine "Info: Name cleaned uppere and lower => $Value." "Yes"
return $Value
Catch
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-LogAppendLine "Error: Failed on cleaning Akzent." "Yes"
Write-LogAppendLine "Error: Failed Item => $FailedItem" "No"
Write-LogAppendLine "Error: ErrorMessage => $ErrorMessage" "No"
return $false
# Function Get-Username_A ($LastName, $GivenName):
# Function Get-Username_A
# No return Value
function Get-Username_A ($LastName, $GivenName) {
Try
If ($LastName.length -gt $A_CharLastName) {
$A_LastName = $LastName.ToLower().Substring(0,$A_CharLastName)
else
$A_LastName = $LastName.ToLower()}
If ($GivenName.length -gt $A_CharFirstName) {
$A_GivenName = $GivenName.ToLower().Substring(0,$A_CharGivenName)
else
$A_GivenName = $GivenName.ToLower()
$UsernameOrig="$A_LastName$A_GivenName"
$Username=$UsernameOrig
$Nummer=1
$UserExist=0
while ($UserExist -lt 1) {
if (!(get-aduser -filter {SamAccountName -eq $Username})) {
$UserExist=1
$Value=$Username
Else
$Username=$UsernameOrig+$Nummer
$Nummer++
Write-LogAppendLine "Info: Got a Username => $Value." "Yes"
return $Value
Catch
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-LogAppendLine "Error: Failed on cleaning Akzent." "Yes"
Write-LogAppendLine "Error: Failed Item => $FailedItem" "No"
Write-LogAppendLine "Error: ErrorMessage => $ErrorMessage" "No"
return $false
# Function Get-Username_B ($LastName, $GivenName):
# Function Get-Username_B
# No return Value
function Get_Username_B ($LastName, $GivenName) {
Try
$GivenNameOrig=$GivenName
If ($LastName.length -gt $B_CharLastName) {
$LastName = $LastName.ToLower().Substring(0,$B_CharLastName)
else
$LasTName = $LastName.ToLower()
If ($GivenName.length -gt $B_CharGivenName) {
$GivenName = $GivenName.ToLower().Substring(0,$B_CharGivenName)
else
$GivenName = $GivenName.ToLower()
$UserName="$LastName$GivenName"
$Nummer=1
$UserExist=0
$Length=$givenNameOrig.Length
$Position = 3
$TwoFirstName=$GivenNameOrig.Substring(0,2)
while ($UserExist -lt 1) {
if (!(get-aduser -filter {SamAccountName -eq $Username})) {
$UserExist=1
Else
$UserExist=0
if ($Position -lt $Length) {
$Buchstabe=$givenNameOrig.Substring($Position,1)
$UserName=$LastName+$TwoFirstName+$Buchstabe
$Position++
elseif ($Position -eq $Length) {
$UserName="$LastName$FirstName"
$UserName=$Username.subString(0,$B_CharLastName+$B_CharGivenName)
$UserName=$username+$Nummer
$Nummer++
return $Username.tolower()
Write-LogAppendLine "Info: Got a Username => $Value." "Yes"
#return $Value
Catch
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-LogAppendLine "Error: Failed on cleaning Akzent." "Yes"
Write-LogAppendLine "Error: Failed Item => $FailedItem" "No"
Write-LogAppendLine "Error: ErrorMessage => $ErrorMessage" "No"
return $false
##################Section: Module-Imports/Add-Snappins###############
$CheckModuleImportAD = get-mymodule -name "ActiveDirectory"
if($CheckModuleImportAD){ Write-LogAppendLine "Info: ActiveDirectory-Modul successfully imported." }else{ Write-LogAppendLine "Error: ActiveDirectory-Modul not avaiable." }
##################Section: Magic##################
#Cleaning
if ($Cleaning -eq "yes") {
$GivenName=Clean-Akzent $GivenName
$GivenName=Clean-Size $GivenName
$LastName=Clean-Akzent $LastName
$LastName=Clean-Size $LastName
#Set DisplayName
$Displayname=$LastName+", "+$GivenName
Write-LogAppendLine "Info: Displayname defined => $Displayname." "Yes"
Get-Username_A $LastName $GivenName
Get_Username_B $LastName $GivenName
Seidl Michael | http://www.techguy.at |
twitter.com/techguyat | facebook.com/techguyat -
How to get JSON item in web service workflow?
Im tried to get json item in workflow,But was unable to obtain "RtnCode",how to do it?
This my JSON,
"MerchantID": "1032017",
"RtnCode": "2",
"RtnMsg": "Get Succeeded",
My workflow :
Get RtnCodefrom
Variable: DealItems
Error code:
RequestorId: f85b0795-6682-fde7-0000-000000000000.
Details: An unhandled exception occurred during the execution of the workflow instance.
Exception details: System.InvalidOperationException: Looking up a value using a key is not supported on an instance of 'Microsoft.Activities.Dynamic.DynamicPrimitive'. at Microsoft.Activities.Dynamic.DynamicItem.TryGetValue(String key, DynamicItem&
value) at Microsoft.Activities.Dynamic.DynamicValueBuilder.PathSegmentFactory.ObjectPathSegment.Get(DynamicItem obj) at Microsoft.Activities.GetDynamicValueProperty`1.Execute(CodeActivityContext context) at System.Activities.CodeActivity`1.InternalExecute(ActivityInstance
instance, ActivityExecutor executor, BookmarkManager bookmarkManager) at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation) Exception from activity
GetDynamicValueProperty<String> Start Sequence Flowchart Sequence Pay.WorkflowXaml_07f732da_c82a_4234_abd5_34c32c637413Hi Felaray,
I have a similar issue and what I tried to do is to install JSON.NET in my project and used the "Assign" activity (under "Primitives" category on the toolbox) to assign the string to an object:
Newtonsoft
.Json.JsonConvert.DeserializeObject(resultFromCustomActivity)
but unfortunately did not work. I am getting this exception:
Visual Studio 2013 Workflow: Failed to translate expression because of the following error: Translating the method or one of its overloads to an activity is not supported
If you cannot really change the source header, you might need to create a code custom activity and pass in your string and use JSON.NET, parse it and return what you want.
Another "easier" option might involve doing some nasty parsing (using the Assign Activity) by finding the index of your "RntCode:" and getting the next set of characters before the comma. Since the .NET classes to utilize are limited
it would be worth trying to use a RegEx
resultFromCustomActivity
.Substring(0,
10) -
I have a WHILE statement : "while (s2.substring(k, l) != "<")" that does not work at the bottom of this program. The condition never stops the loop. The JDB does not find any of the fields e. g. PRINT S2
I am doing this in win XP in a DOS window. My CLASSPATH keeps going away for some reason. I set it as CLASSPATH=.;d:\program files\java\jre1.5.0_11\lib\ext\qtjava.zip;c:\program files\java2\java\jdk1.5.0_11
At one time JDB worked with this program. For some reason, now it does not. But the WHILE condition has never worked.
import java.util.*;
import java.io.*;
public class readfile4
public static void main(String args[])
// Here we get a list of all files in the current directory
String list[] = new File(".").list();
for (int i = 0; i < list.length; i++)
// Here we take each file name and read all of its
// records into an array. At this point, we can
// determine the file size since all the rcds are
// in an array.
// If the file size is greater than the original file size
// then it has been updated, so we look at record 4 and get
// the name and display it to a screen.
String s = list.substring(0, 06) ;
int orgsize = 13000 ;
if (s.equals("whats_"))
final int assumedLineLength = 50;
File file = new File(list[i]);
List<String> fileList =
new ArrayList<String>((int)(file.length() / assumedLineLength) * 2);
BufferedReader reader = null;
int lineCount = 0;
try {
reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null;
line = reader.readLine()) {
fileList.add(line);
lineCount++;
} catch (IOException e) {
System.err.format("Could not read %s: %s%n", file, e);
System.exit(1);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {}
// At this point we have the the entire file in an array.
// The above loop has put all the records for the "i" file
// in an array.
// Now, if the filename is "whats_new_....." then extract
// the classmates name out of the 4th record and display it.
// Then return for the next record from the directory list.
String s2 = fileList.get(3) ;
String s2a = s2.substring(0, 5);
String s3 = " " ;
// Only look at title records to get the name
// because some of the html records are
if (s2a.equals("<titl"))
int k = 7 ;
int l = k + 1 ;
while (s2.substring(k, l) != "<")
k++ ;
l++ ;
s3 = s2.substring(7, l) ;
else
s3 = " " ;
if (file.length() > orgsize)
System.out.println(s3 + " - has updated their bio ") ;That condition may very well never be met. Using logical operators (==, !=, etc) to compare strings is a bad idea. Strings are objects, you should compare them with the equals() method.
try
while (!s2.substring(k, l).equals("<")) {
//etc
} -
hi, ^-^, i was programming the Caesar encription method, this one:
import java.io.*;
public class lol {
public static void main (String args[]) throws Exception{
int seleccion, longi, w, x, y, z;
String sel, texto, encrip="";
boolean a=false, b=false;
System.out.print("Enter a text to encript: ");
DataInputStream entrada3 = new DataInputStream(System.in);
texto = entrada3.readLine();
w=1;
z=0;
for(x=1;x==texto.length();x++){
if(texto.substring(z,w)!= (" ")){
encrip = encrip + texto.substring(z,w);
z++;
w++;
} else{
z++;
w++;
w=1;
z=0;
if ((encrip.length()/2)==0){
longi = ((encrip.length()^(1/2))+1);
} else{
longi = ((encrip.length()^(1/2)));
String crip[][] = new String[longi][longi];
texto = "";
for(x=0;x==longi;x++){
for(y=0;y==longi;y++){
crip[y][x]=(encrip.substring(z,w));
w++;
z++;
for(x=0;x==longi;x++){
for(Y=0;y==longi;y++){
texto=texto+crip[x][y];
System.out.println("your ecripted text is: " + texto);
all it do, is: read the text, decompose it, so it dosnt have any spaces, and then, it create an array whit the dimension of the text^1/2 +1 if the text/2==true or the other writted there; then it fills the array (0.0, 1.0, 2.0....,0.1,1.1,...etc), and then it show u the encripted text. My problem here its that the program dosnt go trought any "for bucle" O_o, dunno why.. any help would be apriciated, thx
Message was edited by:
[email protected]I'm sorry but my Babel fish isn't working. bucle == loop (like English buckle, I guess)
@OP:
The second part of a for-loops (bucle) is a condition that must be true.
So you should write//for(x=1;x == texto.length(); x++) { //<-- not this
for(x=1;x < texto.length() + 1; x++) {
// etc
}and the same for the other loops.
Strings are compared using the equals() method, not ==. So//if(texto.substring(z,w)!= (" ")){ // <-- not this
if(!texto.substring(z,w).equals(" ")) {
// etc
}Exponentiation (potencia) in Java does not use the ^ operator, you have
to use Math.pow()//longi = ((encrip.length()^(1/2))); // <-- not this
longi = Math.round(Math.pow((double)encrip.length(), 0.5));longi will be a long, not an int (but can be used the same way in your
code).
Maybe you are looking for
-
In numbers you can add a checkbox that users can toggle off and on. This feature is not available in Pages. Can numbers features/tables be imported into pages or possibly added via Applescript? I haven't found a way to do this.
-
the sound mutes, the bar keeps downloading and "playing" when i go back or pause+play the sound goes back on when im playing a game i have to open chrome because the sound mutes everytime i click anything on the (flash) game im considering moving to
-
Manual cheque lot creation payment document no.
hi , when we work on FCH5, the first feild in payment document no. which we need to type the number, i tried, all the collective number, so that from where system will give the payment document number, or which number we use, thnks,
-
Regarding IR components........
Hi all, Can anyone please send me a blog that gives a detailed explanation about all IR components that are present in a namespace??i mean including fault msg types,context objects,adapter objects etc. Thanks in Advance
-
Since updating to mavericks i can't open ical or text edit
since updating to mavericks i can't open ical or text edit. do i really have to reinstall, will take me 20 hours athome