code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
return self.filter(
recipient=user,
recipient_deleted_at__isnull=False,
) | self.filter(
sender=user,
sender_deleted_at__isnull=False,
) | def trash_for(self, user) | Returns all messages that were either received or sent by the given
user and are marked as deleted. | 3.016013 | 2.908628 | 1.036919 |
message_list = Message.objects.inbox_for(request.user)
return render(request, template_name, {
'message_list': message_list,
}) | def inbox(request, template_name='django_messages/inbox.html') | Displays a list of received messages for the current user.
Optional Arguments:
``template_name``: name of the template to use. | 2.241618 | 3.202492 | 0.699961 |
message_list = Message.objects.outbox_for(request.user)
return render(request, template_name, {
'message_list': message_list,
}) | def outbox(request, template_name='django_messages/outbox.html') | Displays a list of sent messages by the current user.
Optional arguments:
``template_name``: name of the template to use. | 2.146446 | 3.181024 | 0.674766 |
message_list = Message.objects.trash_for(request.user)
return render(request, template_name, {
'message_list': message_list,
}) | def trash(request, template_name='django_messages/trash.html') | Displays a list of deleted messages.
Optional arguments:
``template_name``: name of the template to use
Hint: A Cron-Job could periodicly clean up old messages, which are deleted
by sender and recipient. | 2.460102 | 3.419579 | 0.719417 |
if request.method == "POST":
sender = request.user
form = form_class(request.POST, recipient_filter=recipient_filter)
if form.is_valid():
form.save(sender=request.user)
messages.info(request, _(u"Message successfully sent."))
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
return HttpResponseRedirect(success_url)
else:
form = form_class()
if recipient is not None:
recipients = [u for u in User.objects.filter(**{'%s__in' % get_username_field(): [r.strip() for r in recipient.split('+')]})]
form.fields['recipient'].initial = recipients
return render(request, template_name, {
'form': form,
}) | def compose(request, recipient=None, form_class=ComposeForm,
template_name='django_messages/compose.html', success_url=None, recipient_filter=None) | Displays and handles the ``form_class`` form to compose new messages.
Required Arguments: None
Optional Arguments:
``recipient``: username of a `django.contrib.auth` User, who should
receive the message, optionally multiple usernames
could be separated by a '+'
``form_class``: the form-class to use
``template_name``: the template to use
``success_url``: where to redirect after successfull submission | 2.169824 | 2.197441 | 0.987432 |
parent = get_object_or_404(Message, id=message_id)
if parent.sender != request.user and parent.recipient != request.user:
raise Http404
if request.method == "POST":
sender = request.user
form = form_class(request.POST, recipient_filter=recipient_filter)
if form.is_valid():
form.save(sender=request.user, parent_msg=parent)
messages.info(request, _(u"Message successfully sent."))
if success_url is None:
success_url = reverse('messages_inbox')
return HttpResponseRedirect(success_url)
else:
form = form_class(initial={
'body': quote_helper(parent.sender, parent.body),
'subject': subject_template % {'subject': parent.subject},
'recipient': [parent.sender,]
})
return render(request, template_name, {
'form': form,
}) | def reply(request, message_id, form_class=ComposeForm,
template_name='django_messages/compose.html', success_url=None,
recipient_filter=None, quote_helper=format_quote,
subject_template=_(u"Re: %(subject)s"),) | Prepares the ``form_class`` form for writing a reply to a given message
(specified via ``message_id``). Uses the ``format_quote`` helper from
``messages.utils`` to pre-format the quote. To change the quote format
assign a different ``quote_helper`` kwarg in your url-conf. | 2.022231 | 2.157322 | 0.93738 |
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
deleted = False
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
if message.sender == user:
message.sender_deleted_at = now
deleted = True
if message.recipient == user:
message.recipient_deleted_at = now
deleted = True
if deleted:
message.save()
messages.info(request, _(u"Message successfully deleted."))
if notification:
notification.send([user], "messages_deleted", {'message': message,})
return HttpResponseRedirect(success_url)
raise Http404 | def delete(request, message_id, success_url=None) | Marks a message as deleted by sender or recipient. The message is not
really removed from the database, because two users must delete a message
before it's save to remove it completely.
A cron-job should prune the database and remove old messages which are
deleted by both users.
As a side effect, this makes it easy to implement a trash with undelete.
You can pass ?next=/foo/bar/ via the url to redirect the user to a different
page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message. | 2.216578 | 2.119594 | 1.045756 |
user = request.user
message = get_object_or_404(Message, id=message_id)
undeleted = False
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
if message.sender == user:
message.sender_deleted_at = None
undeleted = True
if message.recipient == user:
message.recipient_deleted_at = None
undeleted = True
if undeleted:
message.save()
messages.info(request, _(u"Message successfully recovered."))
if notification:
notification.send([user], "messages_recovered", {'message': message,})
return HttpResponseRedirect(success_url)
raise Http404 | def undelete(request, message_id, success_url=None) | Recovers a message from trash. This is achieved by removing the
``(sender|recipient)_deleted_at`` from the model. | 2.226223 | 2.109319 | 1.055422 |
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
if (message.sender != user) and (message.recipient != user):
raise Http404
if message.read_at is None and message.recipient == user:
message.read_at = now
message.save()
context = {'message': message, 'reply_form': None}
if message.recipient == user:
form = form_class(initial={
'body': quote_helper(message.sender, message.body),
'subject': subject_template % {'subject': message.subject},
'recipient': [message.sender,]
})
context['reply_form'] = form
return render(request, template_name, context) | def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote,
subject_template=_(u"Re: %(subject)s"),
template_name='django_messages/view.html') | Shows a single message.``message_id`` argument is required.
The user is only allowed to see the message, if he is either
the sender or the recipient. If the user is not allowed a 404
is raised.
If the user is the recipient and the message is unread
``read_at`` is set to the current datetime.
If the user is the recipient a reply form will be added to the
tenplate context, otherwise 'reply_form' will be None. | 2.09982 | 2.00365 | 1.047998 |
lines = wrap(body, 55).split('\n')
for i, line in enumerate(lines):
lines[i] = "> %s" % line
quote = '\n'.join(lines)
return ugettext(u"%(sender)s wrote:\n%(body)s") % {
'sender': sender,
'body': quote
} | def format_quote(sender, body) | Wraps text at 55 chars and prepends each
line with `> `.
Used for quoting messages in replies. | 2.984327 | 2.625784 | 1.136547 |
subject_prefix_re = r'^Re\[(\d*)\]:\ '
m = re.match(subject_prefix_re, subject, re.U)
prefix = u""
if subject.startswith('Re: '):
prefix = u"[2]"
subject = subject[4:]
elif m is not None:
try:
num = int(m.group(1))
prefix = u"[%d]" % (num+1)
subject = subject[6+len(str(num)):]
except:
# if anything fails here, fall back to the old mechanism
pass
return ugettext(u"Re%(prefix)s: %(subject)s") % {
'subject': subject,
'prefix': prefix
} | def format_subject(subject) | Prepends 'Re:' to the subject. To avoid multiple 'Re:'s
a counter is added.
NOTE: Currently unused. First step to fix Issue #48.
FIXME: Any hints how to make this i18n aware are very welcome. | 3.880856 | 3.497305 | 1.10967 |
if default_protocol is None:
default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
except Exception as e:
#print e
pass | def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
template_name="django_messages/new_message.html",
default_protocol=None,
*args, **kwargs) | This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
``default_protocol``: default protocol in site URL passed to template | 2.078345 | 2.268301 | 0.916256 |
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v1/reference-data/locations/{0}'
.format(self.location_id), **params) | def get(self, **params) | Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed | 4.122308 | 2.142902 | 1.923703 |
'''
A helper function for making generic POST requests calls. It is used by
every namespaced API method. It can be used to make any generic API
call that is automatically authenticated using your API credentials:
.. code-block:: python
amadeus.request('GET', '/foo/bar', airline='1X')
:param verb: the HTTP verb to use
:paramtype verb: str
:param path: path the full path for the API call
:paramtype path: str
:param params: (optional) params to pass to the API
:paramtype params: dict
:rtype: amadeus.Response
:raises amadeus.ResponseError: when the request fails
'''
return self._unauthenticated_request(
verb, path, params,
self.__access_token()._bearer_token()
) | def request(self, verb, path, **params) | A helper function for making generic POST requests calls. It is used by
every namespaced API method. It can be used to make any generic API
call that is automatically authenticated using your API credentials:
.. code-block:: python
amadeus.request('GET', '/foo/bar', airline='1X')
:param verb: the HTTP verb to use
:paramtype verb: str
:param path: path the full path for the API call
:paramtype path: str
:param params: (optional) params to pass to the API
:paramtype params: dict
:rtype: amadeus.Response
:raises amadeus.ResponseError: when the request fails | 6.778641 | 1.787275 | 3.792724 |
'''
Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v2/shopping/hotel-offers/{0}'
.format(self.offer_id), **params) | def get(self, **params) | Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed | 4.490731 | 2.265836 | 1.981931 |
if self.currently_buffering_typechecks:
for note in payload['notes']:
self.buffered_notes.append(note) | def buffer_typechecks(self, call_id, payload) | Adds typecheck events to the buffer | 7.940947 | 6.757747 | 1.175088 |
self.buffer_typechecks(call_id, payload)
self.editor.display_notes(self.buffered_notes) | def buffer_typechecks_and_display(self, call_id, payload) | Adds typecheck events to the buffer, and displays them right away.
This is a workaround for this issue:
https://github.com/ensime/ensime-server/issues/1616 | 7.130761 | 6.845202 | 1.041717 |
self.log.debug('handle_typecheck_complete: in')
if not self.currently_buffering_typechecks:
self.log.debug('Completed typecheck was not requested by user, not displaying notes')
return
self.editor.display_notes(self.buffered_notes)
self.currently_buffering_typechecks = False
self.buffered_notes = [] | def handle_typecheck_complete(self, call_id, payload) | Handles ``NewScalaNotesEvent```.
Calls editor to display/highlight line notes and clears notes buffer. | 5.761065 | 4.89474 | 1.176991 |
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client)
if client and client.running:
return f(self, client, *args, **kwargs)
return wrapper2
return wrapper | def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True) | Decorator that gets a client and performs an operation on it. | 2.918473 | 2.700589 | 1.08068 |
gkey = "ensime_{}".format(key)
return self._vim.vars.get(gkey, default) | def get_setting(self, key, default) | Returns the value of a Vim variable ``g:ensime_{key}``
if it is set, and ``default`` otherwise. | 10.709979 | 3.856401 | 2.777195 |
c = self.client_for(config_path)
status = "stopped"
if not c or not c.ensime:
status = 'unloaded'
elif c.ensime.is_ready():
status = 'ready'
elif c.ensime.is_running():
status = 'startup'
elif c.ensime.aborted():
status = 'aborted'
return status | def client_status(self, config_path) | Get status of client for a project, given path to its config. | 4.19438 | 4.119249 | 1.018239 |
current_file = self._vim.current.buffer.name
config_path = ProjectConfig.find_from(current_file)
if config_path:
return self.client_for(
config_path,
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client) | def current_client(self, quiet, bootstrap_server, create_client) | Return the client for current file in the editor. | 3.921142 | 3.338516 | 1.174517 |
client = None
abs_path = os.path.abspath(config_path)
if abs_path in self.clients:
client = self.clients[abs_path]
elif create_client:
client = self.create_client(config_path)
if client.setup(quiet=quiet, bootstrap_server=bootstrap_server):
self.clients[abs_path] = client
return client | def client_for(self, config_path, quiet=False, bootstrap_server=False,
create_client=False) | Get a cached client for a project, otherwise create one. | 2.343274 | 2.221341 | 1.054892 |
config = ProjectConfig(config_path)
editor = Editor(self._vim)
launcher = EnsimeLauncher(self._vim, config)
if self.using_server_v2:
client = EnsimeClientV2(editor, launcher)
else:
client = EnsimeClientV1(editor, launcher)
self._create_ticker()
return client | def create_client(self, config_path) | Create an :class:`EnsimeClient` for a project, given its config file path.
This will launch the ENSIME server for the project as a side effect. | 5.792971 | 4.934412 | 1.173994 |
for path in self.runtime_paths():
self._vim.command('set runtimepath-={}'.format(path)) | def disable_plugin(self) | Disable ensime-vim, in the event of an error we can't usefully
recover from.
Todo:
This is incomplete and unreliable, see:
https://github.com/ensime/ensime-vim/issues/294
If used from a secondary thread, this may need to use threadsafe
Vim calls where available -- see :meth:`Editor.raw_message`. | 20.45816 | 19.986416 | 1.023603 |
if plugin in path:
paths.append(os.path.expanduser(path))
return paths | def runtime_paths(self): # TODO: memoize
runtimepath = self._vim.options['runtimepath']
plugin = "ensime-vim"
paths = []
for path in runtimepath.split(',') | All the runtime paths of ensime-vim plugin files. | 6.97784 | 3.574863 | 1.951918 |
if not self._ticker:
self._create_ticker()
for client in self.clients.values():
self._ticker.tick(client) | def tick_clients(self) | Trigger the periodic tick function in the client. | 4.986058 | 4.373972 | 1.139938 |
if isinstance(findstart_and_base, list):
# Invoked by neovim
findstart = findstart_and_base[0]
base = findstart_and_base[1]
else:
# Invoked by vim
findstart = findstart_and_base
return client.complete_func(findstart, base) | def fun_en_complete_func(self, client, findstart_and_base, base=None) | Invokable function from vim and neovim to perform completion. | 2.857401 | 2.247985 | 1.271094 |
if afterline:
self._vim.current.buffer.append(text, afterline)
else:
self._vim.current.buffer.append(text) | def append(self, text, afterline=None) | Append text to the current buffer.
Args:
text (str or Sequence[str]): One or many lines of text to append.
afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the
first line; if ``None``, at end of the buffer. | 2.679399 | 3.417922 | 0.783926 |
return self._vim.current.buffer[lnum] if lnum else self._vim.current.line | def getline(self, lnum=None) | Get a line from the current buffer.
Args:
lnum (Optional[str]): Number of the line to get, current if ``None``.
Todo:
- Give this more behavior of Vim ``getline()``?
- ``buffer[index]`` is zero-based, this is probably too confusing | 4.075628 | 5.870386 | 0.694269 |
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
return buf[:] | def getlines(self, bufnr=None) | Get all lines of a buffer as a list.
Args:
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
Returns:
List[str] | 4.337203 | 5.175525 | 0.838022 |
row = self._vim.eval('byte2line({})'.format(point))
col = self._vim.eval('{} - line2byte({})'.format(point, row))
return (int(row), int(col)) | def point2pos(self, point) | Converts a point or offset in a file to a (row, col) position. | 5.635231 | 4.252621 | 1.32512 |
menu = [prompt] + [
"{0}. {1}".format(*choice) for choice in enumerate(choices, start=1)
]
command = 'inputlist({})'.format(repr(menu))
choice = int(self._vim.eval(command))
# Vim returns weird stuff if user clicks outside choices with mouse
if not 0 < choice < len(menu):
return
return choices[choice - 1] | def menu(self, prompt, choices) | Presents a selection menu and returns the user's choice.
Args:
prompt (str): Text to ask the user what to select.
choices (Sequence[str]): Values for the user to select from.
Returns:
The value selected by the user, or ``None``.
Todo:
Nice opportunity to provide a hook for Unite.vim, etc. here. | 6.385257 | 7.026821 | 0.908698 |
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
# Special case handling for filetype, see doc on ``set_filetype``
filetype = options.pop('filetype', None)
if filetype:
self.set_filetype(filetype)
for opt, value in options.items():
buf.options[opt] = value | def set_buffer_options(self, options, bufnr=None) | Set buffer-local options for a buffer, defaulting to current.
Args:
options (dict):
Options to set, with keys being Vim option names. For Boolean
options, use a :class:`bool` value as expected, e.g.
``{'buflisted': False}`` for ``setlocal nobuflisted``.
bufnr (Optional[int]):
A Vim buffer number, as you might get from VimL ``bufnr('%')``
or Python ``vim.current.buffer.number``. If ``None``, options
are set on the current buffer. | 3.696261 | 3.570821 | 1.035129 |
if bufnr:
self._vim.command(str(bufnr) + 'bufdo set filetype=' + filetype)
else:
self._vim.command('set filetype=' + filetype) | def set_filetype(self, filetype, bufnr=None) | Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
bufnr (Optional[int]): A Vim buffer number, current if ``None``. | 4.012634 | 4.683179 | 0.856818 |
command = 'split {}'.format(fpath) if fpath else 'new'
if vertical:
command = 'v' + command
if size:
command = str(size) + command
self._vim.command(command)
if bufopts:
self.set_buffer_options(bufopts) | def split_window(self, fpath, vertical=False, size=None, bufopts=None) | Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size (Optional[int]): The height (or width) to set for the new window.
bufopts (Optional[dict]): Buffer-local options to set in the split window.
See :func:`.set_buffer_options`. | 3.973402 | 3.628285 | 1.095118 |
cmd = 'noautocmd write' if noautocmd else 'write'
self._vim.command(cmd) | def write(self, noautocmd=False) | Writes the file of the current buffer.
Args:
noautocmd (bool): If true, write will skip autocommands.
Todo:
We should consider whether ``SourceFileInfo`` can replace most
usage of noautocmd. See #298 | 6.593712 | 9.490129 | 0.694797 |
# TODO: This seems wrong, the user setting value is never used anywhere.
if 'EnErrorStyle' not in self._vim.vars:
self._vim.vars['EnErrorStyle'] = 'EnError'
self._vim.command('highlight EnErrorStyle ctermbg=red gui=underline')
# TODO: this SHOULD be a buffer-local setting only, and since it should
# apply to all Scala files, ftplugin is the ideal place to set it. I'm
# not even sure how this is currently working when only set once.
self._vim.command('set omnifunc=EnCompleteFunc')
# TODO: custom filetype ftplugin
self._vim.command(
'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>')
self._vim.command('autocmd FileType package_info setlocal splitright') | def initialize(self) | Sets up initial ensime-vim editor settings. | 15.884157 | 14.307921 | 1.110165 |
self._vim.current.window.cursor = (row, col) | def set_cursor(self, row, col) | Set cursor position to given row and column in the current window.
Operation is not added to the jump list. | 6.047884 | 6.333649 | 0.954881 |
self._vim.command('normal e')
end = self.cursor()
self._vim.command('normal b')
beg = self.cursor()
return beg, end | def word_under_cursor_pos(self) | Return start and end positions of the cursor respectively. | 6.067608 | 4.736392 | 1.281061 |
buff = self._vim.current.buffer
beg = buff.mark('<')
end = buff.mark('>')
return beg, end | def selection_pos(self) | Return start and end positions of the visual selection respectively. | 7.892087 | 5.678287 | 1.389871 |
self._vim.command('call inputsave()')
self._vim.command('let user_input = input("{} ")'.format(prompt))
self._vim.command('call inputrestore()')
response = self._vim.eval('user_input')
self._vim.command('unlet user_input')
return response | def ask_input(self, prompt) | Prompt user for input and return the entered value. | 2.674478 | 2.582722 | 1.035527 |
position = self.cursor()
error = self.get_error_at(position)
if error:
report = error.get_truncated_message(position, self.width() - 1)
self.raw_message(report) | def lazy_display_error(self, filename) | Display error when user is over it. | 6.578428 | 6.411458 | 1.026042 |
for error in self._errors:
if error.includes(self._vim.eval("expand('%:p')"), cursor):
return error
return None | def get_error_at(self, cursor) | Return error at position `cursor`. | 7.252044 | 6.665246 | 1.088038 |
self._vim.eval('clearmatches()')
self._errors = []
self._matches = []
# Reset Syntastic notes - TODO: bufdo?
self._vim.current.buffer.vars['ensime_notes'] = [] | def clean_errors(self) | Clean errors and unhighlight them in vim. | 25.408398 | 19.251013 | 1.319847 |
vim = self._vim
cmd = 'echo "{}"'.format(message.replace('"', '\\"'))
if silent:
cmd = 'silent ' + cmd
if self.isneovim:
vim.async_call(vim.command, cmd)
else:
vim.command(cmd) | def raw_message(self, message, silent=False) | Display a message in the Vim status line. | 4.489691 | 3.883259 | 1.156166 |
def indent(line):
n = 0
for char in line:
if char == ' ':
n += 1
else:
break
return n / 2
lines = self._vim.current.buffer[:lineno]
i = indent(lines[-1])
fqn = [lines[-1].split()[-1]]
for line in reversed(lines):
if indent(line) == i - 1:
i -= 1
fqn.insert(0, line.split()[-1])
return ".".join(fqn) | def symbol_for_inspector_line(self, lineno) | Given a line number for the Package Inspector window, returns the
fully-qualified name for the symbol on that line. | 3.402712 | 3.136755 | 1.084787 |
# TODO: this can probably be a cached property like isneovim
hassyntastic = bool(int(self._vim.eval('exists(":SyntasticCheck")')))
if hassyntastic:
self.__display_notes_with_syntastic(notes)
else:
self.__display_notes(notes)
self._vim.command('redraw!') | def display_notes(self, notes) | Renders "notes" reported by ENSIME, such as typecheck errors. | 9.823029 | 9.268579 | 1.05982 |
f_result = completion["name"]
if is_basic_type(completion):
# It's a raw type
return f_result
elif len(completion["typeInfo"]["paramSections"]) == 0:
return f_result
# It's a function type
sections = completion["typeInfo"]["paramSections"]
f_sections = [formatted_param_section(ps) for ps in sections]
return u"{}{}".format(f_result, "".join(f_sections)) | def formatted_completion_sig(completion) | Regenerate signature for methods. Return just the name otherwise | 4.775263 | 4.788366 | 0.997264 |
implicit = "implicit " if section["isImplicit"] else ""
s_params = [(p[0], formatted_param_type(p[1])) for p in section["params"]]
return "({}{})".format(implicit, concat_params(s_params)) | def formatted_param_section(section) | Format a parameters list. Supports the implicit list | 5.059684 | 5.430829 | 0.93166 |
pt_name = ptype["name"]
if pt_name.startswith("<byname>"):
pt_name = pt_name.replace("<byname>[", "=> ")[:-1]
elif pt_name.startswith("<repeated>"):
pt_name = pt_name.replace("<repeated>[", "")[:-1] + "*"
return pt_name | def formatted_param_type(ptype) | Return the short name for a type. Special treatment for by-name and var args | 4.639627 | 3.89149 | 1.19225 |
self.handlers["SymbolInfo"] = self.handle_symbol_info
self.handlers["IndexerReadyEvent"] = self.handle_indexer_ready
self.handlers["AnalyzerReadyEvent"] = self.handle_analyzer_ready
self.handlers["NewScalaNotesEvent"] = self.buffer_typechecks
self.handlers["NewJavaNotesEvent"] = self.buffer_typechecks_and_display
self.handlers["BasicTypeInfo"] = self.show_type
self.handlers["ArrowTypeInfo"] = self.show_type
self.handlers["FullTypeCheckCompleteEvent"] = self.handle_typecheck_complete
self.handlers["StringResponse"] = self.handle_string_response
self.handlers["CompletionInfoList"] = self.handle_completion_info_list
self.handlers["TypeInspectInfo"] = self.handle_type_inspect
self.handlers["SymbolSearchResults"] = self.handle_symbol_search
self.handlers["SourcePositions"] = self.handle_source_positions
self.handlers["DebugOutputEvent"] = self.handle_debug_output
self.handlers["DebugBreakEvent"] = self.handle_debug_break
self.handlers["DebugBacktrace"] = self.handle_debug_backtrace
self.handlers["DebugVmError"] = self.handle_debug_vm_error
self.handlers["RefactorDiffEffect"] = self.apply_refactor
self.handlers["ImportSuggestions"] = self.handle_import_suggestions
self.handlers["PackageInfo"] = self.handle_package_info
self.handlers["FalseResponse"] = self.handle_false_response | def register_responses_handlers(self) | Register handlers for responses from the server.
A handler must accept only one parameter: `payload`. | 3.390681 | 3.42627 | 0.989613 |
self.log.debug('handle_incoming_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id) # We already log the full JSON response
typehint = payload["typehint"]
handler = self.handlers.get(typehint)
def feature_not_supported(m):
msg = feedback["handler_not_implemented"]
self.editor.raw_message(msg.format(typehint, self.launcher.ensime_version))
if handler:
with catch(NotImplementedError, feature_not_supported):
handler(call_id, payload)
else:
self.log.warning('Response has not been handled: %s', Pretty(payload)) | def handle_incoming_response(self, call_id, payload) | Get a registered handler for a given response and execute it. | 8.31672 | 7.953924 | 1.045612 |
self.log.debug('handle_symbol_search: in %s', Pretty(payload))
syms = payload["syms"]
qfList = []
for sym in syms:
p = sym.get("pos")
if p:
item = self.editor.to_quickfix_item(str(p["file"]),
p["line"],
str(sym["name"]),
"info")
qfList.append(item)
self.editor.write_quickfix_list(qfList, "Symbol Search") | def handle_symbol_search(self, call_id, payload) | Handler for symbol search results | 6.354641 | 6.179993 | 1.02826 |
with catch(KeyError, lambda e: self.editor.message("unknown_symbol")):
decl_pos = payload["declPos"]
f = decl_pos.get("file")
call_options = self.call_options[call_id]
self.log.debug('handle_symbol_info: call_options %s', call_options)
display = call_options.get("display")
if display and f:
self.editor.raw_message(f)
open_definition = call_options.get("open_definition")
if open_definition and f:
self.editor.clean_errors()
self.editor.doautocmd('BufLeave')
if call_options.get("split"):
vert = call_options.get("vert")
self.editor.split_window(f, vertical=vert)
else:
self.editor.edit(f)
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter')
self.set_position(decl_pos)
del self.call_options[call_id] | def handle_symbol_info(self, call_id, payload) | Handler for response `SymbolInfo`. | 4.852104 | 4.777349 | 1.015648 |
self.log.debug('handle_string_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id)
# :EnDocBrowse or :EnDocUri
url = payload['text']
if not url.startswith('http'):
port = self.ensime.http_port()
url = gconfig['localhost'].format(port, url)
options = self.call_options.get(call_id)
if options and options.get('browse'):
self._browse_doc(url)
del self.call_options[call_id]
else:
# TODO: make this return value of a Vim function synchronously, how?
self.log.debug('EnDocUri %s', url)
return url | def handle_string_response(self, call_id, payload) | Handler for response `StringResponse`.
This is the response for the following requests:
1. `DocUriAtPointReq` or `DocUriForSymbolReq`
2. `DebugToStringReq` | 9.151885 | 8.707154 | 1.051076 |
self.log.debug('handle_completion_info_list: in')
# filter out completions without `typeInfo` field to avoid server bug. See #324
completions = [c for c in payload["completions"] if "typeInfo" in c]
self.suggestions = [completion_to_suggest(c) for c in completions]
self.log.debug('handle_completion_info_list: %s', Pretty(self.suggestions)) | def handle_completion_info_list(self, call_id, payload) | Handler for a completion response. | 5.339241 | 5.203419 | 1.026102 |
style = 'fullName' if self.full_types_enabled else 'name'
interfaces = payload.get("interfaces")
ts = [i["type"][style] for i in interfaces]
prefix = "( " + ", ".join(ts) + " ) => "
self.editor.raw_message(prefix + payload["type"][style]) | def handle_type_inspect(self, call_id, payload) | Handler for responses `TypeInspectInfo`. | 8.318937 | 8.116004 | 1.025004 |
if self.full_types_enabled:
tpe = payload['fullName']
else:
tpe = payload['name']
self.log.info('Displayed type %s', tpe)
self.editor.raw_message(tpe) | def show_type(self, call_id, payload) | Show type of a variable or scala type. | 7.465104 | 6.784992 | 1.100238 |
self.log.debug('handle_source_positions: in %s', Pretty(payload))
call_options = self.call_options[call_id]
word_under_cursor = call_options.get("word_under_cursor")
positions = payload["positions"]
if not positions:
self.editor.raw_message("No usages of <{}> found".format(word_under_cursor))
return
qf_list = []
for p in positions:
position = p["position"]
preview = str(p["preview"]) if "preview" in p else "<no preview>"
item = self.editor.to_quickfix_item(str(position["file"]),
position["line"],
preview,
"info")
qf_list.append(item)
qf_sorted = sorted(qf_list, key=itemgetter('filename', 'lnum'))
self.editor.write_quickfix_list(qf_sorted, "Usages of <{}>".format(word_under_cursor)) | def handle_source_positions(self, call_id, payload) | Handler for source positions | 4.559613 | 4.510631 | 1.010859 |
if not self._timer:
self._timer = self._vim.eval(
"timer_start({}, 'EnTick', {{'repeat': -1}})"
.format(REFRESH_TIMER)
) | def _start_refresh_timer(self) | Start the Vim timer. | 11.949553 | 8.579254 | 1.392843 |
connection_alive = True
while self.running:
if self.ws:
def logger_and_close(msg):
self.log.error('Websocket exception', exc_info=True)
if not self.running:
# Tear down has been invoked
# Prepare to exit the program
connection_alive = False # noqa: F841
else:
if not self.number_try_connection:
# Stop everything.
self.teardown()
self._display_ws_warning()
with catch(websocket.WebSocketException, logger_and_close):
result = self.ws.recv()
self.queue.put(result)
if connection_alive:
time.sleep(sleep_t) | def queue_poll(self, sleep_t=0.5) | Put new messages on the queue as they arrive. Blocking in a thread.
Value of sleep is low to improve responsiveness. | 7.021574 | 7.004282 | 1.002469 |
def lazy_initialize_ensime():
if not self.ensime:
called_by = inspect.stack()[4][3]
self.log.debug(str(inspect.stack()))
self.log.debug('setup(quiet=%s, bootstrap_server=%s) called by %s()',
quiet, bootstrap_server, called_by)
installed = self.launcher.strategy.isinstalled()
if not installed and not bootstrap_server:
if not quiet:
scala = self.launcher.config.get('scala-version')
msg = feedback["prompt_server_install"].format(scala_version=scala)
self.editor.raw_message(msg)
return False
try:
self.ensime = self.launcher.launch()
except InvalidJavaPathError:
self.editor.message('invalid_java') # TODO: also disable plugin
return bool(self.ensime)
def ready_to_connect():
if not self.ws and self.ensime.is_ready():
self.connect_ensime_server()
return True
# True if ensime is up and connection is ok, otherwise False
return self.running and lazy_initialize_ensime() and ready_to_connect() | def setup(self, quiet=False, bootstrap_server=False) | Check the classpath and connect to the server if necessary. | 6.081478 | 5.894559 | 1.03171 |
def reconnect(e):
self.log.error('send error, reconnecting...', exc_info=True)
self.connect_ensime_server()
if self.ws:
self.ws.send(msg + "\n")
self.log.debug('send: in')
if self.running and self.ws:
with catch(websocket.WebSocketException, reconnect):
self.log.debug('send: sending JSON on WebSocket')
self.ws.send(msg + "\n") | def send(self, msg) | Send something to the ensime server. | 5.901829 | 5.038043 | 1.171453 |
self.log.debug('connect_ensime_server: in')
server_v2 = isinstance(self, EnsimeClientV2)
def disable_completely(e):
if e:
self.log.error('connection error: %s', e, exc_info=True)
self.shutdown_server()
self._display_ws_warning()
if self.running and self.number_try_connection:
self.number_try_connection -= 1
if not self.ensime_server:
port = self.ensime.http_port()
uri = "websocket" if server_v2 else "jerky"
self.ensime_server = gconfig["ensime_server"].format(port, uri)
with catch(websocket.WebSocketException, disable_completely):
# Use the default timeout (no timeout).
options = {"subprotocols": ["jerky"]} if server_v2 else {}
options['enable_multithread'] = True
self.log.debug("About to connect to %s with options %s",
self.ensime_server, options)
self.ws = websocket.create_connection(self.ensime_server, **options)
if self.ws:
self.send_request({"typehint": "ConnectionInfoReq"})
else:
# If it hits this, number_try_connection is 0
disable_completely(None) | def connect_ensime_server(self) | Start initial connection with the server. | 5.271865 | 5.17459 | 1.018799 |
self.log.debug('shutdown_server: in')
if self.ensime and self.toggle_teardown:
self.ensime.stop() | def shutdown_server(self) | Shut down server if it is alive. | 13.89406 | 12.537458 | 1.108204 |
self.log.debug('teardown: in')
self.running = False
self.shutdown_server()
shutil.rmtree(self.tmp_diff_folder, ignore_errors=True) | def teardown(self) | Tear down the server or keep it alive. | 7.658488 | 6.27357 | 1.220754 |
self.log.debug('send_at_position: in')
b, e = self.editor.selection_pos() if useSelection else self.editor.word_under_cursor_pos()
self.log.debug('useSelection: {}, beg: {}, end: {}'.format(useSelection, b, e))
beg = self.get_position(b[0], b[1])
end = self.get_position(e[0], e[1])
self.send_request(
{"typehint": what + "AtPointReq",
"file": self.editor.path(),
where: {"from": beg, "to": end}}) | def send_at_position(self, what, useSelection, where="range") | Ask the server to perform an operation on a range (sometimes named point)
`what` is used as the prefix for the typehint.
If `useSelection` is `False` the range is calculated based on the word under de
cursor. Current selection start and end is used as the range otherwise.
`where` defines the name of the property holding the range info within the request.
Default value is 'range' but 'point' is sometimes used | 4.596913 | 3.764586 | 1.221094 |
if decl_pos["typehint"] == "LineSourcePosition":
self.editor.set_cursor(decl_pos['line'], 0)
else: # OffsetSourcePosition
point = decl_pos["offset"]
row, col = self.editor.point2pos(point + 1)
self.editor.set_cursor(row, col) | def set_position(self, decl_pos) | Set editor position from ENSIME declPos data. | 4.979021 | 4.725003 | 1.05376 |
result = col
self.log.debug('%s %s', row, col)
lines = self.editor.getlines()[:row - 1]
result += sum([len(l) + 1 for l in lines])
self.log.debug(result)
return result | def get_position(self, row, col) | Get char position in all the text from row and column. | 5.531557 | 4.816225 | 1.148526 |
pos = self.get_position(row, col)
self.send_request(
{"typehint": what + "AtPointReq",
"file": self._file_info(),
"point": pos}) | def send_at_point(self, what, row, col) | Ask the server to perform an operation at a given point. | 9.384033 | 8.024503 | 1.169422 |
self.log.debug('type_check_cmd: in')
self.start_typechecking()
self.type_check("")
self.editor.message('typechecking') | def type_check_cmd(self, args, range=None) | Sets the flag to begin buffering typecheck notes & clears any
stale notes before requesting a typecheck from the server | 12.961993 | 10.418771 | 1.2441 |
self.log.debug('doc_uri: in')
self.send_at_position("DocUri", False, "point") | def doc_uri(self, args, range=None) | Request doc of whatever at cursor. | 21.53916 | 16.594326 | 1.297983 |
row, col = self.editor.cursor()
self.log.debug('usages: in')
self.call_options[self.call_id] = {
"word_under_cursor": self.editor.current_word(),
"false_resp_msg": "Not a valid symbol under the cursor"}
self.send_at_point("UsesOfSymbol", row, col) | def usages(self) | Request usages of whatever at cursor. | 14.135782 | 11.359365 | 1.244417 |
self.log.debug('browse: in')
self.call_options[self.call_id] = {"browse": True}
self.send_at_position("DocUri", False, "point") | def doc_browse(self, args, range=None) | Browse doc of whatever at cursor. | 19.511765 | 17.567036 | 1.110703 |
self.log.debug('rename: in')
if not new_name:
new_name = self.editor.ask_input("Rename to:")
self.editor.write(noautocmd=True)
b, e = self.editor.word_under_cursor_pos()
current_file = self.editor.path()
self.editor.raw_message(current_file)
self.send_refactor_request(
"RefactorReq",
{
"typehint": "RenameRefactorDesc",
"newName": new_name,
"start": self.get_position(b[0], b[1]),
"end": self.get_position(e[0], e[1]) + 1,
"file": current_file,
},
{"interactive": False}
) | def rename(self, new_name, range=None) | Request a rename to the server. | 5.645566 | 5.357729 | 1.053724 |
self.log.debug('symbol_search: in')
if not search_terms:
self.editor.message('symbol_search_symbol_required')
return
req = {
"typehint": "PublicSymbolSearchReq",
"keywords": search_terms,
"maxResults": 25
}
self.send_request(req) | def symbol_search(self, search_terms) | Search for symbols matching a set of keywords | 6.588915 | 6.569716 | 1.002922 |
request = {
"typehint": ref_type,
"procId": self.refactor_id,
"params": ref_params
}
f = ref_params["file"]
self.refactorings[self.refactor_id] = f
self.refactor_id += 1
request.update(ref_options)
self.send_request(request) | def send_refactor_request(self, ref_type, ref_params, ref_options) | Send a refactor request to the Ensime server.
The `ref_params` field will always have a field `type`. | 4.532797 | 4.586019 | 0.988395 |
supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]
if payload["refactorType"]["typehint"] in supported_refactorings:
diff_filepath = payload["diff"]
path = self.editor.path()
bname = os.path.basename(path)
target = os.path.join(self.tmp_diff_folder, bname)
reject_arg = "--reject-file={}.rej".format(target)
backup_pref = "--prefix={}".format(self.tmp_diff_folder)
# Patch utility is prepackaged or installed with vim
cmd = ["patch", reject_arg, backup_pref, path, diff_filepath]
failed = Popen(cmd, stdout=PIPE, stderr=PIPE).wait()
if failed:
self.editor.message("failed_refactoring")
# Update file and reload highlighting
self.editor.edit(self.editor.path())
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter') | def apply_refactor(self, call_id, payload) | Apply a refactor depending on its type. | 7.532675 | 7.375064 | 1.021371 |
self.log.debug('send_request: in')
message = {'callId': self.call_id, 'req': request}
self.log.debug('send_request: %s', Pretty(message))
self.send(json.dumps(message))
call_id = self.call_id
self.call_id += 1
return call_id | def send_request(self, request) | Send a request to the server. | 3.750311 | 3.560165 | 1.053409 |
self.log.debug('buffer_leave: %s', filename)
# TODO: This is questionable, and we should use location list for
# single-file errors.
self.editor.clean_errors() | def buffer_leave(self, filename) | User is changing of buffer. | 15.600114 | 13.856193 | 1.125859 |
self.log.debug('type_check: in')
self.editor.clean_errors()
self.send_request(
{"typehint": "TypecheckFilesReq",
"files": [self.editor.path()]}) | def type_check(self, filename) | Update type checking when user saves buffer. | 13.194589 | 11.492652 | 1.148089 |
start, now = time.time(), time.time()
wait = self.queue.empty() and should_wait
while (not self.queue.empty() or wait) and (now - start) < timeout:
if wait and self.queue.empty():
time.sleep(0.25)
now = time.time()
else:
result = self.queue.get(False)
self.log.debug('unqueue: result received\n%s', result)
if result and result != "nil":
wait = None
# Restart timeout
start, now = time.time(), time.time()
_json = json.loads(result)
# Watch out, it may not have callId
call_id = _json.get("callId")
if _json["payload"]:
self.handle_incoming_response(call_id, _json["payload"])
else:
self.log.debug('unqueue: nil or None received')
if (now - start) >= timeout:
self.log.warning('unqueue: no reply from server for %ss', timeout) | def unqueue(self, timeout=10, should_wait=False) | Unqueue all the received ensime responses for a given file. | 3.845308 | 3.774953 | 1.018637 |
if self.running and self.ws:
self.editor.lazy_display_error(filename)
self.unqueue() | def unqueue_and_display(self, filename) | Unqueue messages and give feedback to user (if necessary). | 14.815532 | 14.898898 | 0.994405 |
if self.connection_attempts < 10:
# Trick to connect ASAP when
# plugin is started without
# user interaction (CursorMove)
self.setup(True, False)
self.connection_attempts += 1
self.unqueue_and_display(filename) | def tick(self, filename) | Try to connect and display messages in queue. | 16.175064 | 12.867819 | 1.257017 |
success = self.setup(True, False)
if success:
self.editor.message("start_message") | def vim_enter(self, filename) | Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible. | 20.157476 | 18.903261 | 1.066349 |
self.log.debug('complete_func: in %s %s', findstart, base)
def detect_row_column_start():
row, col = self.editor.cursor()
start = col
line = self.editor.getline()
while start > 0 and line[start - 1] not in " .,([{":
start -= 1
# Start should be 1 when startcol is zero
return row, col, start if start else 1
if str(findstart) == "1":
row, col, startcol = detect_row_column_start()
# Make request to get response ASAP
self.complete(row, col)
self.completion_started = True
# We always allow autocompletion, even with empty seeds
return startcol
else:
result = []
# Only handle snd invocation if fst has already been done
if self.completion_started:
# Unqueing messages until we get suggestions
self.unqueue(timeout=self.completion_timeout, should_wait=True)
suggestions = self.suggestions or []
self.log.debug('complete_func: suggestions in')
for m in suggestions:
result.append(m)
self.suggestions = None
self.completion_started = False
return result | def complete_func(self, findstart, base) | Handle omni completion. | 7.213242 | 6.957799 | 1.036713 |
line = payload['line']
config = self.launcher.config # TODO: make an attribute of client
path = os.path.relpath(payload['file'], config['root-dir'])
self.editor.raw_message(feedback['notify_break'].format(line, path))
self.debug_thread_id = payload["threadId"] | def handle_debug_break(self, call_id, payload) | Handle responses `DebugBreakEvent`. | 10.701054 | 10.031165 | 1.066781 |
frames = payload["frames"]
fd, path = tempfile.mkstemp('.json', text=True, dir=self.tmp_diff_folder)
tmpfile = os.fdopen(fd, 'w')
tmpfile.write(json.dumps(frames, indent=2))
opts = {'readonly': True, 'bufhidden': 'wipe',
'buflisted': False, 'swapfile': False}
self.editor.split_window(path, size=20, bufopts=opts)
tmpfile.close() | def handle_debug_backtrace(self, call_id, payload) | Handle responses `DebugBacktrace`. | 6.903043 | 6.905264 | 0.999678 |
home = os.environ['HOME']
old_base_dir = os.path.join(home, '.config', 'classpath_project_ensime')
if os.path.isdir(old_base_dir):
shutil.rmtree(old_base_dir, ignore_errors=True) | def _remove_legacy_bootstrap() | Remove bootstrap projects from old path, they'd be really stale by now. | 3.904952 | 3.420489 | 1.141636 |
cache_dir = self.config['cache-dir']
java_flags = self.config['java-flags']
iswindows = os.name == 'nt'
Util.mkdir_p(cache_dir)
log_path = os.path.join(cache_dir, "server.log")
log = open(log_path, "w")
null = open(os.devnull, "r")
java = os.path.join(self.config['java-home'], 'bin', 'java.exe' if iswindows else 'java')
if not os.path.exists(java):
raise InvalidJavaPathError(errno.ENOENT, 'No such file or directory', java)
elif not os.access(java, os.X_OK):
raise InvalidJavaPathError(errno.EACCES, 'Permission denied', java)
args = (
[java, "-cp", (';' if iswindows else ':').join(classpath)] +
[a for a in java_flags if a] +
["-Densime.config={}".format(self.config.filepath),
"org.ensime.server.Server"])
process = subprocess.Popen(
args,
stdin=null,
stdout=log,
stderr=subprocess.STDOUT)
pid_path = os.path.join(cache_dir, "server.pid")
Util.write_file(pid_path, str(process.pid))
def on_stop():
log.close()
null.close()
with catch(Exception):
os.remove(pid_path)
return EnsimeProcess(cache_dir, process, log_path, on_stop) | def _start_process(self, classpath) | Given a classpath prepared for running ENSIME, spawns a server process
in a way that is otherwise agnostic to how the strategy installs ENSIME.
Args:
classpath (list of str): list of paths to jars or directories
(Within this function the list is joined with a system dependent
path separator to create a single string argument suitable to
pass to ``java -cp`` as a classpath)
Returns:
EnsimeProcess: A process handle for the launched server. | 2.864062 | 2.642728 | 1.083752 |
project_dir = os.path.dirname(self.classpath_file)
sbt_plugin =
Util.mkdir_p(project_dir)
Util.mkdir_p(os.path.join(project_dir, "project"))
Util.write_file(
os.path.join(project_dir, "build.sbt"),
self.build_sbt())
Util.write_file(
os.path.join(project_dir, "project", "build.properties"),
"sbt.version={}".format(self.SBT_VERSION))
Util.write_file(
os.path.join(project_dir, "project", "plugins.sbt"),
sbt_plugin.format(*self.SBT_COURSIER_COORDS))
# Synchronous update of the classpath via sbt
# see https://github.com/ensime/ensime-vim/issues/29
cd_cmd = "cd {}".format(project_dir)
sbt_cmd = "sbt -Dsbt.log.noformat=true -batch saveClasspath"
if int(self.vim.eval("has('nvim')")):
import tempfile
import re
tmp_dir = tempfile.gettempdir()
flag_file = "{}/ensime-vim-classpath.flag".format(tmp_dir)
self.vim.command("echo 'Waiting for generation of classpath...'")
if re.match(".+fish$", self.vim.eval("&shell")):
sbt_cmd += "; echo $status > {}".format(flag_file)
self.vim.command("terminal {}; and {}".format(cd_cmd, sbt_cmd))
else:
sbt_cmd += "; echo $? > {}".format(flag_file)
self.vim.command("terminal ({} && {})".format(cd_cmd, sbt_cmd))
# Block execution when sbt is run
waiting_for_flag = True
while waiting_for_flag:
waiting_for_flag = not os.path.isfile(flag_file)
if not waiting_for_flag:
with open(flag_file, "r") as f:
rtcode = f.readline()
os.remove(flag_file)
if rtcode and int(rtcode) != 0: # error
self.vim.command(
"echo 'Something wrong happened, check the "
"execution log...'")
return None
else:
time.sleep(0.2)
else:
self.vim.command("!({} && {})".format(cd_cmd, sbt_cmd))
success = self.reorder_classpath(self.classpath_file)
if not success:
self.vim.command("echo 'Classpath ordering failed.'")
return True | def install(self) | Installs ENSIME server with a bootstrap sbt project and generates its classpath. | 3.881734 | 3.63984 | 1.066457 |
success = False
with catch((IOError, OSError)):
with open(classpath_file, "r") as f:
classpath = f.readline()
# Proceed if classpath is non-empty
if classpath:
units = classpath.split(":")
reordered_units = []
for unit in units:
if "monkeys" in unit:
reordered_units.insert(0, unit)
else:
reordered_units.append(unit)
reordered_classpath = ":".join(reordered_units)
with open(classpath_file, "w") as f:
f.write(reordered_classpath)
success = True
return success | def reorder_classpath(self, classpath_file) | Reorder classpath and put monkeys-jar in the first place. | 2.888562 | 2.514069 | 1.148959 |
realpath = os.path.realpath(path)
config_path = os.path.join(realpath, '.ensime')
if os.path.isfile(config_path):
return config_path
elif realpath == os.path.abspath('/'):
return None
else:
dirname = os.path.dirname(realpath)
return ProjectConfig.find_from(dirname) | def find_from(path) | Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found. | 3.209683 | 3.005566 | 1.067913 |
def paired(iterable):
cursor = iter(iterable)
return zip(cursor, cursor)
def unwrap_if_sexp_symbol(datum):
return datum.value() if isinstance(datum, sexpdata.Symbol) else datum
def sexp2dict(sexps):
newdict = {}
# Turn flat list into associative pairs
for key, value in paired(sexps):
key = str(unwrap_if_sexp_symbol(key)).lstrip(':')
# Recursively transform nested lists
if isinstance(value, list) and value:
if isinstance(value[0], list):
newdict[key] = [sexp2dict(val) for val in value]
elif isinstance(value[0], sexpdata.Symbol):
newdict[key] = sexp2dict(value)
else:
newdict[key] = value
else:
newdict[key] = value
return newdict
conf = sexpdata.loads(Util.read_file(path))
return sexp2dict(conf) | def parse(path) | Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys. | 3.586547 | 3.530195 | 1.015963 |
'''Takes JSON response from API and converts to ACL object'''
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read'])
return Acl(read_acl)
else:
raise ValueError('Response does not contain read ACL') | def from_acl_response(acl_response) | Takes JSON response from API and converts to ACL object | 4.542964 | 3.403173 | 1.33492 |
'''Creates a directory, optionally include Acl argument to set permissions'''
parent, name = getParentAndBase(self.path)
json = { 'name': name }
if acl is not None:
json['acl'] = acl.to_api_param()
response = self.client.postJsonHelper(DataDirectory._getUrl(parent), json, False)
if (response.status_code != 200):
raise DataApiError("Directory creation failed: " + str(response.content)) | def create(self, acl=None) | Creates a directory, optionally include Acl argument to set permissions | 7.310087 | 5.175035 | 1.412568 |
'''
Returns permissions for this directory or None if it's a special collection such as
.session or .algo
'''
response = self.client.getHelper(self.url, acl='true')
if response.status_code != 200:
raise DataApiError('Unable to get permissions:' + str(response.content))
content = response.json()
if 'acl' in content:
return Acl.from_acl_response(content['acl'])
else:
return None | def get_permissions(self) | Returns permissions for this directory or None if it's a special collection such as
.session or .algo | 7.517772 | 3.747245 | 2.006213 |
if value == 0:
return b'\x00\x00\x00\x00\x00\x00\x00\x00'
if value < 0:
byte1 = 0x80
value = -value
else:
byte1 = 0x00
fexp = numpy.log2(value) / 4
exponent = int(numpy.ceil(fexp))
if fexp == exponent:
exponent += 1
mantissa = int(value * 16.**(14 - exponent))
byte1 += exponent + 64
byte2 = (mantissa // 281474976710656)
short3 = (mantissa % 281474976710656) // 4294967296
long4 = mantissa % 4294967296
return struct.pack(">HHL", byte1 * 256 + byte2, short3, long4) | def _eight_byte_real(value) | Convert a number into the GDSII 8 byte real format.
Parameters
----------
value : number
The number to be converted.
Returns
-------
out : string
The GDSII binary string that represents ``value``. | 2.420112 | 2.494794 | 0.970065 |
short1, short2, long3 = struct.unpack('>HHL', value)
exponent = (short1 & 0x7f00) // 256 - 64
mantissa = (((short1 & 0x00ff) * 65536 + short2) * 4294967296 +
long3) / 72057594037927936.0
if short1 & 0x8000:
return -mantissa * 16.**exponent
return mantissa * 16.**exponent | def _eight_byte_real_to_float(value) | Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``. | 2.54348 | 2.711431 | 0.938058 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.