Expand selection to custom line - sublimetext2

I am wondering if there is a out of the box way, or a plugin that can achieve the following behaviour in SublimeText3.
I would like to put the caret at a certain line. And then select all the text until another line number. The amount of lines should be variable.
For example put the caret on 10 and then expand selection to line 21 or line 104.
I hate having to hold down key or use the mouse for this action.

I wrote a simple plugin that allows you to enter a line to select until via an input_panel:
Features:
works bidirectionally
respects the current selection
only executes if there is a single selection
Setup Info:
# GitHub
Code:
import sublime, sublime_plugin
class SelectToLineCommand( sublime_plugin.TextCommand ):
def run( self, edit ):
window = self.view.window()
selections = self.view.sel()
if len( selections ) != 1:
return
self.currentSelection = selections[0]
if self.currentSelection.a > self.currentSelection.b:
self.currentSelection = sublime.Region( self.currentSelection.b, self.currentSelection.a )
window.show_input_panel( "Select To Line Number", "", self.get_LineNumber, None, None )
def get_LineNumber( self, userInput ):
lineToRow_Offset = 1
row = int( userInput ) - lineToRow_Offset
selectionEnd_Row = self.view.text_point( row, 0 )
currentSelection = self.currentSelection
if selectionEnd_Row >= currentSelection.b:
selectionStart = currentSelection.a
selectionEnd = self.view.line( selectionEnd_Row ).b
elif selectionEnd_Row < currentSelection.a:
selectionStart = currentSelection.b
selectionEnd = self.view.line( selectionEnd_Row ).a
newSelection = sublime.Region( selectionStart, selectionEnd )
self.view.selection.clear()
self.view.selection.add( newSelection )

Related

Django queryset update migration

I'm trying to optimize a migration, it's taking too long, about 15 minutes every time you try to run it, because there is a lot of data on this table. It's an old database that have dates like this '14102019' (%d%m%Y) as String, and need to convert them to DateField. I created a DateField for both.
Database is MySQL.
dtobito and dtnasc are the old strings that need to be converted
data_obito and data_nasc are the new DateFields
What works (very slowly):
def date_to_datefield(apps, schema_editor):
Obitos = apps.get_model('core', 'Obitos')
for obito in Obitos.objects.all():
if obito.dtnasc and obito.dtnasc != '':
obito.data_nasc = datetime.strptime(obito.dtnasc, '%d%m%Y')
if obito.dtobito and obito.dtobito != '':
obito.data_obito = datetime.strptime(obito.dtobito, '%d%m%Y')
obito.save()
What doesn't work:
Obitos.objects.update(
data_nasc=datetime.strptime(F('dtnasc'), '%d%m%Y'),
data_obito=datetime.strptime(F('dtobito'), '%d%m%Y')
)
What could work, but I don't know how:
Obitos.objects.raw("""
UPDATE obitos new,
(
SELECT
STR_TO_DATE(dtnasc, '%d%m%Y') AS dtnasc,
STR_TO_DATE(dtobito, '%d%m%Y') AS dtobito,
FROM obitos
) old
SET new.data_nasc = old.dtnasc
SET new.data_obtio = old.dtobito
""")
Try using bulk_update:
def date_to_datefield(apps, schema_editor):
Obitos = apps.get_model('core', 'Obitos')
objs = []
def to_date_object(date_string):
return datetime.strptime(date_string, '%d%m%Y')
for obito in Obitos.objects.all():
updated = False
if obito.dtnasc:
obito.data_nasc = to_date_object(obito.dtnasc)
updated = True
if obito.dtobito:
obito.data_obito = to_date_object(obito.dtobito)
updated = True
if updated:
objs.append(obito)
if objs:
Obitos.objects.bulk_update(objs, ['data_nasc', 'data_obito'])

Odoo 12 Confirmation form (confirm/ discard) from Wizard

