In my erb file I have this:
"name": "<%= o =*('a'..'z'),*('A'..'Z')
string = o.sample(10).join %>",
That assigns a random generated string as the value to the name element as the key.
It is generating the random string fine but in RubyMine IDE it says
"expected <% or <%= or ;"
at the place of the second "*" in the code? Why is that and how to fix it?
Also more importantly, How can I can a prefix to this generated string? so for example let's say this generates string of abcDef But I need it to be MyPrefix_abcDef
The IDE is correct, there is an error. You need to replace
o =*('a'..'z'),*('A'..'Z')
with
o =[*'a'..'z'] + [*'A'..'Z']
Related
I am trying to get the values in "ID" column of DOORS and I am currently doing this
string ostr=richtext_identifier(o)
When I try to print ostr, in some modules I get just the ID(which is what I want). But in other modules I will get values like "{\rtf1\ansi\ansicpg1256\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Times New Roman;}{\f1\froman\fcharset0 Times New Roman;}} {*\generator Riched20 10.0.17134}\viewkind4\uc1 \pard\f0\fs20\lang1033 SS_\f1\fs24 100\par } " This is the RTF value and I am wondering what the best way is to strip this formatting and get just the value.
Perhaps there is another way to go about this that I am not thinking of as well. Any help would be appreciated.
So the ID column of DOORS is actually a composite- DOORS builds it out of the Module level attribute 'Prefix' and the Object level attribute 'Absolute Number'.
If you wish to grab this value in the future, I would do the following (using your variables)
string ostr = ( module ( o ) )."Prefix" o."Absolute Number" ""
This is opposed to the following, which (despite seeming to be a valid attribute in the insert column dialog) WILL NOT WORK.
string ostr = o."Object Identifier" ""
Hope this helps!
Comment response: You should not need the module name for the code to work. I tested the following successfully on DOORS 9.6.1.10:
Object o = current
string ostr = ( module ( o ) )."Prefix" o."Absolute Number" ""
print ostr
Another solution is to use the identifier function, which takes an Object as input parameter, and returns the identifier as a plain (not RTF) string:
Declaration
string identifier(Object o)
Operation
Returns the identifier, which is a combination of absolute number and module prefix, of object o as a string.
The optimal solution somewhat depends on your underlying requirement for retrieving the object ID.
I have a ruby array like below
tomcats = [
'sandbox',
'sandbox_acserver',
'sandbox_vgw'
]
I need to pass the string as a hash index like below
tomcats.each do |tomcat_name|
obi_tomcat '#{tomcat_name}' do
Chef::Log::info("Creating tomcat instance - #{tomcat_name}")
Chef::Log::info("#{node['obi']['tomcat']['sandbox'][:name]}") // works
Chef::Log::info("#{node['obi']['tomcat']['#{tomcat_name}'][:name]}") // doesn't work
end
end
The last log throws an error since the access with #{tomcat_name} is nil. I'm new to ruby. How do I access with key as the tomcat_name ?
In normal code, you'd write:
node['obi']['tomcat'][tomcat_name][:name]
In a string interpolation (useless here, because it's the only thing in the string in this case), it is completely the same:
"#{node['obi']['tomcat'][tomcat_name][:name]}"
#{} only works in double quote, as "#{tomcat_name}".
But you don't need the syntax here, just use [tomcat_name] directly.
When I saw this question, I'm thinking whether ruby placeholder could be put inside other placeholder in string interpolation. And I found that ruby actually support it, and most interesting thing is that you don't need to escape the " inside the string.
Although it is not very useful in this case, it still works if you write as below:
Chef::Log::info("#{node['obi']['tomcat']["#{tomcat_name}"][:name]}")
Below is an simple example of placeholder inside other placeholder:
tomcats = [
'sandbox',
'sandbox_acserver',
'sandbox_vgw'
]
node = {
'sandbox_name' => "sandbox name",
'sandbox_acserver_name' => "sandbox_acserver name",
'sandbox_vgw_name' => "sandbox_vgw name",
}
tomcats.each do | tomcat |
puts "This is tomcat : #{node["#{tomcat}_name"]}"
end
I am pushing some variables to a httpGet statement and it is failing on any spaces, how can I replace the spaces in the variable with %20 prior to running the GET?
I am trying to encode "felton, ca" which is in the variable from with def fromFormatted = URLEncoder.encode(from, "UTF-8")
and when I run the code I get the error
groovy.lang.MissingMethodException: No signature of method: static java.net.URLEncoder.encode() is applicable for argument types: (org.codehaus.groovy.grails.web.json.JSONArray, java.lang.String) values: [[felton, ca], UTF-8]
original input field
section("Departing From:"){
input "from", "text", title: "Address?"
Also tried def fromFormatted = from.encodeAsURL()
with the result of
%5B%22felton%22%2C%22ca%22%5D
apparently since the input text contained a , then it automatically treated that input text as an array. Any thoughts on keeping this from happening, or converting it to a string and maintaining the comma?
I resolved the array by using def fromStr = from.join(",")
unforunately join creates a json string that adds double quotes
%22felton%22%2C%22ca%22
Is there another method for joining the array that would maintain the comma without adding quotes?
I'm trying to pass more than one regex parameter for parts of a string that needs to be replaced. Here's the string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
Here is the expected string:
str = "stands in hall "Let's go get to first period everyone" Students continue moving to seats."
This is what I tried:
str.gsub(/'|"/, "'" => "\'", """ => "\"")
This is what I got:
"stands in hall \"Let's go get to first period everyone\" Students continue moving to seats."
How do I get the quotes in while sending in two regex parameters using gsub?
This is an HTML unescaping problem.
require 'cgi'
CGI.unescape_html(str)
This gives you the correct answer.
From my comments on this question:
Your updated version is correct. The only reason the slashes are in your final line of code is that it's an escape sequence so that you don't mistakenly think the first slash is used to terminate the string. Try assigning your output and printing it:
str1 = str.gsub(/'|"/, "'" => "\'", """ => "\"")
puts str1
and you'll see that the slashes are gone when str1 is printed using puts.
The difference is that autoevaluating variables within irb (which is what I assume you're doing to execute this sample code) automatically calls the inspect method, which for string variables shows the string in its entirety.
Because I did not understand unescaping characters I found an alternative solution that might be the "rails-way"
Can you use <%= raw 'some_html' %>
My final solution ended up being this instead of messy regex and requiring CGI
<%= raw evidence_score.description %>
Unescaping HTML string in Rails
I'm just starting to pick up ASP.Net MVC and find myself writing a lot of <%= %> in the views. Intellisense does supply the closing %>, but I find that typing the introductory <%= to be burdensome (they are tough for me to type :-)).
I've dabbled around a bit with Rails and the NetBeans IDE where I was able to type:
r<tab> - which would expand to <% %>
and
re<tab> - which would expand to <%= %>
Can something similar be done in the Visual Studio 2008 IDE?
Based on a comment, I double-checked the snippets answer below and it unfortunately doesn't run in HTML view. The other way to do this is via a recorded macro:
In your web project, start recording: CTRL+SHIFT+R
Type <%= %> then return the caret to between the spaces after the "="
Stop recording: CTRL+SHIFT+R
Insert the macro via CTRL+SHIFT+P
That could be enough, but it would be better to have it across all projects, plus we'd like a better keystroke than CTRL+SHIFT+P:
Save the Macro: Tools->Macros->Save Temporary Macro, giving it a name
Bind it to a keystroke combination:
Tools->Options, and choose the Keyboard node
Search for the name you chose
Enter a key combination (e.g. ALT+A) and click OK
Now you can press the key shortcut (e.g. ALT+A) in HTML view, it will insert <%= %>, and position the caret in the tags, ready for input.
[Old Answer: doesn't work in HTML view, unfortunately.]
For a Code Snippet, create an XML snippet file (e.g. "asp.snippet") with the name, shortcut and expansion, then use Tools -> Code Snippet Manager to add the folder where your snippet is stored.
Here's the XML for snippet that (via "asp[tab][tab]"), expands "<%= [code] %>"
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>ASP Server Tags</Title>
<Author>Chris Bowen</Author>
<Shortcut>asp</Shortcut>
<Description>ASP.NET server escape characters, including equals</Description>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>code</ID>
<Default>Code</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[<%= $code$ $selected$%>$end$]]>
</Code>
</Snippet>
</CodeSnippet>
More details are here on MSDN.
BTW, VS has a snippet to create snippets. Just open a new XML file, then right click and choose Insert Snippet -> "Snippet".
This macro function should do it:
The main code will do one of two things, if nothing is selected it will just insert the <%= %> code construct, if you have something currently selected in the editor, it will wrap that code with the construct E.G. <%= selected code here %>
Public Sub WrapMVC()
Try
DTE.UndoContext.Open("Wrap MVC")
Dim OutText As String = ""
Dim OutFormat As String = "<%={0} %>"
DTE.ActiveDocument.Selection.Text = String.Format(OutFormat, ActiveWindowSelection)
Finally
DTE.UndoContext.Close()
End Try
End Sub
Helper Routines:
Friend Function ActiveWindowSelection() As String
If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then
Return OutputWindowSelection()
End If
If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then
Return HTMLEditorSelection()
End If
Return SelectionText(DTE.ActiveWindow.Selection)
End Function
Private Function HTMLEditorSelection() As String
Dim hw As EnvDTE.HTMLWindow = ActiveDocument.ActiveWindow.Object
Dim tw As TextWindow = hw.CurrentTabObject
Return SelectionText(tw.Selection)
End Function
Private Function OutputWindowSelection() As String
Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = w.Object
Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)
Return SelectionText(owp.TextDocument.Selection)
End Function
Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String
If sel Is Nothing Then
Return ""
End If
If sel.Text.Length <= 2 Then
SelectWord(sel)
End If
If sel.Text.Length <= 2 Then
Return ""
End If
Return sel.Text
End Function
Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection)
Dim leftPos As Integer
Dim line As Integer
Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
sel.WordLeft(True, 1)
line = sel.TextRanges.Item(1).StartPoint.Line
leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset
pt.MoveToLineAndOffset(line, leftPos)
sel.MoveToPoint(pt)
sel.WordRight(True, 1)
End Sub
I believe Code Snippets would fit the bill.
I've found it straight forward to write a macro and then bind it to a keyboard command.
I use Tools->Macros->Macro Explorer to see what's there and you can create a new module and add in a macro to inject your code. Then you bind it to a key with Tools->Customize->Keyboard...
Since it's not too different from what you're doing, here is a macro to inject a source command with the date and username - VBScript - I didn't look to hard for other alternatives.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module Module1
Private Function GetUserName() As String
GetUserName = System.Environment.UserName
End Function
Sub InjectChangeComment()
ActiveDocument().Selection().Text = "// " + System.DateTime.Now.ToString("MM-dd-yy") + " " + GetUserName() + vbTab + vbTab + vbTab
End Sub
End Module
Code Snippets in the HTML view do not work. It's slated for the next version of Visual Studio. I'd look at a Macro approach for now, or see if other tools allow for snippets in the HTML editor.
One good tool which will allow you to do this is Resharper. You can create your own templates that will do what you require but also have surround with tags too. There are a whole host of features and is well worth it for the price.