docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
---|---|---|
Get a list of rated moview for a specific guest session id.
Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def rated_movies(self, **kwargs):
path = self._get_guest_session_id_path('rated_movies')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,810 |
Check to see if a movie id is already added to a list.
Args:
movie_id: The id of the movie.
Returns:
A dict respresentation of the JSON returned from the API.
|
def item_status(self, **kwargs):
path = self._get_id_path('item_status')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,812 |
Create a new list.
A valid session id is required.
Args:
name: Name of the list.
description: Description of the list.
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def create_list(self, **kwargs):
path = self._get_path('create_list')
kwargs.update({'session_id': self.session_id})
payload = {
'name': kwargs.pop('name', None),
'description': kwargs.pop('description', None),
}
if 'language' in kwargs:
payload['language'] = kwargs['language']
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response
| 243,813 |
Delete movies from a list that the user created.
A valid session id is required.
Args:
media_id: A movie id.
Returns:
A dict respresentation of the JSON returned from the API.
|
def remove_item(self, **kwargs):
path = self._get_id_path('remove_item')
kwargs.update({'session_id': self.session_id})
payload = {
'media_id': kwargs.pop('media_id', None),
}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response
| 243,814 |
Clears all of the items within a list. This is an irreversible action
and should be treated with caution.
A valid session id is required.
Args:
confirm: True (do it) | False (don't do it)
Returns:
A dict respresentation of the JSON returned from the API.
|
def clear_list(self, **kwargs):
path = self._get_id_path('clear')
kwargs.update({'session_id': self.session_id})
payload = {}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response
| 243,815 |
Get the content ratings for a TV Series.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any collection
method.
Returns:
A dict respresentation of the JSON returned from the API.
|
def content_ratings(self, **kwargs):
path = self._get_id_path('content_ratings')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,817 |
Get the similar TV series for a specific TV series id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any TV method.
Returns:
A dict respresentation of the JSON returned from the API.
|
def similar(self, **kwargs):
path = self._get_id_path('similar')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,818 |
Get the most newly created TV show. This is a live response
and will continuously change.
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def latest(self, **kwargs):
path = self._get_id_path('latest')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,819 |
Get the list of TV shows that are currently on the air. This query
looks for any TV show that has an episode with an air date in the
next 7 days.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def on_the_air(self, **kwargs):
path = self._get_path('on_the_air')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,820 |
Get the list of TV shows that air today. Without a specified timezone,
this query defaults to EST (Eastern Time UTC-05:00).
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
timezone: (optional) Valid value from the list of timezones.
Returns:
A dict respresentation of the JSON returned from the API.
|
def airing_today(self, **kwargs):
path = self._get_path('airing_today')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,821 |
Get the primary information about a TV season by its season number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
A dict respresentation of the JSON returned from the API.
|
def info(self, **kwargs):
path = self._get_series_id_season_number_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,823 |
Get the external ids that we have stored for a TV season by season
number.
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def external_ids(self, **kwargs):
path = self._get_series_id_season_number_path('external_ids')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,825 |
Get the images (posters) that we have stored for a TV season by season
number.
Args:
language: (optional) ISO 639 code.
include_image_language: (optional) Comma separated, a valid
ISO 69-1.
Returns:
A dict respresentation of the JSON returned from the API.
|
def images(self, **kwargs):
path = self._get_series_id_season_number_path('images')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,826 |
Get the videos that have been added to a TV season (trailers, teasers,
etc...).
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def videos(self, **kwargs):
path = self._get_series_id_season_number_path('videos')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,827 |
Get the primary information about a TV episode by combination of a
season and episode number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
A dict respresentation of the JSON returned from the API.
|
def info(self, **kwargs):
path = self._get_series_id_season_number_episode_number_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,829 |
Get the external ids for a TV episode by combination of a season and
episode number.
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def external_ids(self, **kwargs):
path = self._get_series_id_season_number_episode_number_path(
'external_ids')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,831 |
Get the videos that have been added to a TV episode (teasers, clips,
etc...).
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def videos(self, **kwargs):
path = self._get_series_id_season_number_episode_number_path('videos')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,833 |
Search for collections by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
|
def collection(self, **kwargs):
path = self._get_path('collection')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,848 |
Search for companies by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict respresentation of the JSON returned from the API.
|
def company(self, **kwargs):
path = self._get_path('company')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,851 |
Search for keywords by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict respresentation of the JSON returned from the API.
|
def keyword(self, **kwargs):
path = self._get_path('keyword')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,852 |
Search the movie, tv show and person collections with a single query.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
include_adult: (optional) Toggle the inclusion of adult titles.
Expected value is True or False.
Returns:
A dict respresentation of the JSON returned from the API.
|
def multi(self, **kwargs):
path = self._get_path('multi')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response
| 243,853 |
Puts the ProgressBar bar in the finished state.
Also flushes and disables output buffering if this was the last
progressbar running.
Args:
end (str): The string to end the progressbar with, defaults to a
newline
dirty (bool): When True the progressbar kept the current state and
won't be set to 100 percent
|
def finish(self, end='\n', dirty=False):
if not dirty:
self.end_time = datetime.now()
self.update(self.max_value, force=True)
StdRedirectMixin.finish(self, end=end)
ResizableMixin.finish(self)
ProgressBarBase.finish(self)
| 244,227 |
A QAOA circuit for the Quadratic Unconstrained Binary Optimization
problem (i.e. an Ising model).
Args:
graph : a networkx graph instance with optional edge and node weights
steps : number of QAOA steps
beta : driver parameters (One per step)
gamma : cost parameters (One per step)
|
def qubo_circuit(
graph: nx.Graph,
steps: int,
beta: Sequence,
gamma: Sequence) -> Circuit:
qubits = list(graph.nodes())
# Initialization
circ = Circuit()
for q0 in qubits:
circ += H(q0)
# Run for given number of QAOA steps
for p in range(0, steps):
# Cost
for q0, q1 in graph.edges():
weight = graph[q0][q1].get('weight', 1.0)
# Note factor of pi due to parameterization of ZZ gate
circ += ZZ(-weight * gamma[p] / np.pi, q0, q1)
for q0 in qubits:
node_weight = graph.nodes[q0].get('weight', None)
if node_weight is not None:
circ += RZ(node_weight, q0)
# Drive
for q0 in qubits:
circ += RX(beta[p], q0)
return circ
| 244,347 |
Return the circuit depth.
Args:
local: If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth.
|
def depth(self, local: bool = True) -> int:
G = self.graph
if not local:
def remove_local(dagc: DAGCircuit) \
-> Generator[Operation, None, None]:
for elem in dagc:
if dagc.graph.degree[elem] > 2:
yield elem
G = DAGCircuit(remove_local(self)).graph
return nx.dag_longest_path_length(G) - 1
| 244,353 |
Pretty print state probabilities.
Args:
state:
ndigits: Number of digits of accuracy
file: Output stream (Defaults to stdout)
|
def print_probabilities(state: State, ndigits: int = 4,
file: TextIO = None) -> None:
prob = bk.evaluate(state.probabilities())
for index, prob in np.ndenumerate(prob):
prob = round(prob, ndigits)
if prob == 0.0:
continue
ket = "".join([str(n) for n in index])
print(ket, ":", prob, file=file)
| 244,365 |
Create a new State from a tensor of qubit amplitudes
Args:
tensor: A vector or tensor of state amplitudes
qubits: A sequence of qubit names.
(Defaults to integer indices, e.g. [0, 1, 2] for 3 qubits)
memory: Classical memory.
|
def __init__(self,
tensor: bk.TensorLike,
qubits: Qubits = None,
memory: Dict[Addr, Any] = None) -> None: # DOCME TESTME
if qubits is None:
tensor = bk.astensorproduct(tensor)
bits = bk.rank(tensor)
qubits = range(bits)
self.vec = QubitVector(tensor, qubits)
self._memory = memory if memory is not None else {}
| 244,369 |
Convert a floating point number to a Fraction with a small
denominator.
Args:
flt: A floating point number
denominators: Collection of standard denominators. Default is
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512,
1024, 2048, 4096, 8192
Raises:
ValueError: If cannot rationalize float
|
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction:
if denominators is None:
denominators = _DENOMINATORS
frac = Fraction.from_float(flt).limit_denominator()
if frac.denominator not in denominators:
raise ValueError('Cannot rationalize')
return frac
| 244,415 |
Load a pyQuil program, and initialize QVM into a fresh state.
Args:
binary: A pyQuil program
|
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM':
assert self.status in ['connected', 'done']
prog = quil_to_program(str(binary))
self._prog = prog
self.program = binary
self.status = 'loaded'
return self
| 244,424 |
Returns the von-Neumann entropy of a mixed quantum state.
Args:
rho: A density matrix
base: Optional logarithm base. Default is base e, and entropy is
measures in nats. For bits set base to 2.
Returns:
The von-Neumann entropy of rho
|
def entropy(rho: Density, base: float = None) -> float:
op = asarray(rho.asoperator())
probs = np.linalg.eigvalsh(op)
probs = np.maximum(probs, 0.0) # Compensate for floating point errors
return scipy.stats.entropy(probs, base=base)
| 244,456 |
Compute the bipartite von-Neumann mutual information of a mixed
quantum state.
Args:
rho: A density matrix of the complete system
qubits0: Qubits of system 0
qubits1: Qubits of system 1. If none, taken to be all remaining qubits
base: Optional logarithm base. Default is base e
Returns:
The bipartite von-Neumann mutual information.
|
def mutual_info(rho: Density,
qubits0: Qubits,
qubits1: Qubits = None,
base: float = None) -> float:
if qubits1 is None:
qubits1 = tuple(set(rho.qubits) - set(qubits0))
rho0 = rho.partial_trace(qubits1)
rho1 = rho.partial_trace(qubits0)
ent = entropy(rho, base)
ent0 = entropy(rho0, base)
ent1 = entropy(rho1, base)
return ent0 + ent1 - ent
| 244,457 |
Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX document as a string.
Returns:
A PIL Image
Raises:
OSError: If an external dependency is not installed.
|
def render_latex(latex: str) -> PIL.Image: # pragma: no cover
tmpfilename = 'circ'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename)
with open(tmppath + '.tex', 'w') as latex_file:
latex_file.write(latex)
subprocess.run(["pdflatex",
"-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename+'.tex')],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True)
subprocess.run(['pdftocairo',
'-singlefile',
'-png',
'-q',
tmppath + '.pdf',
tmppath])
img = PIL.Image.open(tmppath + '.png')
return img
| 244,559 |
Create an image of a quantum circuit.
A convenience function that calls circuit_to_latex() and render_latex().
Args:
circ: A quantum Circuit
qubits: Optional qubit list to specify qubit order
Returns:
Returns: A PIL Image (Use img.show() to display)
Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed.
|
def circuit_to_image(circ: Circuit,
qubits: Qubits = None) -> PIL.Image: # pragma: no cover
latex = circuit_to_latex(circ, qubits)
img = render_latex(latex)
return img
| 244,560 |
Print version strings of currently installed dependencies
``> python -m quantumflow.meta``
Args:
file: Output stream. Defaults to stdout.
|
def print_versions(file: typing.TextIO = None) -> None:
print('** QuantumFlow dependencies (> python -m quantumflow.meta) **')
print('quantumflow \t', qf.__version__, file=file)
print('python \t', sys.version[0:5], file=file)
print('numpy \t', np.__version__, file=file)
print('networkx \t', nx.__version__, file=file)
print('cvxpy \t', cvx.__version__, file=file)
print('pyquil \t', pyquil.__version__, file=file)
print(bk.name, ' \t', bk.version, '(BACKEND)', file=file)
| 244,563 |
Pretty print a gate tensor
Args:
gate:
ndigits:
file: Stream to which to write. Defaults to stdout
|
def print_gate(gate: Gate, ndigits: int = 2,
file: TextIO = None) -> None:
N = gate.qubit_nb
gate_tensor = gate.vec.asarray()
lines = []
for index, amplitude in np.ndenumerate(gate_tensor):
ket = "".join([str(n) for n in index[0:N]])
bra = "".join([str(index[n]) for n in range(N, 2*N)])
if round(abs(amplitude)**2, ndigits) > 0.0:
lines.append('{} -> {} : {}'.format(bra, ket, amplitude))
lines.sort(key=lambda x: int(x[0:N]))
print('\n'.join(lines), file=file)
| 244,653 |
Set new absolute progress position.
Parameters:
pos: new absolute progress
|
def update(self, pos):
self.pos = pos
self.now = time.time()
| 247,472 |
Prints the core's information.
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
|
def main(jlink_serial, device):
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
sys.stdout.write('ARM Id: %d\n' % jlink.core_id())
sys.stdout.write('CPU Id: %d\n' % jlink.core_cpu())
sys.stdout.write('Core Name: %s\n' % jlink.core_name())
sys.stdout.write('Device Family: %d\n' % jlink.device_family())
| 249,946 |
Creates an instance of a ``JLock`` and populates the name.
Note:
This method may fail if there is no temporary directory in which to
have the lockfile placed.
Args:
self (JLock): the ``JLock`` instance
serial_no (int): the serial number of the J-Link
Returns:
``None``
|
def __init__(self, serial_no):
self.name = self.SERIAL_NAME_FMT.format(serial_no)
self.acquired = False
self.fd = None
self.path = None
self.path = os.path.join(tempfile.tempdir, self.name)
| 249,947 |
Attempts to acquire a lock for the J-Link lockfile.
If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.
Args:
self (Jlock): the ``JLock`` instance
Returns:
``True`` if the lock was acquired, otherwise ``False``.
Raises:
OSError: on file errors.
|
def acquire(self):
if os.path.exists(self.path):
try:
pid = None
with open(self.path, 'r') as f:
line = f.readline().strip()
pid = int(line)
# In the case that the lockfile exists, but the pid does not
# correspond to a valid process, remove the file.
if not psutil.pid_exists(pid):
os.remove(self.path)
except ValueError as e:
# Pidfile is invalid, so just delete it.
os.remove(self.path)
except IOError as e:
# Something happened while trying to read/remove the file, so
# skip trying to read/remove it.
pass
try:
self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
# PID is written to the file, so that if a process exits wtihout
# cleaning up the lockfile, we can still acquire the lock.
to_write = '%s%s' % (os.getpid(), os.linesep)
os.write(self.fd, to_write.encode())
except OSError as e:
if not os.path.exists(self.path):
raise
return False
self.acquired = True
return True
| 249,948 |
Cleans up the lockfile if it was acquired.
Args:
self (JLock): the ``JLock`` instance
Returns:
``False`` if the lock was not released or the lock is not acquired,
otherwise ``True``.
|
def release(self):
if not self.acquired:
return False
os.close(self.fd)
if os.path.exists(self.path):
os.remove(self.path)
self.acquired = False
return True
| 249,949 |
Initializes the base class.
Args:
self (ReadRequest): the ``ReadRequest`` instance
address (int): the register index
ap (bool): ``True`` if this request is to an Access Port Access
Register, otherwise ``False`` for a Debug Port Access Register
Returns:
``None``
|
def __init__(self, address, ap):
super(ReadRequest, self).__init__(address=address, ap=ap)
| 249,951 |
Initializes the base class.
Args:
self (WriteRequest): the ``WriteRequest`` instance
address (int): the register index
ap (bool): ``True`` if this request is to an Access Port Access
Register, otherwise ``False`` for a Debug Port Access Register
Returns:
``None``
|
def __init__(self, address, ap, data):
super(WriteRequest, self).__init__(address=address, ap=ap, data=data)
| 249,953 |
Callback that can be used with ``JLink.flash()``.
This callback generates a progress bar in the console to show the progress
of each of the steps of the flash.
Args:
action (str): the current action being invoked
progress_string (str): the current step in the progress
percentage (int): the percent to which the current step has been done
Returns:
``None``
Note:
This function ignores the compare action.
|
def flash_progress_callback(action, progress_string, percentage):
if action.lower() != 'compare':
return progress_bar(min(100, percentage), 100, prefix=action)
return None
| 249,956 |
Calculates and returns the parity of a number.
The parity of a number is ``1`` if the number has an odd number of ones
in its binary representation, otherwise ``0``.
Args:
n (int): the number whose parity to calculate
Returns:
``1`` if the number has an odd number of ones, otherwise ``0``.
Raises:
ValueError: if ``n`` is less than ``0``.
|
def calculate_parity(n):
if not is_natural(n):
raise ValueError('Expected n to be a positive integer.')
y = 0
n = abs(n)
while n:
y += n & 1
n = n >> 1
return y & 1
| 249,957 |
Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
|
def serial_wire_viewer(jlink_serial, device):
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface. Need this in order to use
# Serial Wire Output.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
jlink.coresight_configure()
jlink.set_reset_strategy(pylink.enums.JLinkResetStrategyCortexM3.RESETPIN)
# Have to halt the CPU before getitng its speed.
jlink.reset()
jlink.halt()
# Output the information about the program.
sys.stdout.write('Serial Wire Viewer\n')
sys.stdout.write('Press Ctrl-C to Exit\n')
sys.stdout.write('Reading data from port 0:\n\n')
# Reset the core without halting so that it runs.
jlink.reset(ms=10, halt=False)
# Use the `try` loop to catch a keyboard interrupt in order to stop logging
# serial wire output.
try:
while True:
# Check the vector catch.
if jlink.register_read(0x0) != 0x05:
continue
offset = jlink.register_read(0x1)
handle, ptr, num_bytes = jlink.memory_read32(offset, 3)
read = ''.join(map(chr, jlink.memory_read8(ptr, num_bytes)))
if num_bytes == 0:
# If no bytes exist, sleep for a bit before trying again.
time.sleep(1)
continue
jlink.register_write(0x0, 0)
jlink.step(thumb=True)
jlink.restart(2, skip_breakpoints=True)
sys.stdout.write(read)
sys.stdout.flush()
except KeyboardInterrupt:
pass
sys.stdout.write('\n')
return 0
| 249,958 |
Populate the attributes.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
|
def finalize_options(self):
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.build_dirs = [
os.path.join(self.cwd, 'build'),
os.path.join(self.cwd, 'htmlcov'),
os.path.join(self.cwd, 'dist'),
os.path.join(self.cwd, 'pylink_square.egg-info')
]
self.build_artifacts = ['.pyc', '.o', '.elf', '.bin']
| 249,961 |
Runs the command.
Args:
self (CleanCommand): the ``CleanCommand`` instance
Returns:
``None``
|
def run(self):
for build_dir in self.build_dirs:
if os.path.isdir(build_dir):
sys.stdout.write('Removing %s%s' % (build_dir, os.linesep))
shutil.rmtree(build_dir)
for (root, dirs, files) in os.walk(self.cwd):
for name in files:
fullpath = os.path.join(root, name)
if any(fullpath.endswith(ext) for ext in self.build_artifacts):
sys.stdout.write('Removing %s%s' % (fullpath, os.linesep))
os.remove(fullpath)
| 249,962 |
Finalizes the command's options.
Args:
self (CoverageCommand): the ``CoverageCommand`` instance
Returns:
``None``
|
def finalize_options(self):
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.test_dir = os.path.join(self.cwd, 'tests')
| 249,963 |
Populate the attributes.
Args:
self (BDDTestCommand): the ``BDDTestCommand`` instance
Returns:
``None``
|
def finalize_options(self):
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.features_dir = os.path.join(self.cwd, 'tests', 'functional', 'features')
self.firmware_dirs = []
root = os.path.join(self.cwd, 'tests', 'functional', 'firmware')
for f in os.listdir(root):
fullpath = os.path.join(root, f)
if os.path.isdir(fullpath):
self.firmware_dirs.append(fullpath)
| 249,964 |
Runs the command.
Args:
self (BDDTestCommand): the ``BDDTestCommand`` instance
Returns:
``True`` on success, otherwise ``False``.
Raises:
ValueError: if a build fails
|
def run(self):
import behave.__main__ as behave
for d in self.firmware_dirs:
original_dir = os.getcwd()
os.chdir(d)
output = ''
try:
output = subprocess.check_output('make', shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if output:
sys.stdout.write('Captured Output:%s%s%s' % (os.linesep, output, os.linesep))
os.chdir(original_dir)
raise e
os.chdir(original_dir)
return behave.main([self.features_dir])
| 249,965 |
Returns the string message for the given ``error_code``.
Args:
cls (JlinkGlobalErrors): the ``JLinkGlobalErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.EMU_NO_CONNECTION:
return 'No connection to emulator.'
elif error_code == cls.EMU_COMM_ERROR:
return 'Emulator connection error.'
elif error_code == cls.DLL_NOT_OPEN:
return 'DLL has not been opened. Did you call \'.connect()\'?'
elif error_code == cls.VCC_FAILURE:
return 'Target system has no power.'
elif error_code == cls.INVALID_HANDLE:
return 'Given file / memory handle is invalid.'
elif error_code == cls.NO_CPU_FOUND:
return 'Could not find supported CPU.'
elif error_code == cls.EMU_FEATURE_UNSUPPORTED:
return 'Emulator does not support the selected feature.'
elif error_code == cls.EMU_NO_MEMORY:
return 'Emulator out of memory.'
elif error_code == cls.TIF_STATUS_ERROR:
return 'Target interface error.'
elif error_code == cls.FLASH_PROG_COMPARE_FAILED:
return 'Programmed data differs from source data.'
elif error_code == cls.FLASH_PROG_PROGRAM_FAILED:
return 'Programming error occured.'
elif error_code == cls.FLASH_PROG_VERIFY_FAILED:
return 'Error while verifying programmed data.'
elif error_code == cls.OPEN_FILE_FAILED:
return 'Specified file could not be opened.'
elif error_code == cls.UNKNOWN_FILE_FORMAT:
return 'File format of selected file is not supported.'
elif error_code == cls.WRITE_TARGET_MEMORY_FAILED:
return 'Could not write target memory.'
elif error_code == cls.DEVICE_FEATURE_NOT_SUPPORTED:
return 'Feature not supported by connected device.'
elif error_code == cls.WRONG_USER_CONFIG:
return 'User configured DLL parameters incorrectly.'
elif error_code == cls.NO_TARGET_DEVICE_SELECTED:
return 'User did not specify core to connect to.'
elif error_code == cls.CPU_IN_LOW_POWER_MODE:
return 'Target CPU is in low power mode.'
elif error_code == cls.UNSPECIFIED_ERROR:
return 'Unspecified error.'
raise ValueError('Invalid error code: %d' % error_code)
| 249,966 |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.ILLEGAL_COMMAND:
return 'Failed to erase sector.'
return super(JLinkEraseErrors, cls).to_string(error_code)
| 249,967 |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkFlashErrors): the ``JLinkFlashErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.COMPARE_ERROR:
return 'Error comparing flash content to programming data.'
elif error_code == cls.PROGRAM_ERASE_ERROR:
return 'Error during program/erase phase.'
elif error_code == cls.VERIFICATION_ERROR:
return 'Error verifying programmed data.'
return super(JLinkFlashErrors, cls).to_string(error_code)
| 249,968 |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkWriteErrors): the ``JLinkWriteErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkWriteErrors, cls).to_string(error_code)
| 249,969 |
Returns the string message for the given ``error_code``.
Args:
cls (JLinkReadErrors): the ``JLinkReadErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkReadErrors, cls).to_string(error_code)
| 249,970 |
Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.ERROR_UNKNOWN:
return 'Unknown error.'
elif error_code == cls.ERROR_NO_MORE_EVENTS:
return 'There are no more available watchpoint units.'
elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return 'No more address comparisons can be set.'
elif error_code == cls.ERROR_NO_MORE_DATA_COMP:
return 'No more data comparisons can be set.'
elif error_code == cls.ERROR_INVALID_ADDR_MASK:
return 'Invalid flags passed for the address mask.'
elif error_code == cls.ERROR_INVALID_DATA_MASK:
return 'Invalid flags passed for the data mask.'
elif error_code == cls.ERROR_INVALID_ACCESS_MASK:
return 'Invalid flags passed for the access mask.'
return super(JLinkDataErrors, cls).to_string(error_code)
| 249,971 |
Returns the string message for the given error code.
Args:
cls (JLinkRTTErrors): the ``JLinkRTTErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
|
def to_string(cls, error_code):
if error_code == cls.RTT_ERROR_CONTROL_BLOCK_NOT_FOUND:
return 'The RTT Control Block has not yet been found (wait?)'
return super(JLinkRTTErrors, cls).to_string(error_code)
| 249,972 |
Checks whether the given flags are a valid identity.
Args:
identity (Identity): the identity to validate against
flags (register.IDCodeRegisterFlags): the set idcode flags
Returns:
``True`` if the given ``flags`` correctly identify the the debug
interface, otherwise ``False``.
|
def unlock_kinetis_identified(identity, flags):
if flags.version_code != identity.version_code:
return False
if flags.part_no != identity.part_no:
return False
return flags.valid
| 249,973 |
Unlock for Freescale Kinetis K40 or K60 device.
Args:
jlink (JLink): an instance of a J-Link that is connected to a target.
Returns:
``True`` if the device was successfully unlocked, otherwise ``False``.
Raises:
ValueError: if the J-Link is not connected to a target.
|
def unlock_kinetis(jlink):
if not jlink.connected():
raise ValueError('No target to unlock.')
method = UNLOCK_METHODS.get(jlink.tif, None)
if method is None:
raise NotImplementedError('Unsupported target interface for unlock.')
return method(jlink)
| 249,977 |
Implements a Serial Wire Viewer (SWV).
A Serial Wire Viewer (SWV) allows us implement real-time logging of output
from a connected device over Serial Wire Output (SWO).
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
Always returns ``0``.
Raises:
JLinkException: on error
|
def serial_wire_viewer(jlink_serial, device):
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)
jlink.open(serial_no=jlink_serial)
# Use Serial Wire Debug as the target interface. Need this in order to use
# Serial Wire Output.
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
jlink.connect(device, verbose=True)
jlink.coresight_configure()
jlink.set_reset_strategy(pylink.enums.JLinkResetStrategyCortexM3.RESETPIN)
# Have to halt the CPU before getitng its speed.
jlink.reset()
jlink.halt()
cpu_speed = jlink.cpu_speed()
swo_speed = jlink.swo_supported_speeds(cpu_speed, 10)[0]
# Start logging serial wire output.
jlink.swo_start(swo_speed)
jlink.swo_flush()
# Output the information about the program.
sys.stdout.write('Serial Wire Viewer\n')
sys.stdout.write('Press Ctrl-C to Exit\n')
sys.stdout.write('Reading data from port 0:\n\n')
# Reset the core without halting so that it runs.
jlink.reset(ms=10, halt=False)
# Use the `try` loop to catch a keyboard interrupt in order to stop logging
# serial wire output.
try:
while True:
# Check for any bytes in the stream.
num_bytes = jlink.swo_num_bytes()
if num_bytes == 0:
# If no bytes exist, sleep for a bit before trying again.
time.sleep(1)
continue
data = jlink.swo_read_stimulus(0, num_bytes)
sys.stdout.write(''.join(map(chr, data)))
sys.stdout.flush()
except KeyboardInterrupt:
pass
sys.stdout.write('\n')
# Stop logging serial wire output.
jlink.swo_stop()
return 0
| 249,978 |
Decorator to specify the minimum SDK version required.
Args:
version (str): valid version string
Returns:
A decorator function.
|
def minimum_required(version):
def _minimum_required(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if list(self.version) < list(version):
raise errors.JLinkException('Version %s required.' % version)
return func(self, *args, **kwargs)
return wrapper
return _minimum_required
| 249,979 |
Decorator to specify that the J-Link DLL must be opened, and a
J-Link connection must be established.
Args:
func (function): function being decorated
Returns:
The wrapper function.
|
def open_required(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not self.opened():
raise errors.JLinkException('J-Link DLL is not open.')
elif not self.connected():
raise errors.JLinkException('J-Link connection has been lost.')
return func(self, *args, **kwargs)
return wrapper
| 249,980 |
Decorator to specify that a target connection is required in order
for the given method to be used.
Args:
func (function): function being decorated
Returns:
The wrapper function.
|
def connection_required(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not self.target_connected():
raise errors.JLinkException('Target is not connected.')
return func(self, *args, **kwargs)
return wrapper
| 249,981 |
Decorator to specify that a particular interface type is required
for the given method to be used.
Args:
interface (int): attribute of ``JLinkInterfaces``
Returns:
A decorator function.
|
def interface_required(interface):
def _interface_required(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self.tif != interface:
raise errors.JLinkException('Unsupported for current interface.')
return func(self, *args, **kwargs)
return wrapper
return _interface_required
| 249,982 |
Destructor for the ``JLink`` instance. Closes the J-Link connection
if one exists.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
|
def __del__(self):
if self._initialized:
if self.connected():
if self.swo_enabled():
self.swo_stop()
if self.opened():
self.close()
| 249,984 |
Setter for the log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
|
def log_handler(self, handler):
if not self.opened():
handler = handler or util.noop
self._log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_EnableLog(self._log_handler)
| 249,985 |
Setter for the detailed log handler function.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
|
def detailed_log_handler(self, handler):
if not self.opened():
handler = handler or util.noop
self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_EnableLogCom(self._detailed_log_handler)
| 249,986 |
Setter for the error handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on error messages
Returns:
``None``
|
def error_handler(self, handler):
if not self.opened():
handler = handler or util.noop
self._error_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_SetErrorOutHandler(self._error_handler)
| 249,987 |
Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warning messages
Returns:
``None``
|
def warning_handler(self, handler):
if not self.opened():
handler = handler or util.noop
self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler)
| 249,988 |
Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.
Raises:
JLinkException: if fails to enumerate devices.
|
def connected_emulators(self, host=enums.JLinkHost.USB):
res = self._dll.JLINKARM_EMU_GetList(host, 0, 0)
if res < 0:
raise errors.JLinkException(res)
num_devices = res
info = (structs.JLinkConnectInfo * num_devices)()
num_found = self._dll.JLINKARM_EMU_GetList(host, info, num_devices)
if num_found < 0:
raise errors.JLinkException(num_found)
return list(info)[:num_found]
| 249,989 |
Gets the device at the given ``index``.
Args:
self (JLink): the ``JLink`` instance
index (int): the index of the device whose information to get
Returns:
A ``JLinkDeviceInfo`` describing the requested device.
Raises:
ValueError: if index is less than 0 or >= supported device count.
|
def supported_device(self, index=0):
if not util.is_natural(index) or index >= self.num_supported_devices():
raise ValueError('Invalid index.')
info = structs.JLinkDeviceInfo()
result = self._dll.JLINKARM_DEVICE_GetInfo(index, ctypes.byref(info))
return info
| 249,990 |
Connects to the J-Link emulator (over SEGGER tunnel).
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
port (int): optional port number (default to 19020).
Returns:
``None``
|
def open_tunnel(self, serial_no, port=19020):
return self.open(ip_addr='tunnel:' + str(serial_no) + ':' + str(port))
| 249,992 |
Closes the open J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
Raises:
JLinkException: if there is no connected JLink.
|
def close(self):
self._dll.JLINKARM_Close()
if self._lock is not None:
del self._lock
self._lock = None
return None
| 249,993 |
Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
|
def sync_firmware(self):
serial_no = self.serial_number
if self.firmware_newer():
# The J-Link's firmware is newer than the one compatible with the
# DLL (though there are promises of backwards compatibility), so
# perform a downgrade.
try:
# This may throw an exception on older versions of the J-Link
# software due to the software timing out after a firmware
# upgrade.
self.invalidate_firmware()
self.update_firmware()
except errors.JLinkException as e:
pass
res = self.open(serial_no=serial_no)
if self.firmware_newer():
raise errors.JLinkException('Failed to sync firmware version.')
return res
elif self.firmware_outdated():
# The J-Link's firmware is older than the one compatible with the
# DLL, so perform a firmware upgrade.
try:
# This may throw an exception on older versions of the J-Link
# software due to the software timing out after a firmware
# upgrade.
self.update_firmware()
except errors.JLinkException as e:
pass
if self.firmware_outdated():
raise errors.JLinkException('Failed to sync firmware version.')
return self.open(serial_no=serial_no)
return None
| 249,994 |
Connects the J-Link to its target.
Args:
self (JLink): the ``JLink`` instance
chip_name (str): target chip name
speed (int): connection speed, one of ``{5-12000, 'auto', 'adaptive'}``
verbose (bool): boolean indicating if connection should be verbose in logging
Returns:
``None``
Raises:
JLinkException: if connection fails to establish.
TypeError: if given speed is invalid
|
def connect(self, chip_name, speed='auto', verbose=False):
if verbose:
self.exec_command('EnableRemarks = 1')
# This is weird but is currently the only way to specify what the
# target is to the J-Link.
self.exec_command('Device = %s' % chip_name)
# Need to select target interface speed here, so the J-Link knows what
# speed to use to establish target communication.
if speed == 'auto':
self.set_speed(auto=True)
elif speed == 'adaptive':
self.set_speed(adaptive=True)
else:
self.set_speed(speed)
result = self._dll.JLINKARM_Connect()
if result < 0:
raise errors.JLinkException(result)
try:
# Issue a no-op command after connect. This has to be in a try-catch.
self.halted()
except errors.JLinkException:
pass
# Determine which device we are. This is essential for using methods
# like 'unlock' or 'lock'.
for index in range(self.num_supported_devices()):
device = self.supported_device(index)
if device.name.lower() == chip_name.lower():
self._device = device
break
else:
raise errors.JLinkException('Unsupported device was connected to.')
return None
| 249,998 |
Returns a string specifying the date and time at which the DLL was
translated.
Args:
self (JLink): the ``JLink`` instance
Returns:
Datetime string.
|
def compile_date(self):
result = self._dll.JLINKARM_GetCompileDateTime()
return ctypes.cast(result, ctypes.c_char_p).value.decode()
| 249,999 |
Returns the device's version.
The device's version is returned as a string of the format: M.mr where
``M`` is major number, ``m`` is minor number, and ``r`` is revision
character.
Args:
self (JLink): the ``JLink`` instance
Returns:
Device version string.
|
def version(self):
version = int(self._dll.JLINKARM_GetDLLVersion())
major = version / 10000
minor = (version / 100) % 100
rev = version % 100
rev = '' if rev == 0 else chr(rev + ord('a') - 1)
return '%d.%02d%s' % (major, minor, rev)
| 250,000 |
Returns the DLL's compatible J-Link firmware version.
Args:
self (JLink): the ``JLink`` instance
Returns:
The firmware version of the J-Link that the DLL is compatible
with.
Raises:
JLinkException: on error.
|
def compatible_firmware_version(self):
identifier = self.firmware_version.split('compiled')[0]
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
res = self._dll.JLINKARM_GetEmbeddedFWString(identifier.encode(), buf, buf_size)
if res < 0:
raise errors.JLinkException(res)
return ctypes.string_at(buf).decode()
| 250,001 |
Returns whether the J-Link's firmware version is older than the one
that the DLL is compatible with.
Note:
This is not the same as calling ``not jlink.firmware_newer()``.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if the J-Link's firmware is older than the one supported by
the DLL, otherwise ``False``.
|
def firmware_outdated(self):
datefmt = ' %b %d %Y %H:%M:%S'
compat_date = self.compatible_firmware_version.split('compiled')[1]
compat_date = datetime.datetime.strptime(compat_date, datefmt)
fw_date = self.firmware_version.split('compiled')[1]
fw_date = datetime.datetime.strptime(fw_date, datefmt)
return (compat_date > fw_date)
| 250,002 |
Retrieves and returns the hardware status.
Args:
self (JLink): the ``JLink`` instance
Returns:
A ``JLinkHardwareStatus`` describing the J-Link hardware.
|
def hardware_status(self):
stat = structs.JLinkHardwareStatus()
res = self._dll.JLINKARM_GetHWStatus(ctypes.byref(stat))
if res == 1:
raise errors.JLinkException('Error in reading hardware status.')
return stat
| 250,004 |
Returns the hardware version of the connected J-Link as a
major.minor string.
Args:
self (JLink): the ``JLink`` instance
Returns:
Hardware version string.
|
def hardware_version(self):
version = self._dll.JLINKARM_GetHardwareVersion()
major = version / 10000 % 100
minor = version / 100 % 100
return '%d.%02d' % (major, minor)
| 250,005 |
Returns a firmware identification string of the connected J-Link.
It consists of the following:
- Product Name (e.g. J-Link)
- The string: compiled
- Compile data and time.
- Optional additional information.
Args:
self (JLink): the ``JLink`` instance
Returns:
Firmware identification string.
|
def firmware_version(self):
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_GetFirmwareString(buf, self.MAX_BUF_SIZE)
return ctypes.string_at(buf).decode()
| 250,006 |
Gets the capabilities of the connected emulator as a list.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of 32 integers which define the extended capabilities based on
their value and index within the list.
|
def extended_capabilities(self):
buf = (ctypes.c_uint8 * 32)()
self._dll.JLINKARM_GetEmuCapsEx(buf, 32)
return list(buf)
| 250,007 |
Returns a list of the J-Link embedded features.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of strings, each a feature. Example:
``[ 'RDI', 'FlashBP', 'FlashDL', 'JFlash', 'GDB' ]``
|
def features(self):
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_GetFeatureString(buf)
result = ctypes.string_at(buf).decode().strip()
if len(result) == 0:
return list()
return result.split(', ')
| 250,008 |
Returns the product name of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
Product name.
|
def product_name(self):
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZE)
return ctypes.string_at(buf).decode()
| 250,009 |
Retrieves and returns the OEM string of the connected J-Link.
Args:
self (JLink): the ``JLink`` instance
Returns:
The string of the OEM. If this is an original SEGGER product, then
``None`` is returned instead.
Raises:
JLinkException: on hardware error.
|
def oem(self):
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
res = self._dll.JLINKARM_GetOEMString(ctypes.byref(buf))
if res != 0:
raise errors.JLinkException('Failed to grab OEM string.')
oem = ctypes.string_at(buf).decode()
if len(oem) == 0:
# In the case that the product is an original SEGGER product, then
# the OEM string is the empty string, so there is no OEM.
return None
return oem
| 250,010 |
Retrieves information about supported target interface speeds.
Args:
self (JLink): the ``JLink`` instance
Returns:
The ``JLinkSpeedInfo`` instance describing the supported target
interface speeds.
|
def speed_info(self):
speed_info = structs.JLinkSpeedInfo()
self._dll.JLINKARM_GetSpeedInfo(ctypes.byref(speed_info))
return speed_info
| 250,012 |
Returns a string of the built-in licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the built-in licenses the J-Link has.
|
def licenses(self):
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
res = self._dll.JLINK_GetAvailableLicense(buf, buf_size)
if res < 0:
raise errors.JLinkException(res)
return ctypes.string_at(buf).decode()
| 250,013 |
Returns a string of the installed licenses the J-Link has.
Args:
self (JLink): the ``JLink`` instance
Returns:
String of the contents of the custom licenses the J-Link has.
|
def custom_licenses(self):
buf = (ctypes.c_char * self.MAX_BUF_SIZE)()
result = self._dll.JLINK_EMU_GetLicenses(buf, self.MAX_BUF_SIZE)
if result < 0:
raise errors.JLinkException(result)
return ctypes.string_at(buf).decode()
| 250,014 |
Adds the given ``contents`` as a new custom license to the J-Link.
Args:
self (JLink): the ``JLink`` instance
contents: the string contents of the new custom license
Returns:
``True`` if license was added, ``False`` if license already existed.
Raises:
JLinkException: if the write fails.
Note:
J-Link V9 and J-Link ULTRA/PRO V4 have 336 Bytes of memory for
licenses, while older versions of 80 bytes.
|
def add_license(self, contents):
buf_size = len(contents)
buf = (ctypes.c_char * (buf_size + 1))(*contents.encode())
res = self._dll.JLINK_EMU_AddLicense(buf)
if res == -1:
raise errors.JLinkException('Unspecified error.')
elif res == -2:
raise errors.JLinkException('Failed to read/write license area.')
elif res == -3:
raise errors.JLinkException('J-Link out of space.')
return (res == 0)
| 250,015 |
Returns a bitmask of the supported target interfaces.
Args:
self (JLink): the ``JLink`` instance
Returns:
Bitfield specifying which target interfaces are supported.
|
def supported_tifs(self):
buf = ctypes.c_uint32()
self._dll.JLINKARM_TIF_GetAvailable(ctypes.byref(buf))
return buf.value
| 250,016 |
Selects the specified target interface.
Note that a restart must be triggered for this to take effect.
Args:
self (Jlink): the ``JLink`` instance
interface (int): integer identifier of the interface
Returns:
``True`` if target was updated, otherwise ``False``.
Raises:
JLinkException: if the given interface is invalid or unsupported.
|
def set_tif(self, interface):
if not ((1 << interface) & self.supported_tifs()):
raise errors.JLinkException('Unsupported target interface: %s' % interface)
# The return code here is actually *NOT* the previous set interface, it
# is ``0`` on success, otherwise ``1``.
res = self._dll.JLINKARM_TIF_Select(interface)
if res != 0:
return False
self._tif = interface
return True
| 250,017 |
Returns the properties of the user-controllable GPIOs.
Provided the device supports user-controllable GPIOs, they will be
returned by this method.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of ``JLinkGPIODescriptor`` instances totalling the number of
requested properties.
Raises:
JLinkException: on error.
|
def gpio_properties(self):
res = self._dll.JLINK_EMU_GPIO_GetProps(0, 0)
if res < 0:
raise errors.JLinkException(res)
num_props = res
buf = (structs.JLinkGPIODescriptor * num_props)()
res = self._dll.JLINK_EMU_GPIO_GetProps(ctypes.byref(buf), num_props)
if res < 0:
raise errors.JLinkException(res)
return list(buf)
| 250,018 |
Returns a list of states for the given pins.
Defaults to the first four pins if an argument is not given.
Args:
self (JLink): the ``JLink`` instance
pins (list): indices of the GPIO pins whose states are requested
Returns:
A list of states.
Raises:
JLinkException: on error.
|
def gpio_get(self, pins=None):
if pins is None:
pins = range(4)
size = len(pins)
indices = (ctypes.c_uint8 * size)(*pins)
statuses = (ctypes.c_uint8 * size)()
result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices),
ctypes.byref(statuses),
size)
if result < 0:
raise errors.JLinkException(result)
return list(statuses)
| 250,019 |
Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set
Returns:
A list of updated states.
Raises:
JLinkException: on error.
ValueError: if ``len(pins) != len(states)``
|
def gpio_set(self, pins, states):
if len(pins) != len(states):
raise ValueError('Length mismatch between pins and states.')
size = len(pins)
indices = (ctypes.c_uint8 * size)(*pins)
states = (ctypes.c_uint8 * size)(*states)
result_states = (ctypes.c_uint8 * size)()
result = self._dll.JLINK_EMU_GPIO_SetState(ctypes.byref(indices),
ctypes.byref(states),
ctypes.byref(result_states),
size)
if result < 0:
raise errors.JLinkException(result)
return list(result_states)
| 250,020 |
Erases the flash contents of the device.
This erases the flash memory of the target device. If this method
fails, the device may be left in an inoperable state.
Args:
self (JLink): the ``JLink`` instance
Returns:
Number of bytes erased.
|
def erase(self):
try:
# This has to be in a try-catch, as the device may not be in a
# state where it can halt, but we still want to try and erase.
if not self.halted():
self.halt()
except errors.JLinkException:
# Can't halt, so just continue to erasing.
pass
res = self._dll.JLINK_EraseChip()
if res < 0:
raise errors.JLinkEraseException(res)
return res
| 250,022 |
Resets the target.
This method resets the target, and by default toggles the RESET and
TRST pins.
Args:
self (JLink): the ``JLink`` instance
ms (int): Amount of milliseconds to delay after reset (default: 0)
halt (bool): if the CPU should halt after reset (default: True)
Returns:
Number of bytes read.
|
def reset(self, ms=0, halt=True):
self._dll.JLINKARM_SetResetDelay(ms)
res = self._dll.JLINKARM_Reset()
if res < 0:
raise errors.JLinkException(res)
elif not halt:
self._dll.JLINKARM_Go()
return res
| 250,025 |
Halts the CPU Core.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if halted, ``False`` otherwise.
|
def halt(self):
res = int(self._dll.JLINKARM_Halt())
if res == 0:
time.sleep(1)
return True
return False
| 250,027 |
Returns whether the CPU core was halted.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if the CPU core is halted, otherwise ``False``.
Raises:
JLinkException: on device errors.
|
def halted(self):
result = int(self._dll.JLINKARM_IsHalted())
if result < 0:
raise errors.JLinkException(result)
return (result > 0)
| 250,028 |
Returns the name of the target ARM core.
Args:
self (JLink): the ``JLink`` instance
Returns:
The target core's name.
|
def core_name(self):
buf_size = self.MAX_BUF_SIZE
buf = (ctypes.c_char * buf_size)()
self._dll.JLINKARM_Core2CoreName(self.core_cpu(), buf, buf_size)
return ctypes.string_at(buf).decode()
| 250,029 |
Retrieves and returns the number of bits in the scan chain.
Args:
self (JLink): the ``JLink`` instance
scan_chain (int): scan chain to be measured
Returns:
Number of bits in the specified scan chain.
Raises:
JLinkException: on error.
|
def scan_chain_len(self, scan_chain):
res = self._dll.JLINKARM_MeasureSCLen(scan_chain)
if res < 0:
raise errors.JLinkException(res)
return res
| 250,030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.