I created a wizard in account.invoice form who is displayed when user click on "confirm bill".
This wizard contain two buttons: discard and confirm.
When user click on confirm button the bill is created.
How to save fields of the "account.invoice" view from the confirm button of the wizard?
I hope you can help me.
this is the confirm function of the wizard:
#api.multi
def action_invoice_validation(self):
invoice = self.env['account.invoice'].search([('id', '=', self._context['parent_obj'])])
to_open_invoices = self.filtered(lambda inv: invoice.state != 'open')
to_open_invoices.action_move_creation()
return to_open_invoices.invoice_validation()
Below the two functions called in my principal function
action_move_creation function:
#api.multi
def action_move_creation(self):
""" Creates invoice related analytics and financial move lines """
account_move = self.env['account.move'].search([('id', '=', self._context['parent_obj'])])
for inv in self:
if not inv.date_invoice:
inv.write({'date_invoice': fields.Date.context_today(self)})
if not inv.date_due:
inv.write({'date_due': inv.date_invoice})
company_currency = inv.company_id.currency_id
# create move lines (one per invoice line + eventual taxes and analytic lines)
iml = inv.invoice_line_move_line_get()
iml += inv.tax_line_move_line_get()
diff_currency = inv.currency_id != company_currency
# create one move line for the total and possibly adjust the other lines amount
total, total_currency, iml = inv.compute_invoice_totals(company_currency, iml)
name = inv.name or ''
if inv.payment_term_id:
totlines = \
inv.payment_term_id.with_context(currency_id=company_currency.id).compute(total, inv.date_invoice)[
0]
res_amount_currency = total_currency
for i, t in enumerate(totlines):
if inv.currency_id != company_currency:
amount_currency = company_currency._convert(t[1], inv.currency_id, inv.company_id,
inv._get_currency_rate_date() or fields.Date.today())
else:
amount_currency = False
# last line: add the diff
res_amount_currency -= amount_currency or 0
if i + 1 == len(totlines):
amount_currency += res_amount_currency
iml.append({
'type': 'dest',
'name': name,
'price': t[1],
'account_id': inv.account_id.id,
'date_maturity': t[0],
'amount_currency': diff_currency and amount_currency,
'currency_id': diff_currency and inv.currency_id.id,
'invoice_id': inv.id
})
else:
iml.append({
'type': 'dest',
'name': name,
'price': total,
'account_id': inv.account_id.id,
'date_maturity': inv.date_due,
'amount_currency': diff_currency and total_currency,
'currency_id': diff_currency and inv.currency_id.id,
'invoice_id': inv.id
})
part = self.env['res.partner']._find_accounting_partner(inv.partner_id)
line = [(0, 0, self.line_get_convert(l, part.id)) for l in iml]
line = inv.group_lines(iml, line)
line = inv.finalize_invoice_move_lines(line)
date = inv.date or inv.date_invoice
move_vals = {
'ref': inv.reference,
'line_ids': line,
'journal_id': inv.journal_id.id,
'date': date,
'narration': inv.comment,
}
move = account_move.create(move_vals)
# Pass invoice in method post: used if you want to get the same
# account move reference when creating the same invoice after a cancelled one:
move.post(invoice=inv)
# make the invoice point to that move
vals = {
'move_id': move.id,
'date': date,
'move_name': move.name,
}
inv.write(vals)
return True
my invoice_validation function:
#api.multi
def invoice_validation(self):
invoice = self.env['account.invoice'].search([('id', '=', self._context['parent_obj'])])
for invoice in self.filtered(lambda p: invoice.partner_id not in invoice.message_partner_ids):
invoice.message_subscribe([invoice.partner_id.id])
# Auto-compute reference, if not already existing and if configured on company
if not create_uidinvoice.reference and invoice.type == 'out_invoice':
invoice.reference = invoice._get_computed_reference()
# DO NOT FORWARD-PORT.
# The reference is copied after the move creation because we need the move to get the invoice number but
# we need the invoice number to get the reference.
invoice.move_id.ref = invoice.reference
self._check_duplicate_supplier_reference()
return self.write({'state': 'open'})

