text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
cmd = 'noautocmd write' if noautocmd else 'write'
self._vim.command(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize(self):
"""Sets up initial ensime-vim editor settings.""" |
# 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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
self._vim.current.window.cursor = (row, col) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def word_under_cursor_pos(self):
"""Return start and end positions of the cursor respectively.""" |
self._vim.command('normal e')
end = self.cursor()
self._vim.command('normal b')
beg = self.cursor()
return beg, end |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selection_pos(self):
"""Return start and end positions of the visual selection respectively.""" |
buff = self._vim.current.buffer
beg = buff.mark('<')
end = buff.mark('>')
return beg, end |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask_input(self, prompt):
"""Prompt user for input and return the entered value.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_display_error(self, filename):
"""Display error when user is over it.""" |
position = self.cursor()
error = self.get_error_at(position)
if error:
report = error.get_truncated_message(position, self.width() - 1)
self.raw_message(report) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_error_at(self, cursor):
"""Return error at position `cursor`.""" |
for error in self._errors:
if error.includes(self._vim.eval("expand('%:p')"), cursor):
return error
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_errors(self):
"""Clean errors and unhighlight them in vim.""" |
self._vim.eval('clearmatches()')
self._errors = []
self._matches = []
# Reset Syntastic notes - TODO: bufdo?
self._vim.current.buffer.vars['ensime_notes'] = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_message(self, message, silent=False):
"""Display a message in the Vim status line.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_notes(self, notes):
"""Renders "notes" reported by ENSIME, such as typecheck errors.""" |
# 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!') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatted_param_section(section):
"""Format a parameters list. Supports the implicit list""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatted_param_type(ptype):
"""Return the short name for a type. Special treatment for by-name and var args""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_responses_handlers(self):
"""Register handlers for responses from the server. A handler must accept only one parameter: `payload`. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_incoming_response(self, call_id, payload):
"""Get a registered handler for a given response and execute it.""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_symbol_search(self, call_id, payload):
"""Handler for symbol search results""" |
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_symbol_info(self, call_id, payload):
"""Handler for response `SymbolInfo`.""" |
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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` """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_completion_info_list(self, call_id, payload):
"""Handler for a completion response.""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_type_inspect(self, call_id, payload):
"""Handler for responses `TypeInspectInfo`.""" |
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_type(self, call_id, payload):
"""Show type of a variable or scala type.""" |
if self.full_types_enabled:
tpe = payload['fullName']
else:
tpe = payload['name']
self.log.info('Displayed type %s', tpe)
self.editor.raw_message(tpe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_source_positions(self, call_id, payload):
"""Handler for source positions""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start_refresh_timer(self):
"""Start the Vim timer. """ |
if not self._timer:
self._timer = self._vim.eval(
"timer_start({}, 'EnTick', {{'repeat': -1}})"
.format(REFRESH_TIMER)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self, quiet=False, bootstrap_server=False):
"""Check the classpath and connect to the server if necessary.""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, msg):
"""Send something to the ensime server.""" |
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_ensime_server(self):
"""Start initial connection with the server.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown_server(self):
"""Shut down server if it is alive.""" |
self.log.debug('shutdown_server: in')
if self.ensime and self.toggle_teardown:
self.ensime.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def teardown(self):
"""Tear down the server or keep it alive.""" |
self.log.debug('teardown: in')
self.running = False
self.shutdown_server()
shutil.rmtree(self.tmp_diff_folder, ignore_errors=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_position(self, decl_pos):
"""Set editor position from ENSIME declPos data.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_position(self, row, col):
"""Get char position in all the text from row and column.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_at_point(self, what, row, col):
"""Ask the server to perform an operation at a given point.""" |
pos = self.get_position(row, col)
self.send_request(
{"typehint": what + "AtPointReq",
"file": self._file_info(),
"point": pos}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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""" |
self.log.debug('type_check_cmd: in')
self.start_typechecking()
self.type_check("")
self.editor.message('typechecking') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_uri(self, args, range=None):
"""Request doc of whatever at cursor.""" |
self.log.debug('doc_uri: in')
self.send_at_position("DocUri", False, "point") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usages(self):
"""Request usages of whatever at cursor.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_browse(self, args, range=None):
"""Browse doc of whatever at cursor.""" |
self.log.debug('browse: in')
self.call_options[self.call_id] = {"browse": True}
self.send_at_position("DocUri", False, "point") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(self, new_name, range=None):
"""Request a rename to the server.""" |
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}
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symbol_search(self, search_terms):
"""Search for symbols matching a set of keywords""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_refactor(self, call_id, payload):
"""Apply a refactor depending on its type.""" |
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buffer_leave(self, filename):
"""User is changing of buffer.""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_check(self, filename):
"""Update type checking when user saves buffer.""" |
self.log.debug('type_check: in')
self.editor.clean_errors()
self.send_request(
{"typehint": "TypecheckFilesReq",
"files": [self.editor.path()]}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unqueue(self, timeout=10, should_wait=False):
"""Unqueue all the received ensime responses for a given file.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tick(self, filename):
"""Try to connect and display messages in queue.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vim_enter(self, filename):
"""Set up EnsimeClient when vim enters. This is useful to start the EnsimeLauncher as soon as possible.""" |
success = self.setup(True, False)
if success:
self.editor.message("start_message") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_func(self, findstart, base):
"""Handle omni completion.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_debug_break(self, call_id, payload):
"""Handle responses `DebugBreakEvent`.""" |
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"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_debug_backtrace(self, call_id, payload):
"""Handle responses `DebugBacktrace`.""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_legacy_bootstrap():
"""Remove bootstrap projects from old path, they'd be really stale by now.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self):
"""Installs ENSIME server with a bootstrap sbt project and generates its classpath.""" |
project_dir = os.path.dirname(self.classpath_file)
sbt_plugin = """addSbtPlugin("{0}" % "{1}" % "{2}")"""
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reorder_classpath(self, classpath_file):
"""Reorder classpath and put monkeys-jar in the first place.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
def paired(iterable):
"""s -> (s0, s1), (s2, s3), (s4, s5), ..."""
cursor = iter(iterable)
return zip(cursor, cursor)
def unwrap_if_sexp_symbol(datum):
"""Convert Symbol(':key') to ':key' (Symbol isn't hashable for dict keys).
"""
return datum.value() if isinstance(datum, sexpdata.Symbol) else datum
def sexp2dict(sexps):
"""Transforms a nested list structure from sexpdata to dict."""
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_acl_response(acl_response):
'''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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create(self, acl=None):
'''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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_permissions(self):
'''
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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``. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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``. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice(objects, position, axis, precision=1e-3, layer=0, datatype=0):
""" Slice polygons and polygon sets at given positions along an axis. Parameters objects : ``PolygonSet``, or list Operand of the slice operation. If this is a list, each element must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array-like[N][2] of vertices of a polygon. position : number or list of numbers Positions to perform the slicing operation along the specified axis. axis : 0 or 1 Axis along which the polygon will be sliced. precision : float Desired precision for rounding vertice coordinates. layer : integer, list The GDSII layer numbers for the elements between each division. If the number of layers in the list is less than the number of divided regions, the list is repeated. datatype : integer The GDSII datatype for the resulting element (between 0 and 255). Returns ------- out : list[N] of PolygonSet Result of the slicing operation, with N = len(positions) + 1. Each PolygonSet comprises all polygons between 2 adjacent slicing positions, in crescent order. Examples -------- """ |
if not isinstance(layer, list):
layer = [layer]
if not isinstance(objects, list):
objects = [objects]
if not isinstance(position, list):
pos = [position]
else:
pos = sorted(position)
result = [[] for _ in range(len(pos) + 1)]
polygons = []
for obj in objects:
if isinstance(obj, PolygonSet):
polygons.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
polygons.extend(obj.get_polygons())
else:
polygons.append(obj)
scaling = 1 / precision
for pol in polygons:
for r, p in zip(result, clipper._chop(pol, pos, axis, scaling)):
r.extend(p)
for i in range(len(result)):
result[i] = PolygonSet(result[i], layer[i % len(layer)], datatype)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def offset(polygons, distance, join='miter', tolerance=2, precision=0.001, join_first=False, max_points=199, layer=0, datatype=0):
""" Shrink or expand a polygon or polygon set. Parameters polygons : polygon or array-like Polygons to be offset. Must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array. The array may contain any of the previous objects or an array-like[N][2] of vertices of a polygon. distance : number Offset distance. Positive to expand, negative to shrink. join : {'miter', 'bevel', 'round'} Type of join used to create the offset polygon. tolerance : number For miter joints, this number must be at least 2 and it represents the maximun distance in multiples of offset betwen new vertices and their original position before beveling to avoid spikes at acute joints. For round joints, it indicates the curvature resolution in number of points per full circle. precision : float Desired precision for rounding vertice coordinates. join_first : bool Join all paths before offseting to avoid unecessary joins in adjacent polygon sides. max_points : integer If greater than 4, fracture the resulting polygons to ensure they have at most ``max_points`` vertices. This is not a tessellating function, so this number should be as high as possible. For example, it should be set to 199 for polygons being drawn in GDSII files. layer : integer The GDSII layer number for the resulting element. datatype : integer The GDSII datatype for the resulting element (between 0 and 255). Returns ------- out : ``PolygonSet`` or ``None`` Return the offset shape as a set of polygons. """ |
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
result = clipper.offset(poly, distance, join, tolerance, 1 / precision, 1
if join_first else 0)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fast_boolean(operandA, operandB, operation, precision=0.001, max_points=199, layer=0, datatype=0):
""" Execute any boolean operation between 2 polygons or polygon sets. Parameters operandA : polygon or array-like First operand. Must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array. The array may contain any of the previous objects or an array-like[N][2] of vertices of a polygon. operandB : polygon, array-like or ``None`` Second operand. Must be ``None``, a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array. The array may contain any of the previous objects or an array-like[N][2] of vertices of a polygon. operation : {'or', 'and', 'xor', 'not'} Boolean operation to be executed. The 'not' operation returns the difference ``operandA - operandB``. precision : float Desired precision for rounding vertice coordinates. max_points : integer If greater than 4, fracture the resulting polygons to ensure they have at most ``max_points`` vertices. This is not a tessellating function, so this number should be as high as possible. For example, it should be set to 199 for polygons being drawn in GDSII files. layer : integer The GDSII layer number for the resulting element. datatype : integer The GDSII datatype for the resulting element (between 0 and 255). Returns ------- out : PolygonSet or ``None`` Result of the boolean operation. """ |
polyA = []
polyB = []
for poly, obj in zip((polyA, polyB), (operandA, operandB)):
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
elif obj is not None:
for inobj in obj:
if isinstance(inobj, PolygonSet):
poly.extend(inobj.polygons)
elif isinstance(inobj, CellReference) or isinstance(
inobj, CellArray):
poly.extend(inobj.get_polygons())
else:
poly.append(inobj)
if len(polyB) == 0:
polyB.append(polyA.pop())
result = clipper.clip(polyA, polyB, operation, 1 / precision)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inside(points, polygons, short_circuit='any', precision=0.001):
""" Test whether each of the points is within the given set of polygons. Parameters points : array-like[N][2] or list of array-like[N][2] Coordinates of the points to be tested or groups of points to be tested together. polygons : polygon or array-like Polygons to be tested against. Must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array. The array may contain any of the previous objects or an array-like[N][2] of vertices of a polygon. short_circuit : {'any', 'all'} If `points` is a list of point groups, testing within each group will be short-circuited if any of the points in the group is inside ('any') or outside ('all') the polygons. If `points` is simply a list of points, this parameter has no effect. precision : float Desired precision for rounding vertice coordinates. Returns ------- out : tuple Tuple of booleans indicating if each of the points or point groups is inside the set of polygons. """ |
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
if hasattr(points[0][0], '__iter__'):
pts = points
sc = 1 if short_circuit == 'any' else -1
else:
pts = (points, )
sc = 0
return clipper.inside(pts, poly, sc, 1 / precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(obj, dx, dy):
""" Creates a copy of ``obj`` and translates the new object to a new location. Parameters obj : ``obj`` any translatable geometery object. dx : float distance to move in the x-direction dy : float distance to move in the y-direction Returns ------- out : ``obj`` Translated copy of original ``obj`` Examples -------- """ |
newObj = libCopy.deepcopy(obj)
newObj.translate(dx, dy)
return newObj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_gds(outfile, cells=None, name='library', unit=1.0e-6, precision=1.0e-9):
""" Write the current GDSII library to a file. The dimensions actually written on the GDSII file will be the dimensions of the objects created times the ratio ``unit/precision``. For example, if a circle with radius 1.5 is created and we set ``unit=1.0e-6`` (1 um) and ``precision=1.0e-9`` (1 nm), the radius of the circle will be 1.5 um and the GDSII file will contain the dimension 1500 nm. Parameters outfile : file or string The file (or path) where the GDSII stream will be written. It must be opened for writing operations in binary format. cells : array-like The list of cells or cell names to be included in the library. If ``None``, all cells are used. name : string Name of the GDSII library. unit : number Unit size for the objects in the library (in *meters*). precision : number Precision for the dimensions of the objects in the library (in *meters*). """ |
current_library.name = name
current_library.unit = unit
current_library.precision = precision
current_library.write_gds(outfile, cells) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gdsii_hash(filename, engine=None):
""" Calculate the a hash value for a GDSII file. The hash is generated based only on the contents of the cells in the GDSII library, ignoring any timestamp records present in the file structure. Parameters filename : string Full path to the GDSII file. engine : hashlib-like engine The engine that executes the hashing algorithm. It must provide the methods ``update`` and ``hexdigest`` as defined in the hashlib module. If ``None``, the dafault ``hashlib.sha1()`` is used. Returns ------- out : string The hash correponding to the library contents in hex format. """ |
with open(filename, 'rb') as fin:
data = fin.read()
contents = []
start = pos = 0
while pos < len(data):
size, rec = struct.unpack('>HH', data[pos:pos + 4])
if rec == 0x0502:
start = pos + 28
elif rec == 0x0700:
contents.append(data[start:pos])
pos += size
h = hashlib.sha1() if engine is None else engine
for x in sorted(contents):
h.update(x)
return h.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bounding_box(self):
""" Returns the bounding box of the polygons. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this polygon in the form [[x_min, y_min], [x_max, y_max]], or ``None`` if the polygon is empty. """ |
if len(self.polygons) == 0:
return None
return numpy.array(((min(pts[:, 0].min() for pts in self.polygons),
min(pts[:, 1].min() for pts in self.polygons)),
(max(pts[:, 0].max() for pts in self.polygons),
max(pts[:, 1].max() for pts in self.polygons)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(self, scalex, scaley=None, center=(0, 0)):
""" Scale this object. Parameters scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ``scalex``. center : array-like[2] Center point for the scaling operation. Returns ------- out : ``PolygonSet`` This object. """ |
c0 = numpy.array(center)
s = scalex if scaley is None else numpy.array((scalex, scaley))
self.polygons = [(points - c0) * s + c0 for points in self.polygons]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_gds(self, multiplier):
""" Convert this object to a series of GDSII elements. Parameters multiplier : number A number that multiplies all dimensions written in the GDSII elements. Returns ------- out : string The GDSII binary string that represents this object. """ |
data = []
for ii in range(len(self.polygons)):
if len(self.polygons[ii]) > 4094:
raise ValueError("[GDSPY] Polygons with more than 4094 are "
"not supported by the GDSII format.")
data.append(
struct.pack('>10h', 4, 0x0800, 6, 0x0D02, self.layers[ii], 6,
0x0E02, self.datatypes[ii],
12 + 8 * len(self.polygons[ii]), 0x1003))
data.extend(
struct.pack('>2l', int(round(point[0] * multiplier)),
int(round(point[1] * multiplier)))
for point in self.polygons[ii])
data.append(
struct.pack('>2l2h',
int(round(self.polygons[ii][0][0] * multiplier)),
int(round(self.polygons[ii][0][1] * multiplier)),
4, 0x1100))
return b''.join(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fracture(self, max_points=199, precision=1e-3):
""" Slice these polygons in the horizontal and vertical directions so that each resulting piece has at most ``max_points``. This operation occurs in place. Parameters max_points : integer Maximal number of points in each resulting polygon (must be greater than 4). precision : float Desired precision for rounding vertice coordinates. Returns ------- out : ``PolygonSet`` This object. """ |
if max_points > 4:
ii = 0
while ii < len(self.polygons):
if len(self.polygons[ii]) > max_points:
pts0 = sorted(self.polygons[ii][:, 0])
pts1 = sorted(self.polygons[ii][:, 1])
ncuts = len(pts0) // max_points
if pts0[-1] - pts0[0] > pts1[-1] - pts1[0]:
# Vertical cuts
cuts = [
pts0[int(i * len(pts0) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 0,
1 / precision)
else:
# Horizontal cuts
cuts = [
pts1[int(i * len(pts1) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 1,
1 / precision)
self.polygons.pop(ii)
layer = self.layers.pop(ii)
datatype = self.datatypes.pop(ii)
self.polygons.extend(
numpy.array(x)
for x in itertools.chain.from_iterable(chopped))
npols = sum(len(c) for c in chopped)
self.layers.extend(layer for _ in range(npols))
self.datatypes.extend(datatype for _ in range(npols))
else:
ii += 1
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self, dx, dy):
""" Move the polygons from one place to another Parameters dx : number distance to move in the x-direction dy : number distance to move in the y-direction Returns ------- out : ``PolygonSet`` This object. """ |
vec = numpy.array((dx, dy))
self.polygons = [points + vec for points in self.polygons]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_gds(self, multiplier):
""" Convert this label to a GDSII structure. Parameters multiplier : number A number that multiplies all dimensions written in the GDSII structure. Returns ------- out : string The GDSII binary string that represents this label. """ |
text = self.text
if len(text) % 2 != 0:
text = text + '\0'
data = struct.pack('>11h', 4, 0x0C00, 6, 0x0D02, self.layer, 6, 0x1602,
self.texttype, 6, 0x1701, self.anchor)
if (self.rotation is not None) or (self.magnification is
not None) or self.x_reflection:
word = 0
values = b''
if self.x_reflection:
word += 0x8000
if not (self.magnification is None):
# This flag indicates that the magnification is absolute, not
# relative (not supported).
#word += 0x0004
values += struct.pack('>2h', 12, 0x1B05) + _eight_byte_real(
self.magnification)
if not (self.rotation is None):
# This flag indicates that the rotation is absolute, not
# relative (not supported).
#word += 0x0002
values += struct.pack('>2h', 12, 0x1C05) + _eight_byte_real(
self.rotation)
data += struct.pack('>2hH', 6, 0x1A01, word) + values
return data + struct.pack(
'>2h2l2h', 12, 0x1003, int(round(self.position[0] * multiplier)),
int(round(self.position[1] * multiplier)), 4 + len(text),
0x1906) + text.encode('ascii') + struct.pack('>2h', 4, 0x1100) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self, dx, dy):
""" Move the text from one place to another Parameters dx : float distance to move in the x-direction dy : float distance to move in the y-direction Returns ------- out : ``Label`` This object. Examples -------- """ |
self.position = numpy.array((dx + self.position[0],
dy + self.position[1]))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_gds(self, multiplier, timestamp=None):
""" Convert this cell to a GDSII structure. Parameters multiplier : number A number that multiplies all dimensions written in the GDSII structure. timestamp : datetime object Sets the GDSII timestamp. If ``None``, the current time is used. Returns ------- out : string The GDSII binary string that represents this cell. """ |
now = datetime.datetime.today() if timestamp is None else timestamp
name = self.name
if len(name) % 2 != 0:
name = name + '\0'
return struct.pack(
'>16h', 28, 0x0502, now.year, now.month, now.day, now.hour,
now.minute, now.second, now.year, now.month, now.day, now.hour,
now.minute, now.second, 4 + len(name),
0x0606) + name.encode('ascii') + b''.join(
element.to_gds(multiplier)
for element in self.elements) + b''.join(
label.to_gds(multiplier)
for label in self.labels) + struct.pack('>2h', 4, 0x0700) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, name, exclude_from_current=False, deep_copy=False):
""" Creates a copy of this cell. Parameters name : string The name of the cell. exclude_from_current : bool If ``True``, the cell will not be included in the global list of cells maintained by ``gdspy``. deep_copy : bool If ``False``, the new cell will contain only references to the existing elements. If ``True``, copies of all elements are also created. Returns ------- out : ``Cell`` The new copy of this cell. """ |
new_cell = Cell(name, exclude_from_current)
if deep_copy:
new_cell.elements = libCopy.deepcopy(self.elements)
new_cell.labels = libCopy.deepcopy(self.labels)
for ref in new_cell.get_dependencies(True):
if ref._bb_valid:
ref._bb_valid = False
else:
new_cell.elements = list(self.elements)
new_cell.labels = list(self.labels)
return new_cell |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, element):
""" Add a new element or list of elements to this cell. Parameters element : object, list The element or list of elements to be inserted in this cell. Returns ------- out : ``Cell`` This cell. """ |
if isinstance(element, list):
for e in element:
if isinstance(e, Label):
self.labels.append(e)
else:
self.elements.append(e)
else:
if isinstance(element, Label):
self.labels.append(element)
else:
self.elements.append(element)
self._bb_valid = False
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_polygons(self, test):
""" Remove polygons from this cell. The function or callable ``test`` is called for each polygon in the cell. If its return value evaluates to ``True``, the corresponding polygon is removed from the cell. Parameters test : callable Test function to query whether a polygon should be removed. The function is called with arguments: ``(points, layer, datatype)`` Returns ------- out : ``Cell`` This cell. Examples -------- Remove polygons in layer 1: Remove polygons with negative x coordinates: """ |
empty = []
for element in self.elements:
if isinstance(element, PolygonSet):
ii = 0
while ii < len(element.polygons):
if test(element.polygons[ii], element.layers[ii],
element.datatypes[ii]):
element.polygons.pop(ii)
element.layers.pop(ii)
element.datatypes.pop(ii)
else:
ii += 1
if len(element.polygons) == 0:
empty.append(element)
for element in empty:
self.elements.remove(element)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_labels(self, test):
""" Remove labels from this cell. The function or callable ``test`` is called for each label in the cell. If its return value evaluates to ``True``, the corresponding label is removed from the cell. Parameters test : callable Test function to query whether a label should be removed. The function is called with the label as the only argument. Returns ------- out : ``Cell`` This cell. Examples -------- Remove labels in layer 1: """ |
ii = 0
while ii < len(self.labels):
if test(self.labels[ii]):
self.labels.pop(ii)
else:
ii += 1
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def area(self, by_spec=False):
""" Calculate the total area of the elements on this cell, including cell references and arrays. Parameters by_spec : bool If ``True``, the return value is a dictionary with the areas of each individual pair (layer, datatype). Returns ------- out : number, dictionary Area of this cell. """ |
if by_spec:
cell_area = {}
for element in self.elements:
element_area = element.area(True)
for ll in element_area.keys():
if ll in cell_area:
cell_area[ll] += element_area[ll]
else:
cell_area[ll] = element_area[ll]
else:
cell_area = 0
for element in self.elements:
cell_area += element.area()
return cell_area |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_layers(self):
""" Returns a set of layers in this cell. Returns ------- out : set Set of the layers used in this cell. """ |
layers = set()
for element in self.elements:
if isinstance(element, PolygonSet):
layers.update(element.layers)
elif isinstance(element, CellReference) or isinstance(
element, CellArray):
layers.update(element.ref_cell.get_layers())
for label in self.labels:
layers.add(label.layer)
return layers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_datatypes(self):
""" Returns a set of datatypes in this cell. Returns ------- out : set Set of the datatypes used in this cell. """ |
datatypes = set()
for element in self.elements:
if isinstance(element, PolygonSet):
datatypes.update(element.datatypes)
elif isinstance(element, CellReference) or isinstance(
element, CellArray):
datatypes.update(element.ref_cell.get_datatypes())
return datatypes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bounding_box(self):
""" Returns the bounding box for this cell. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this cell [[x_min, y_min], [x_max, y_max]], or ``None`` if the cell is empty. """ |
if len(self.elements) == 0:
return None
if not (self._bb_valid and
all(ref._bb_valid for ref in self.get_dependencies(True))):
bb = numpy.array(((1e300, 1e300), (-1e300, -1e300)))
all_polygons = []
for element in self.elements:
if isinstance(element, PolygonSet):
all_polygons.extend(element.polygons)
elif isinstance(element, CellReference) or isinstance(
element, CellArray):
element_bb = element.get_bounding_box()
if element_bb is not None:
bb[0, 0] = min(bb[0, 0], element_bb[0, 0])
bb[0, 1] = min(bb[0, 1], element_bb[0, 1])
bb[1, 0] = max(bb[1, 0], element_bb[1, 0])
bb[1, 1] = max(bb[1, 1], element_bb[1, 1])
if len(all_polygons) > 0:
all_points = numpy.concatenate(all_polygons).transpose()
bb[0, 0] = min(bb[0, 0], all_points[0].min())
bb[0, 1] = min(bb[0, 1], all_points[1].min())
bb[1, 0] = max(bb[1, 0], all_points[0].max())
bb[1, 1] = max(bb[1, 1], all_points[1].max())
self._bb_valid = True
_bounding_boxes[self] = bb
return _bounding_boxes[self] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_polygons(self, by_spec=False, depth=None):
""" Returns a list of polygons in this cell. Parameters by_spec : bool If ``True``, the return value is a dictionary with the polygons of each individual pair (layer, datatype). depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve polygons. References below this level will result in a bounding box. If ``by_spec`` is ``True`` the key will be the name of this cell. Returns ------- out : list of array-like[N][2] or dictionary List containing the coordinates of the vertices of each polygon, or dictionary with the list of polygons (if ``by_spec`` is ``True``). """ |
if depth is not None and depth < 0:
bb = self.get_bounding_box()
if bb is None:
return {} if by_spec else []
pts = [
numpy.array([(bb[0, 0], bb[0, 1]), (bb[0, 0], bb[1, 1]),
(bb[1, 0], bb[1, 1]), (bb[1, 0], bb[0, 1])])
]
polygons = {self.name: pts} if by_spec else pts
else:
if by_spec:
polygons = {}
for element in self.elements:
if isinstance(element, PolygonSet):
for ii in range(len(element.polygons)):
key = (element.layers[ii], element.datatypes[ii])
if key in polygons:
polygons[key].append(
numpy.array(element.polygons[ii]))
else:
polygons[key] = [
numpy.array(element.polygons[ii])
]
else:
cell_polygons = element.get_polygons(
True, None if depth is None else depth - 1)
for kk in cell_polygons.keys():
if kk in polygons:
polygons[kk].extend(cell_polygons[kk])
else:
polygons[kk] = cell_polygons[kk]
else:
polygons = []
for element in self.elements:
if isinstance(element, PolygonSet):
for points in element.polygons:
polygons.append(numpy.array(points))
else:
polygons.extend(
element.get_polygons(
depth=None if depth is None else depth - 1))
return polygons |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_labels(self, depth=None):
""" Returns a list with a copy of the labels in this cell. Parameters depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------- out : list of ``Label`` List containing the labels in this cell and its references. """ |
labels = libCopy.deepcopy(self.labels)
if depth is None or depth > 0:
for element in self.elements:
if isinstance(element, CellReference):
labels.extend(
element.get_labels(None if depth is None else depth -
1))
elif isinstance(element, CellArray):
labels.extend(
element.get_labels(None if depth is None else depth -
1))
return labels |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dependencies(self, recursive=False):
""" Returns a list of the cells included in this cell as references. Parameters recursive : bool If True returns cascading dependencies. Returns ------- out : set of ``Cell`` List of the cells referenced by this cell. """ |
dependencies = set()
for element in self.elements:
if isinstance(element, CellReference) or isinstance(
element, CellArray):
if recursive:
dependencies.update(
element.ref_cell.get_dependencies(True))
dependencies.add(element.ref_cell)
return dependencies |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(self, single_layer=None, single_datatype=None, single_texttype=None):
""" Flatten all ``CellReference`` and ``CellArray`` elements in this cell into real polygons and labels, instead of references. Parameters single_layer : integer or None If not ``None``, all polygons will be transfered to the layer indicated by this number. single_datatype : integer or None If not ``None``, all polygons will be transfered to the datatype indicated by this number. single_datatype : integer or None If not ``None``, all labels will be transfered to the texttype indicated by this number. Returns ------- out : ``Cell`` This cell. """ |
self.labels = self.get_labels()
if single_layer is not None:
for lbl in self.labels:
lbl.layer = single_layer
if single_texttype is not None:
for lbl in self.labels:
lbl.texttype = single_texttype
if single_layer is None or single_datatype is None:
poly_dic = self.get_polygons(True)
self.elements = []
if single_layer is None and single_datatype is None:
for ld in poly_dic.keys():
self.add(PolygonSet(poly_dic[ld], *ld, verbose=False))
elif single_layer is None:
for ld in poly_dic.keys():
self.add(
PolygonSet(
poly_dic[ld],
ld[0],
single_datatype,
verbose=False))
else:
for ld in poly_dic.keys():
self.add(
PolygonSet(
poly_dic[ld], single_layer, ld[1], verbose=False))
else:
polygons = self.get_polygons()
self.elements = []
self.add(
PolygonSet(
polygons, single_layer, single_datatype, verbose=False))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def area(self, by_spec=False):
""" Calculate the total area of the referenced cell with the magnification factor included. Parameters by_spec : bool If ``True``, the return value is a dictionary with the areas of each individual pair (layer, datatype). Returns ------- out : number, dictionary Area of this cell. """ |
if not isinstance(self.ref_cell, Cell):
return dict() if by_spec else 0
if self.magnification is None:
return self.ref_cell.area(by_spec)
else:
if by_spec:
factor = self.magnification**2
cell_area = self.ref_cell.area(True)
for kk in cell_area.keys():
cell_area[kk] *= factor
return cell_area
else:
return self.ref_cell.area() * self.magnification**2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bounding_box(self):
""" Returns the bounding box for this reference. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this cell [[x_min, y_min], [x_max, y_max]], or ``None`` if the cell is empty. """ |
if not isinstance(self.ref_cell, Cell):
return None
if (self.rotation is None and self.magnification is None and
self.x_reflection is None):
key = self
else:
key = (self.ref_cell, self.rotation, self.magnification,
self.x_reflection)
deps = self.ref_cell.get_dependencies(True)
if not (self.ref_cell._bb_valid and
all(ref._bb_valid for ref in deps) and key in _bounding_boxes):
for ref in deps:
ref.get_bounding_box()
self.ref_cell.get_bounding_box()
tmp = self.origin
self.origin = None
polygons = self.get_polygons()
self.origin = tmp
if len(polygons) == 0:
bb = None
else:
all_points = numpy.concatenate(polygons).transpose()
bb = numpy.array(((all_points[0].min(), all_points[1].min()),
(all_points[0].max(), all_points[1].max())))
_bounding_boxes[key] = bb
else:
bb = _bounding_boxes[key]
if self.origin is None or bb is None:
return bb
else:
return bb + numpy.array(((self.origin[0], self.origin[1]),
(self.origin[0], self.origin[1]))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self, dx, dy):
""" Move the reference from one place to another Parameters dx : float distance to move in the x-direction dy : float distance to move in the y-direction Returns ------- out : ``CellReference`` This object. """ |
self.origin = (self.origin[0] + dx, self.origin[1] + dy)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, cell, overwrite_duplicate=False):
""" Add one or more cells to the library. Parameters cell : ``Cell`` of list of ``Cell`` Cells to be included in the library. overwrite_duplicate : bool If True an existing cell with the same name in the library will be overwritten. Returns ------- out : ``GdsLibrary`` This object. """ |
if isinstance(cell, Cell):
if (not overwrite_duplicate and cell.name in self.cell_dict and
self.cell_dict[cell.name] is not cell):
raise ValueError("[GDSPY] cell named {0} already present in "
"library.".format(cell.name))
self.cell_dict[cell.name] = cell
else:
for c in cell:
if (not overwrite_duplicate and c.name in self.cell_dict and
self.cell_dict[c.name] is not c):
raise ValueError("[GDSPY] cell named {0} already present "
"in library.".format(c.name))
self.cell_dict[c.name] = c
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_gds(self, outfile, cells=None, timestamp=None):
""" Write the GDSII library to a file. The dimensions actually written on the GDSII file will be the dimensions of the objects created times the ratio ``unit/precision``. For example, if a circle with radius 1.5 is created and we set ``unit=1.0e-6`` (1 um) and ``precision=1.0e-9`` (1 nm), the radius of the circle will be 1.5 um and the GDSII file will contain the dimension 1500 nm. Parameters outfile : file or string The file (or path) where the GDSII stream will be written. It must be opened for writing operations in binary format. cells : array-like The list of cells or cell names to be included in the library. If ``None``, all cells are used. timestamp : datetime object Sets the GDSII timestamp. If ``None``, the current time is used. Notes ----- Only the specified cells are written. The user is responsible for ensuring all cell dependencies are satisfied. """ |
if isinstance(outfile, basestring):
outfile = open(outfile, 'wb')
close = True
else:
close = False
now = datetime.datetime.today() if timestamp is None else timestamp
name = self.name if len(self.name) % 2 == 0 else (self.name + '\0')
outfile.write(
struct.pack('>19h', 6, 0x0002, 0x0258, 28, 0x0102, now.year,
now.month, now.day, now.hour, now.minute, now.second,
now.year, now.month, now.day, now.hour, now.minute,
now.second, 4 + len(name), 0x0206) +
name.encode('ascii') + struct.pack('>2h', 20, 0x0305) +
_eight_byte_real(self.precision / self.unit) +
_eight_byte_real(self.precision))
if cells is None:
cells = self.cell_dict.values()
else:
cells = [self.cell_dict.get(c, c) for c in cells]
for cell in cells:
outfile.write(cell.to_gds(self.unit / self.precision))
outfile.write(struct.pack('>2h', 4, 0x0400))
if close:
outfile.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_record(self, stream):
""" Read a complete record from a GDSII stream file. Parameters stream : file GDSII stream file to be imported. Returns ------- out : 2-tuple Record type and data (as a numpy.array) """ |
header = stream.read(4)
if len(header) < 4:
return None
size, rec_type = struct.unpack('>HH', header)
data_type = (rec_type & 0x00ff)
rec_type = rec_type // 256
data = None
if size > 4:
if data_type == 0x01:
data = numpy.array(
struct.unpack('>{0}H'.format((size - 4) // 2),
stream.read(size - 4)),
dtype='uint')
elif data_type == 0x02:
data = numpy.array(
struct.unpack('>{0}h'.format((size - 4) // 2),
stream.read(size - 4)),
dtype='int')
elif data_type == 0x03:
data = numpy.array(
struct.unpack('>{0}l'.format((size - 4) // 4),
stream.read(size - 4)),
dtype='int')
elif data_type == 0x05:
data = numpy.array([
_eight_byte_real_to_float(stream.read(8))
for _ in range((size - 4) // 8)
])
else:
data = stream.read(size - 4)
if str is not bytes:
if data[-1] == 0:
data = data[:-1].decode('ascii')
else:
data = data.decode('ascii')
elif data[-1] == '\0':
data = data[:-1]
return [rec_type, data] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(self, cell):
""" Extract a cell from the this GDSII file and include it in the current global library, including referenced dependencies. Parameters cell : ``Cell`` or string Cell or name of the cell to be extracted from the imported file. Referenced cells will be automatically extracted as well. Returns ------- out : ``Cell`` The extracted cell. """ |
cell = self.cell_dict.get(cell, cell)
current_library.add(cell)
current_library.add(cell.get_dependencies(True))
return cell |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def top_level(self):
""" Output the top level cells from the GDSII data. Top level cells are those that are not referenced by any other cells. Returns ------- out : list List of top level cells. """ |
top = list(self.cell_dict.values())
for cell in self.cell_dict.values():
for dependency in cell.get_dependencies():
if dependency in top:
top.remove(dependency)
return top |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_cell(self, cell):
""" Write the specified cell to the file. Parameters cell : ``Cell`` Cell to be written. Notes ----- Only the specified cell is written. Dependencies must be manually included. Returns ------- out : ``GdsWriter`` This object. """ |
self._outfile.write(cell.to_gds(self._res))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Finalize the GDSII stream library. """ |
self._outfile.write(struct.pack('>2h', 4, 0x0400))
if self._close:
self._outfile.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def waveguide(path,
points,
finish,
bend_radius,
number_of_points=0.01,
direction=None,
layer=0,
datatype=0):
'''
Easy waveguide creation tool with absolute positioning.
path : starting `gdspy.Path`
points : coordinates along which the waveguide will travel
finish : end point of the waveguide
bend_radius : radius of the turns in the waveguide
number_of_points : same as in `path.turn`
direction : starting direction
layer : GDSII layer number
datatype : GDSII datatype number
Return `path`.
'''
if direction is not None:
path.direction = direction
axis = 0 if path.direction[1] == 'x' else 1
points.append(finish[(axis + len(points)) % 2])
n = len(points)
if points[0] > (path.x, path.y)[axis]:
path.direction = ['+x', '+y'][axis]
else:
path.direction = ['-x', '-y'][axis]
for i in range(n):
path.segment(
abs(points[i] - (path.x, path.y)[axis]) - bend_radius,
layer=layer,
datatype=datatype)
axis = 1 - axis
if i < n - 1:
goto = points[i + 1]
else:
goto = finish[axis]
if (goto > (path.x, path.y)[axis]) ^ ((path.direction[0] == '+') ^
(path.direction[1] == 'x')):
bend = 'l'
else:
bend = 'r'
path.turn(
bend_radius,
bend,
number_of_points=number_of_points,
layer=layer,
datatype=datatype)
return path.segment(
abs(finish[axis] - (path.x, path.y)[axis]),
layer=layer,
datatype=datatype) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.