How to reformat long line of array in WebStorm - webstorm

I have a long list of the array defined in the JavaScript file as follows:
const array = ['a', 'b', 'c', ..................]
The length of the line is more than 80 character. I tried to reformat the code using the Code | Reformat code menu item, but the formatter didn't split the code into multiple lines.
What I expect is reformatted change the code to the following.
const array = [
'a',
'b',
'c',
...
];
How could I do it?

in Preferences > Editor > Code Style > JavaScript > Wrappings and Braces, set Arrays to Wrap if long (or Chop down if long) and set Hard wrap at value to 80

Related

Convert a set of numbers into a word

I need to convert a given string of numbers to the word those numbers correspond to. For example:
>>>number_to_word ('222 2 333 33')
'CAFE'
The numbers work like they do on a cell phone, you hit once on the second button and you get an 'A', you hit twice and you get an 'B', etc. Let's say I want the letter 'E', I'd have to press the third button twice.
I would like to have some help trying to understand the easiest way to do this function. I have thought on creating a dictionary with the key being the letter and the value being the number, like this:
dic={'A':'2', 'B':'22', 'C':'222', 'D':'3', 'E':'33',etc...}
And then using a 'for' cycle to read all the numbers the in the string, but I do not know how to start.
You need to reverse your dictionary:
def number_to_word(number):
dic = {'2': 'A', '22': 'B', '222': 'C', '3': 'D', '33': 'E', '333': 'F'}
return ''.join(dic[n] for n in number.split())
>>> number_to_word('222 2 333 33')
'CAFE'
Let's start inside out. number.split() splits the text with your number at white space characters:
>>> number = '222 2 333 33'
>>> number.split()
['222', '2', '333', '33']
We use a generator expression ((dic[n] for n in number.split())) to find the letter for each number. Here is a list comprehension that does nearly the same but also shows the result as a list:
>>> [dic[n] for n in number.split()]
['C', 'A', 'F', 'E']
This lets n run through all elements in the list with the numbers and uses n as the key in the dictionary dic to get the corresponding letter.
Finally, we use the method join() with an empty string as spectator to turn the list into a string:
>>> ''.join([dic[n] for n in number.split()])
'CAFE'

F# Use result of boolean function in if statement