Tkinter dropdown menu from SQL table

Instead of having a user input "Job Name", I want it to be a Tkinter drop down menu.
Im guessing the idea will be to append Jobname with the list of names from Table. How will it have it show in the tkinter dropdown?
Jobname = []
...
for row in rows:
data = "%s %s %s %s %s" % (row["Id"], row["Title"], row["Date"], row["Time"], row["Duration"])
movieList.append(data)
print data
My Code
def reportdata():
clear()
w11 = Label(fr, text="Job Name : ")
w11.grid(row=1, column=0)
listlab.append(w11)
w22 = Label(fr, text="Job Start Date: ")
w22.grid(row=2, column=0)
listlab.append(w22)
w33 = Label(fr, text="Job End Date: ")
w33.grid(row=3, column=0)
listlab.append(w33)
e11 = Entry(fr, textvariable=jjname)
e11.grid(row=1, column=1)
listlab.append(e11)
e22 = Entry(fr, textvariable=jjdates)
e22.grid(row=2, column=1)
listlab.append(e22)
e33 = Entry(fr, textvariable=jjdatee)
e33.grid(row=3, column=1)
listlab.append(e33)
mbuttonn = Button(fr, text="Generate", command=savexl)
mbuttonn.grid(row=4, column=3)
listlab.append(mbuttonn)
Please see below for an example of how you can use a list to populate a tkinter OptionMenu:
from tkinter import *
root = Tk()
a = [] #creates a list to store the job names in
var = StringVar() #creates a stringvar to store the value of options
for i in range(20): #fills list with nonsense jobs for troubleshooting
a.append("Job Name "+str(i))
var.set(a[0]) #sets the default option of options
options = OptionMenu(root, var, *a) #createa an optionmenu populated with every element of the list
button = Button(root, text="Ok", command=lambda:print(var.get())) #prints the current value of options
options.pack()
button.pack()
This uses a list to fill out an OptionMenu with all of it's elements, then we create a button which prints the current value of the OptionMenu.
If you can get your SQL imported data into a list you can use the same logic as above.

Can you highlight a character after a certain length in sublime text?

In VIM it is possible to highlight a character only if the line goes over a certain length, for example:
Can this be done in Sublime Text 2 or 3? I know there's a setting to display rulers but I find them a bit distracting sometimes.
javiervd
Can this be done in Sublime Text 2 or 3?
Save the following script #:
/Packages/Highlight Long Lines/highlight_long_lines.py
import sublime, sublime_plugin
class highlight_long_lines( sublime_plugin.EventListener ):
def on_modified_async( self, view ):
#▒▒▒▒▒▒▒▒ Settings ▒▒▒▒▒▒▒▒#
maxLength = 80
scope = "Invalid"
firstCharacter_Only = False
view.erase_regions( "LongLines" )
indentationSize = view.settings().get( "tab_size" )
indentation_IsSpace = view.settings().get( "translate_tabs_to_spaces" )
document = sublime.Region( 0, view.size() )
lineRegions = view.lines( document )
invalidRegions = []
for region in lineRegions:
text = view.substr( region )
text_WithoutTabs = text.expandtabs( indentationSize )
if text_WithoutTabs.isspace():
tabOffset = 0
else:
tabCount = text.count( " " )
tabDifference = len( text_WithoutTabs ) - len( text )
tabOffset = tabDifference
lineLength = ( region.end() - region.begin() ) - tabOffset
if lineLength > maxLength:
highlightStart = region.begin() + ( maxLength - tabOffset )
if firstCharacter_Only == True:
highlightEnd = highlightStart + 1
else:
highlightEnd = region.end()
invalidRegion = sublime.Region( highlightStart, highlightEnd )
invalidRegions.append( invalidRegion )
if len( invalidRegions ) > 0:
view.add_regions( "LongLines", invalidRegions, scope )
Variable Settings:
maxLength affects the length that lines will highlight after.
scope affects the color of the highlighted regions.
You can use any scope from your active .tmTheme file ( color scheme ).
firstCharacter_Only affects the extent of the highlighted regions.
If set to True, only the character at the 81st position will be highlighted.
If set to False, all characters after the 80th position will be highlighted.
You could just search for this regular expression:
(?<=.{80}).+
It would be navigable and on-demand.
You can extend(copy-rename and use) the syntax highlight and add a rule with this specific case!
you can add a regex similar to this:
<key>charAt</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>match</key>
<string>(?<=^.{21})(.)</string>
<key>name</key>
<string>invalid.illegal.bad-comments-or-CDATA.html</string>
</dict>
</array>
</dict>
where 21 is the position to highlight

