Add a number to each selection in Sublime Text 2, incremented once per selection - sublimetext2

Is there a way to add insert a number that is incremented once per cursor in Sublime Text 2?
Example, with | as the cursor:
Lorem ipsum dolor sit amet, |
vehicula sed, mauris nam eget|
neque a pede nullam, ducimus adipiscing,
vestibulum pellentesque pellentesque laoreet faucibus.|
Desired result:
Lorem ipsum dolor sit amet, 1|
vehicula sed, mauris nam eget2|
neque a pede nullam, ducimus adipiscing,
vestibulum pellentesque pellentesque laoreet faucibus.3|
Does this functionality exist natively, or is there a plugin providing it?

I recommend the plugin Text Pastry. The Number Sequence command is the one you need.
I prefer to use the Insert Nums command:
Text Pastry has a build in support for the Insert Nums syntax by
providing three numbers separated by one space:
N M P
N: the start index.
M represents the step size which will be added to the index for
each selection.
P must be > 0 and will be used to pad the index with
leading zeroes.

I think that the only way to achieve what you ask is to create your own plugin.
Tools/New Plugin...:
import sublime_plugin
class IncrementSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
start_value = int(self.view.substr(self.view.sel()[0]))
counter = 0
for selection in self.view.sel():
self.view.insert(edit, selection.begin(), str(start_value + counter))
counter = counter + 1
for selection in self.view.sel():
self.view.erase(edit, selection)
Save it in your User directory.
Then add a shortcut to your Key Bindings - User:
{ "keys": ["YOUR_SHORTCUT"], "command": "increment_selection" }
Now you can place the cursors where you need:
Insert the number the counter should start from (in this case 1):
Select the number you typed (shift<—):
Type the shortcut:

You want to had a number at each row that you have selected, but not the same. For exemple, you select 5 cursors and you want to write 1 2 3 4 5.
select your 5 cursors maybe you can use ctrl + maj + L on the highlighted lines
ctrl + maj + P and select arithmetic
Because you have 5 cursors, it propose 1 2 3 4 5
If you want you can change your number of iteration
Or start from an other number than 1
Add odd number

Related

React API call - text with HTML insert doesn't work as code

I make an API call for an element in React using following code:
<div>{props.text}</div>
After receiving the response, it is displayed in a block. What I want to achieve is to insert new line(s) with HTML. I tried using \n, br / and such but it simply displays the text and is not interpreted as code.
Is there any possibility to escape that?
Thanks!
You can apply some javascript logic for this :
Example for splitting a text into separate lines, in each line 8 words :
const str = 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos nobis iure eveniet consequuntur porro, earum culpa amet nesciunt totam, corrupti hic? Iure, animi, ratione '
const str1 = str.split(' ')
const upstr = str1.slice(0,8).join(' ') + '\n' + str1.slice(8,16).join(' ') + '\n' + str1.slice(16,24).join(' ') + '\n'
console.log(upstr)
if you have a big text you can use a for loop

MySQL Insert 1064 Error, what is wrong with the syntax?

Executing SQL script in server
ERROR: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '829-8588, 'magna#Donecnon.com', 'tempus mauris erat eget ipsum. Suspendisse sagi' at line 1
SQL Code:
INSERT INTO `rrm17b`.`member` (`mem_id`, `mem_fname`, `mem_lname`, `mem_street`,
`mem_city`, `mem_state`, `mem_zip`, `mem_phone`, `mem_email`, `mem_notes`)
VALUES (1, 'Eric', 'Prince', '946-6616 Turpis Street', 'Bundaberg',
'Queensland', 33906, (215) 829-8588, 'magna#Donecnon.com',
'tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam.')
SQL script execution finished: statements: 44 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
You have missed the quotes for (215) 829-8588. Since it includes (), it will have to be mentioned in quotes to be considered as single string
Your query input is in the wrong format.
When you type in (215) 829-8588 , the formatting looks as though you have closed the brackets !, hence the error.
try changing the data type of 'mem_phone' to VARCHAR() then input the values in the form of a string.
INSERT INTO rrm17b.member (mem_id,
mem_fname,
mem_lname,
mem_street,
mem_city,
mem_state,
mem_zip,
mem_phone,
mem_email,
mem_notes)
VALUES (1,
'Eric',
'Prince',
'946-6616 Turpis Street',
'Bundaberg',
'Queensland',
33906,
'(215) 829-8588',
'magna#Donecnon.com',
'tempus mauris erat eget ipsum. Suspendisse sagittis. Nullam vitae diam.')

Move line to next section with SublimeText