I'm trying to write a pig latin translator in F#. To translate, I need to know if a word starts with a vowel or not. To do that, I'm trying to use this function which I wrote...
(*Tests if an element is in a list*)
let isInList elementToFind listToCheck =
List.fold(fun a b -> a || b = elementToFind) false listToCheck;
to test if the first character in a word is in a list of all vowels. Here is what my attempt looks like
(*Takes a word and translates it to pig latin*)
let translateWord wordToTranslate : string =
let startsWithVowel = isInList(wordToTranslate.[0], ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']);
if startsWithVowel then
translateWordStartingWithVowel(wordToTranslate)
else
translateWordStartingWithConsenant(wordToTranslate);
Which is giving several errors. It's saying wordToTranslate.[0] doesn't have enough type constrants and startsWithVowel is of the wrong type. The full error texts are
Severity Code Description Project File Line
Error The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints Pig Latin FSharp
Severity Code Description Project File Line
Error This expression was expected to have type
bool
but here has type
('a * (char * char * char * char * char * char * char * char * char * char) list) list -> bool Pig Latin FSharp
How can I fix this approach so that it does what I want it to do? I'm relatively new to F# so any help would be greatly appreciated!
You need parenthesis in the type annotation, otherwise it applies to the return value, not parameter:
let translateWord (wordToTranslate : string) = ...
You do not need parenthesis and commas when passing arguments to isInList function. To separate elements of a list use ; instead of , (, is used to separate elements of a tuple).
let startsWithVowel = isInList wordToTranslate.[0] ['A'; 'E'; 'I'; 'O'; 'U'; 'a'; 'e'; 'i'; 'o'; 'u']
That will fix the compilation errors.
By the way, the following is cleaner, faster and will give you the same results:
let startsWithVowel = Seq.contains wordToTranslate.[0] "AEIOUaeiou"

Multilevel list natural sort with regexp

Here is an example of data:
'1.' 'Numeric types'
'1.1.' 'Integer'
'1.2.' 'Float'
...
'1.10' 'Double'
To naturally sort it we can use string_to_array with '.' as separator, then cast text[] to int[] and sort by integer array, but since the field itself is of type text and there might be cases where user decides to use non-numeric symbols, e.g. 1.1.3a, thus causing cast error.
To address that I decided to use regexp:
select regexp_matches('1.2.3.4.', E'(?:(\\d+)\.?)+')
Expected result is array: {'1', '2', '3', '4'} but instead i get only the last element of the said array, however, if I use following regexp:
select regexp_matches('1.2.3.4.', E'((?:\\d+)\.?)+')
The result is {'1.2.3.4.'}.
Using global-flag 'g' is not an option, because regexp_matches returns a column.
Is there any way to convert '1.2.3.4a.'::text to {1, 2, 3 ,4}::int[] using only one regexp_matches?
Fiddle.
You can use the global 'g' flag with regexp_matches, but needs to aggregate values to an array (most simple with the array() constructor):
select array(select m[1] from regexp_matches(dt_code, '(\d+)', 'g') m)::int[] nums, *
from data_types
order by 1;
Or, you can split your string to array with string_to_array(), but you still need to use regexp to remove any non-numeric characters:
select string_to_array(trim(regexp_replace(dt_code, '[^\d\.]+', ''), '.'), '.')::int[] nums, *
from data_types
order by 1;
For a more advanced natural-like sorting, you need to split your text to tokens yourself. See more info at the related SO question.
I could come up with a simplified, reusable function:
create or replace function natural_order_tokens(text)
returns table (
txt text,
num int,
num_rep text
)
language sql
strict
immutable
as $func$
select m[1], (case m[2] when '' then '0' else m[2] end)::int, m[2]
from regexp_matches($1, '(\D*)(\d*)', 'g') m
where m[1] != '' or m[2] != ''
$func$;
With this function, natural sorting will be this easy:
select *
from data_types
order by array(select t from natural_order_tokens(dt_code) t);
SQLFiddle

Perform multiple search-and-replaces on the colnames of a dataframe

I have a dataframe with 95 cols and want to batch-rename a lot of them with simple regexes, like the snippet at bottom, there are ~30 such lines. Any other columns which don't match the search regex must be left untouched.
**** Example: names(tr) = c('foo', 'bar', 'xxx_14', 'xxx_2001', 'yyy_76', 'baz', 'zzz_22', ...) ****
I started out with a wall of 25 gsub()s - crude but effective:
names(tr) <- gsub('_1$', '_R', names(tr))
names(tr) <- gsub('_14$', '_I', names(tr))
names(tr) <- gsub('_22$', '_P', names(tr))
names(tr) <- gsub('_50$', '_O', names(tr))
... yada yada
#Joshua: mapply doesn't work, turns out it's more complicated and impossible to vectorize. names(tr) contains other columns, and when these patterns do occur, you cannot assume all of them occur, let alone in the exact order we defined them. Hence, try 2 is:
pattern <- paste('_', c('1','14','22','50','52','57','76','1018','2001','3301','6005'), '$', sep='')
replace <- paste('_', c('R','I', 'P', 'O', 'C', 'D', 'M', 'L', 'S', 'K', 'G'), sep='')
do.call(gsub, list(pattern, replace, names(tr)))
Warning messages:
1: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'pattern' has length > 1 and only the first element will be used
2: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'replacement' has length > 1 and only the first element will be used
Can anyone fix this for me?
EDIT: I read all around SO and R doc on this subject for over a day and couldn't find anything... then when I post it I think of searching for '[r] translation table' and I find xlate. Which is not mentioned anywhere in the grep/sub/gsub documentation.
Is there anything in base/gsubfn/data.table etc. to allow me to write one search-and-replacement instruction? (like a dictionary or translation table)
Can you improve my clunky syntax to be call-by-reference to tr? (mustn't create temp copy of entire df)
EDIT2: my best effort after reading around was:
The dictionary approach (xlate) might be a partial answer to, but this is more than a simple translation table since the regex must be terminal (e.g. '_14$').
I could use gsub() or strsplit() to split on '_' then do my xlate translation on the last component, then paste() them back together. Looking for a cleaner 1/2-line idiom.
Or else I just use walls of gsub()s.
Wall of gsub could be always replace by for-loop. And you can write it as a function:
renamer <- function(x, pattern, replace) {
for (i in seq_along(pattern))
x <- gsub(pattern[i], replace[i], x)
x
}
names(tr) <- renamer(
names(tr),
sprintf('_%s$', c('1','14','22','50','52','57','76','1018','2001','3301','6005')),
sprintf('_%s' , c('R','I', 'P', 'O', 'C', 'D', 'M', 'L', 'S', 'K', 'G'))
)
And I found sprintf more useful than paste for creation this kind of strings.
The question predates the boom of the tidyverse but this is easily solved with the c(pattern1 = replacement1) option in stringr::str_replace_all.
tr <- data.frame("whatevs_1" = NA, "something_52" = NA)
tr
#> whatevs_1 something_52
#> 1 NA NA
patterns <- sprintf('_%s$', c('1','14','22','50','52','57','76','1018','2001','3301','6005'))
replacements <- sprintf('_%s' , c('R','I', 'P', 'O', 'C', 'D', 'M', 'L', 'S', 'K', 'G'))
names(replacements) <- patterns
names(tr) <- stringr::str_replace_all(names(tr), replacements)
tr
#> whatevs_R something_C
#> 1 NA NA
And of course, this particular case can benefit from dplyr
dplyr::rename_all(tr, stringr::str_replace_all, replacements)
#> whatevs_R something_C
#> 1 NA NA
Using do.call() nearly does it, it objects to differing arg lengths. I think I need to nest do.call() inside apply(), like in apply function to elements over a list.
But I need a partial do.call() over pattern and replace.
This is all starting to make a wall of gsub(..., fixed=TRUE) look like a more efficient idiom, if flabby code.
pattern <- paste('_', c('1','14','22','50'), '$', sep='')
replace <- paste('_', c('R','I', 'P', 'O'), sep='')
do.call(gsub, list(pattern, replace, names(tr)))
Warning messages:
1: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'pattern' has length > 1 and only the first element will be used
2: In function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE, :
argument 'replacement' has length > 1 and only the first element will be used

Help in interpreting a c++ method

I have the following c++ method:
typedef unsigned long p3tOffsetType;
p3tOffsetType buildString(std::string string)
{
for (stringMap::const_iterator string_iterator = strings.begin(); string_iterator != strings.end(); ++string_iterator)
{
if (string_iterator->second == string)
return string_iterator->first;
}
p3tOffsetType new_string_offset = string_offset;
strings[string_offset] = string;
string_offset += string.size() + 1;
return new_string_offset;
}
What does the function do? I can give more of the code if needed.
The code is a snippet from a P3T file packer found in the source P3TBuilder (version 2.7).
I need to know this because I am trying to
Assuming that strings is a map<p3tOffsetType, std::string> and that string_offset is initialized to zero, it seems to do the following: Imagine that you call the method a few times with, say, "Hello", "Hi", and "Hey", and that you would treat all these strings as C-strings and store them in the same char array. The array elements would then be {'H', 'e', 'l', 'l', 'o', '\0', 'H', 'i', '\0', 'H', 'e', 'y', '\0'}. The starting indices of the three strings are 0, 6, and 9, respectively. What the method does is to create a map that maps these starting indices to the strings, so strings[0] == "Hello", strings[6] == "Hi", and strings[9] == "Hey". Also, it eliminates duplicates, so calling the method again with "Hello" would leave the map unchanged.
It iterates over strings which is a map from p3tOffsetType to string. If the sought after string is found in the map then it returns the offset. If not then it stores the string with the current offset as key and adds the length of the string to the global variable string_offset (which I assume initialized to zero).
Basically, a map of strings and their offsets is built. So if you called it with "Hello", "test" and "bla" it would contain the following:
strings[0] = "Hello"
strings[6] = "test"
strings[11] = "bla"
This keeps track of the strings and where they are located in the "bigger" string, so to speak.