Object of type 'closure' is not subsettable - R

I am using R to extract tweets and analyse their sentiment, however when I get to the lines below I get an error saying "Object of type 'closure' is not subsettable"
scores$drink = factor(rep(c("east"), nd))
scores$very.pos = as.numeric(scores$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
Full code pasted below
load("twitCred.Rdata")
east_tweets <- filterStream("tweetselnd.json", locations = c(-0.10444, 51.408699, 0.33403, 51.64661),timeout = 120, oauth = twitCred)
tweets.df <- parseTweets("tweetselnd.json", verbose = FALSE)
##function score.sentiment
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
# Parameters
# sentences: vector of text to score
# pos.words: vector of words of postive sentiment
# neg.words: vector of words of negative sentiment
# .progress: passed to laply() to control of progress bar
scores = laply(sentences,
function(sentence, pos.words, neg.words)
{
# remove punctuation
sentence = gsub("[[:punct:]]", "", sentence)
# remove control characters
sentence = gsub("[[:cntrl:]]", "", sentence)
# remove digits?
sentence = gsub('\\d+', '', sentence)
# define error handling function when trying tolower
tryTolower = function(x)
{
# create missing value
y = NA
# tryCatch error
try_error = tryCatch(tolower(x), error=function(e) e)
# if not an error
if (!inherits(try_error, "error"))
y = tolower(x)
# result
return(y)
}
# use tryTolower with sapply
sentence = sapply(sentence, tryTolower)
# split sentence into words with str_split (stringr package)
word.list = str_split(sentence, "\\s+")
words = unlist(word.list)
# compare words to the dictionaries of positive & negative terms
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
# get the position of the matched term or NA
# we just want a TRUE/FALSE
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
# final score
score = sum(pos.matches) - sum(neg.matches)
return(score)
}, pos.words, neg.words, .progress=.progress )
# data frame with scores for each sentence
scores.df = data.frame(text=sentences, score=scores)
return(scores.df)
}
pos = readLines(file.choose())
neg = readLines(file.choose())
east_text = sapply(east_tweets, function(x) x$getText())
scores = score.sentiment(tweetseldn.json, pos, neg, .progress='text')
scores()$drink = factor(rep(c("east"), nd))
scores()$very.pos = as.numeric(scores()$score >= 2)
scores$very.neg = as.numeric(scores$score <= -2)
# how many very positives and very negatives
numpos = sum(scores$very.pos)
numneg = sum(scores$very.neg)
# global score
global_score = round( 100 * numpos / (numpos + numneg) )
If anyone could help with as to why I'm getting this error it will be much appreciated. Also I've seen other answeres about adding '()' when referring to the variable 'scores' such as scores()$.... but it hasn't worked for me. Thank you.
The changes below got rid of the error:
x <- scores
x$drink = factor(rep(c("east"), nd))
x$very.pos = as.numeric(x$score >= 2)
x$very.neg = as.numeric(x$score <= -2)