I'm looking for a way to move a line to the "next section" with SublimeText. It could be in the "next paragraph" if it's text (see below), in the "next node" if it's XML, in the "next code block" if it's code, etc.
Currently I'm using CTRLSHIFTDOWN ARROW many times to move it to the next section, but I think SublimeText might have this feature out-of-the-box.
Example of main use case:
&section1
abcdef
ghijkl <--- if the cursor is in this line, pressing CTRL+DOWN would move this line...
sqfdsdfqsdfjq
&section2 <--- ...here! just between "&section2" and "Lorem".
Lorem ipsum dolor sit amet
&somethingelse <--- one more CTRL+DOWN would move it here
tempor incididunt ut labore et dolore magna aliqua
t enim ad minim veniam
quis nostrud exercitation
I finally managed to write a plugin for this:
# Put this file in "C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\"
# Add this to "C:\Users\User\AppData\Roaming\Sublime Text 2\Packages\User\Default (Windows).sublime-keymap":
# { "keys": ["ctrl+up"], "command": "movesection", "args": {"direction": "up"}},
# { "keys": ["ctrl+down"], "command": "movesection", "args": {"direction": "down"}}
import sublime, sublime_plugin
import subprocess
class MovesectionCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
# select current line, save it and delete it
currentcursor = self.view.sel()[0].begin()
thisline = self.view.substr(self.view.full_line(currentcursor))
self.view.erase(edit, self.view.full_line(currentcursor))
# find the next/previous & and move there
if direction == 'down':
beg = self.view.sel()[0].begin()
end = self.view.size()
else:
beg = 0
end = self.view.sel()[0].begin()
contents = self.view.substr(sublime.Region(beg, end)) # https://stackoverflow.com/questions/20182008/sublime-text-3-api-get-all-text-from-a-file
offset = contents.find('&') if direction == 'down' else contents.rfind('&', 0, contents.rfind('&')) # down: first occurence, up: second-to-last occurence
cursors = self.view.sel()
cursors.clear()
location = sublime.Region(beg+offset, beg+offset)
cursors.add(location)
# move to the next line
(row, col) = self.view.rowcol(self.view.sel()[0].begin()) # go to the next line
self.view.run_command("goto_line", {"line": row+2})
# insert the text here
self.view.insert(edit, self.view.sel()[0].begin(), thisline)
# move to the line currently pasted (because of inserting the line usually including \n, it would go to next line, thus the following code is needed)
(row, col) = self.view.rowcol(self.view.sel()[0].begin())
self.view.run_command("goto_line", {"line": row})

Limiting JSON Response in Swift 4

This may seem like a noob question but I'm receiving a response from the Wikipedia API and sometimes, depending on what the request is, the response of the image description is way too long. This is what I have for this particular request.
let imageDescription = imageJSON["query"]["pages"][pageid]["extract"].stringValue
I'd like to limit it to 50 words. Any suggestions?
One simple way to do this is to break the string up into an array of separate words, limit the array to 50 items, and then put the array back together. You could achieve this like so:
var imageDescription = imageJSON["query"]["pages"][pageid]["extract"].stringValue
imageDescription = imageDescription.components(separatedBy: " ").prefix(50).joined(separator: " ")
Do not split a string by space or punctuations in hope of getting the words. Some languages (such as Chinese and Japanese) do not separate the words by space. See this article for details.
func takeFirst(words wordCount: Int, in str: String) -> String {
let fullRange = str.startIndex..<str.endIndex
var count = 0
var substr: Substring = ""
str.enumerateSubstrings(in: fullRange, options: .byWords) { _, _, enclosingRange, stop in
count += 1
if enclosingRange.upperBound == fullRange.upperBound || count >= wordCount {
substr = str[str.startIndex..<enclosingRange.upperBound]
stop = true
}
}
return String(substr)
}
let imageDescription = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pulvinar semper sapien, sit amet feugiat risus pulvinar a. Sed in aliquam sem. Nullam lacinia sagittis ipsum, et congue lectus pulvinar quis. Vestibulum elementum mattis feugiat. Nam velit elit, facilisis non ipsum vel, ornare aliquam velit. Curabitur hendrerit ante sed odio porttitor, pellentesque molestie sapien eleifend. Etiam porttitor fermentum egestas. Cras dui justo, vulputate non porta sed, congue eu lacus."
let shortImageDescription = takeFirst(words: 5, in: imageDescription)
print(shortImageDescription)
Another example in Chinese to illustrate the point:
let imageDescription = "今天你好吗?" // first two characters form one word: "today"
// third character is its own word: "you"
// fourth chasracter is its own word: "well"
// fifth character is its own word" "huh"
let shortImageDescription = takeFirst(words: 3, in: imageDescription) // 今天你好

Remove quotes from a json object value

I am using Woocommerce API in node js to import product data from mssql server db to my woocommerce database.
The recordset, I am getting through ms sql query, contains a images field.
In Woocommerce API, to import images I need this type of json object,
var data = {
product: {
title: 'Premium Quality',
type: 'simple',
regular_price: '21.99',
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.',
short_description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
categories: [
9,
14
],
**images: [
{
src: 'http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg',
position: 0
},**
{
src: 'http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg',
position: 1
}
]
}
};
Rest is fine, but I have issue with images, As I am getting images json in quotes images: '[{...}]' as the data type is varchar in db table.
Because of this quotes, Images are not inserting in db through Woocommerce rest API.
I want to remove the quote from images specifically. Or any other suggestion.
I am new to node js. Can any one please help.
As far as I understood you problem is you are getting extra "" at the start and end of a string which specifies the image location.
You just have to chop of the first & last character of your string variable in js.
Solution:
var x = String(/'[{...}]'/);
str = x.substring(1, x.length - 1);
var image = str.substring(1, str.length - 1);
Demo :
function myFunction() {
var x = String(/'[{...}]'/);
str = x.substring(1, x.length - 1);
var res = str.substring(1, str.length - 1);
document.getElementById("demo").innerHTML = res;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
OR
Demo:
Remove "" from start and end of string :
var someStr = String('[{...}]');
alert(someStr)
alert(someStr.replace(/^"(.*)"$/, '$1'));
var someStr = String('"[{...}]"');
alert(someStr)
alert(someStr.replace(/^"(.*)"$/, '$1'));
OR
var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, ""));
Refer : remove-double-quotes-from-json-return-data and Can you create a JavaScript string without using ' or " quotes?