repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
selectel/pyte | pyte/screens.py | HistoryScreen.before_event | def before_event(self, event):
"""Ensure a screen is at the bottom of the history buffer.
:param str event: event name, for example ``"linefeed"``.
"""
if event not in ["prev_page", "next_page"]:
while self.history.position < self.history.size:
self.next_page() | python | def before_event(self, event):
"""Ensure a screen is at the bottom of the history buffer.
:param str event: event name, for example ``"linefeed"``.
"""
if event not in ["prev_page", "next_page"]:
while self.history.position < self.history.size:
self.next_page() | [
"def",
"before_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
"not",
"in",
"[",
"\"prev_page\"",
",",
"\"next_page\"",
"]",
":",
"while",
"self",
".",
"history",
".",
"position",
"<",
"self",
".",
"history",
".",
"size",
":",
"self",
".",
... | Ensure a screen is at the bottom of the history buffer.
:param str event: event name, for example ``"linefeed"``. | [
"Ensure",
"a",
"screen",
"is",
"at",
"the",
"bottom",
"of",
"the",
"history",
"buffer",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1161-L1168 | train | 208,200 |
selectel/pyte | pyte/screens.py | HistoryScreen.erase_in_display | def erase_in_display(self, how=0, *args, **kwargs):
"""Overloaded to reset history state."""
super(HistoryScreen, self).erase_in_display(how, *args, **kwargs)
if how == 3:
self._reset_history() | python | def erase_in_display(self, how=0, *args, **kwargs):
"""Overloaded to reset history state."""
super(HistoryScreen, self).erase_in_display(how, *args, **kwargs)
if how == 3:
self._reset_history() | [
"def",
"erase_in_display",
"(",
"self",
",",
"how",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"HistoryScreen",
",",
"self",
")",
".",
"erase_in_display",
"(",
"how",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",... | Overloaded to reset history state. | [
"Overloaded",
"to",
"reset",
"history",
"state",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1204-L1209 | train | 208,201 |
selectel/pyte | pyte/screens.py | HistoryScreen.index | def index(self):
"""Overloaded to update top history with the removed lines."""
top, bottom = self.margins or Margins(0, self.lines - 1)
if self.cursor.y == bottom:
self.history.top.append(self.buffer[top])
super(HistoryScreen, self).index() | python | def index(self):
"""Overloaded to update top history with the removed lines."""
top, bottom = self.margins or Margins(0, self.lines - 1)
if self.cursor.y == bottom:
self.history.top.append(self.buffer[top])
super(HistoryScreen, self).index() | [
"def",
"index",
"(",
"self",
")",
":",
"top",
",",
"bottom",
"=",
"self",
".",
"margins",
"or",
"Margins",
"(",
"0",
",",
"self",
".",
"lines",
"-",
"1",
")",
"if",
"self",
".",
"cursor",
".",
"y",
"==",
"bottom",
":",
"self",
".",
"history",
"... | Overloaded to update top history with the removed lines. | [
"Overloaded",
"to",
"update",
"top",
"history",
"with",
"the",
"removed",
"lines",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1211-L1218 | train | 208,202 |
selectel/pyte | pyte/screens.py | HistoryScreen.prev_page | def prev_page(self):
"""Move the screen page up through the history buffer. Page
size is defined by ``history.ratio``, so for instance
``ratio = .5`` means that half the screen is restored from
history on page switch.
"""
if self.history.position > self.lines and self.history.top:
mid = min(len(self.history.top),
int(math.ceil(self.lines * self.history.ratio)))
self.history.bottom.extendleft(
self.buffer[y]
for y in range(self.lines - 1, self.lines - mid - 1, -1))
self.history = self.history \
._replace(position=self.history.position - mid)
for y in range(self.lines - 1, mid - 1, -1):
self.buffer[y] = self.buffer[y - mid]
for y in range(mid - 1, -1, -1):
self.buffer[y] = self.history.top.pop()
self.dirty = set(range(self.lines)) | python | def prev_page(self):
"""Move the screen page up through the history buffer. Page
size is defined by ``history.ratio``, so for instance
``ratio = .5`` means that half the screen is restored from
history on page switch.
"""
if self.history.position > self.lines and self.history.top:
mid = min(len(self.history.top),
int(math.ceil(self.lines * self.history.ratio)))
self.history.bottom.extendleft(
self.buffer[y]
for y in range(self.lines - 1, self.lines - mid - 1, -1))
self.history = self.history \
._replace(position=self.history.position - mid)
for y in range(self.lines - 1, mid - 1, -1):
self.buffer[y] = self.buffer[y - mid]
for y in range(mid - 1, -1, -1):
self.buffer[y] = self.history.top.pop()
self.dirty = set(range(self.lines)) | [
"def",
"prev_page",
"(",
"self",
")",
":",
"if",
"self",
".",
"history",
".",
"position",
">",
"self",
".",
"lines",
"and",
"self",
".",
"history",
".",
"top",
":",
"mid",
"=",
"min",
"(",
"len",
"(",
"self",
".",
"history",
".",
"top",
")",
",",... | Move the screen page up through the history buffer. Page
size is defined by ``history.ratio``, so for instance
``ratio = .5`` means that half the screen is restored from
history on page switch. | [
"Move",
"the",
"screen",
"page",
"up",
"through",
"the",
"history",
"buffer",
".",
"Page",
"size",
"is",
"defined",
"by",
"history",
".",
"ratio",
"so",
"for",
"instance",
"ratio",
"=",
".",
"5",
"means",
"that",
"half",
"the",
"screen",
"is",
"restored"... | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1229-L1250 | train | 208,203 |
selectel/pyte | pyte/screens.py | HistoryScreen.next_page | def next_page(self):
"""Move the screen page down through the history buffer."""
if self.history.position < self.history.size and self.history.bottom:
mid = min(len(self.history.bottom),
int(math.ceil(self.lines * self.history.ratio)))
self.history.top.extend(self.buffer[y] for y in range(mid))
self.history = self.history \
._replace(position=self.history.position + mid)
for y in range(self.lines - mid):
self.buffer[y] = self.buffer[y + mid]
for y in range(self.lines - mid, self.lines):
self.buffer[y] = self.history.bottom.popleft()
self.dirty = set(range(self.lines)) | python | def next_page(self):
"""Move the screen page down through the history buffer."""
if self.history.position < self.history.size and self.history.bottom:
mid = min(len(self.history.bottom),
int(math.ceil(self.lines * self.history.ratio)))
self.history.top.extend(self.buffer[y] for y in range(mid))
self.history = self.history \
._replace(position=self.history.position + mid)
for y in range(self.lines - mid):
self.buffer[y] = self.buffer[y + mid]
for y in range(self.lines - mid, self.lines):
self.buffer[y] = self.history.bottom.popleft()
self.dirty = set(range(self.lines)) | [
"def",
"next_page",
"(",
"self",
")",
":",
"if",
"self",
".",
"history",
".",
"position",
"<",
"self",
".",
"history",
".",
"size",
"and",
"self",
".",
"history",
".",
"bottom",
":",
"mid",
"=",
"min",
"(",
"len",
"(",
"self",
".",
"history",
".",
... | Move the screen page down through the history buffer. | [
"Move",
"the",
"screen",
"page",
"down",
"through",
"the",
"history",
"buffer",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/screens.py#L1252-L1267 | train | 208,204 |
selectel/pyte | pyte/streams.py | Stream.attach | def attach(self, screen):
"""Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to.
"""
if self.listener is not None:
warnings.warn("As of version 0.6.0 the listener queue is "
"restricted to a single element. Existing "
"listener {0} will be replaced."
.format(self.listener), DeprecationWarning)
if self.strict:
for event in self.events:
if not hasattr(screen, event):
raise TypeError("{0} is missing {1}".format(screen, event))
self.listener = screen
self._parser = None
self._initialize_parser() | python | def attach(self, screen):
"""Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to.
"""
if self.listener is not None:
warnings.warn("As of version 0.6.0 the listener queue is "
"restricted to a single element. Existing "
"listener {0} will be replaced."
.format(self.listener), DeprecationWarning)
if self.strict:
for event in self.events:
if not hasattr(screen, event):
raise TypeError("{0} is missing {1}".format(screen, event))
self.listener = screen
self._parser = None
self._initialize_parser() | [
"def",
"attach",
"(",
"self",
",",
"screen",
")",
":",
"if",
"self",
".",
"listener",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"As of version 0.6.0 the listener queue is \"",
"\"restricted to a single element. Existing \"",
"\"listener {0} will be replace... | Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to. | [
"Adds",
"a",
"given",
"screen",
"to",
"the",
"listener",
"queue",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/streams.py#L146-L164 | train | 208,205 |
selectel/pyte | pyte/streams.py | Stream.feed | def feed(self, data):
"""Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from.
"""
send = self._send_to_parser
draw = self.listener.draw
match_text = self._text_pattern.match
taking_plain_text = self._taking_plain_text
length = len(data)
offset = 0
while offset < length:
if taking_plain_text:
match = match_text(data, offset)
if match:
start, offset = match.span()
draw(data[start:offset])
else:
taking_plain_text = False
else:
taking_plain_text = send(data[offset:offset + 1])
offset += 1
self._taking_plain_text = taking_plain_text | python | def feed(self, data):
"""Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from.
"""
send = self._send_to_parser
draw = self.listener.draw
match_text = self._text_pattern.match
taking_plain_text = self._taking_plain_text
length = len(data)
offset = 0
while offset < length:
if taking_plain_text:
match = match_text(data, offset)
if match:
start, offset = match.span()
draw(data[start:offset])
else:
taking_plain_text = False
else:
taking_plain_text = send(data[offset:offset + 1])
offset += 1
self._taking_plain_text = taking_plain_text | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"send",
"=",
"self",
".",
"_send_to_parser",
"draw",
"=",
"self",
".",
"listener",
".",
"draw",
"match_text",
"=",
"self",
".",
"_text_pattern",
".",
"match",
"taking_plain_text",
"=",
"self",
".",
"_tak... | Consume some data and advances the state as necessary.
:param str data: a blob of data to feed from. | [
"Consume",
"some",
"data",
"and",
"advances",
"the",
"state",
"as",
"necessary",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/pyte/streams.py#L175-L199 | train | 208,206 |
selectel/pyte | examples/webterm.py | on_shutdown | async def on_shutdown(app):
"""Closes all WS connections on shutdown."""
global is_shutting_down
is_shutting_down = True
for task in app["websockets"]:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass | python | async def on_shutdown(app):
"""Closes all WS connections on shutdown."""
global is_shutting_down
is_shutting_down = True
for task in app["websockets"]:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass | [
"async",
"def",
"on_shutdown",
"(",
"app",
")",
":",
"global",
"is_shutting_down",
"is_shutting_down",
"=",
"True",
"for",
"task",
"in",
"app",
"[",
"\"websockets\"",
"]",
":",
"task",
".",
"cancel",
"(",
")",
"try",
":",
"await",
"task",
"except",
"asynci... | Closes all WS connections on shutdown. | [
"Closes",
"all",
"WS",
"connections",
"on",
"shutdown",
"."
] | 8adad489f86da1788a7995720c344a2fa44f244e | https://github.com/selectel/pyte/blob/8adad489f86da1788a7995720c344a2fa44f244e/examples/webterm.py#L123-L132 | train | 208,207 |
charnley/rmsd | rmsd/calculate_rmsd.py | rmsd | def rmsd(V, W):
"""
Calculate Root-mean-square deviation from two sets of vectors V and W.
Parameters
----------
V : array
(N,D) matrix, where N is points and D is dimension.
W : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rmsd : float
Root-mean-square deviation between the two vectors
"""
D = len(V[0])
N = len(V)
result = 0.0
for v, w in zip(V, W):
result += sum([(v[i] - w[i])**2.0 for i in range(D)])
return np.sqrt(result/N) | python | def rmsd(V, W):
"""
Calculate Root-mean-square deviation from two sets of vectors V and W.
Parameters
----------
V : array
(N,D) matrix, where N is points and D is dimension.
W : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rmsd : float
Root-mean-square deviation between the two vectors
"""
D = len(V[0])
N = len(V)
result = 0.0
for v, w in zip(V, W):
result += sum([(v[i] - w[i])**2.0 for i in range(D)])
return np.sqrt(result/N) | [
"def",
"rmsd",
"(",
"V",
",",
"W",
")",
":",
"D",
"=",
"len",
"(",
"V",
"[",
"0",
"]",
")",
"N",
"=",
"len",
"(",
"V",
")",
"result",
"=",
"0.0",
"for",
"v",
",",
"w",
"in",
"zip",
"(",
"V",
",",
"W",
")",
":",
"result",
"+=",
"sum",
... | Calculate Root-mean-square deviation from two sets of vectors V and W.
Parameters
----------
V : array
(N,D) matrix, where N is points and D is dimension.
W : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rmsd : float
Root-mean-square deviation between the two vectors | [
"Calculate",
"Root",
"-",
"mean",
"-",
"square",
"deviation",
"from",
"two",
"sets",
"of",
"vectors",
"V",
"and",
"W",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L40-L61 | train | 208,208 |
charnley/rmsd | rmsd/calculate_rmsd.py | kabsch_rmsd | def kabsch_rmsd(P, Q, translate=False):
"""
Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
translate : bool
Use centroids to translate vector P and Q unto each other.
Returns
-------
rmsd : float
root-mean squared deviation
"""
if translate:
Q = Q - centroid(Q)
P = P - centroid(P)
P = kabsch_rotate(P, Q)
return rmsd(P, Q) | python | def kabsch_rmsd(P, Q, translate=False):
"""
Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
translate : bool
Use centroids to translate vector P and Q unto each other.
Returns
-------
rmsd : float
root-mean squared deviation
"""
if translate:
Q = Q - centroid(Q)
P = P - centroid(P)
P = kabsch_rotate(P, Q)
return rmsd(P, Q) | [
"def",
"kabsch_rmsd",
"(",
"P",
",",
"Q",
",",
"translate",
"=",
"False",
")",
":",
"if",
"translate",
":",
"Q",
"=",
"Q",
"-",
"centroid",
"(",
"Q",
")",
"P",
"=",
"P",
"-",
"centroid",
"(",
"P",
")",
"P",
"=",
"kabsch_rotate",
"(",
"P",
",",
... | Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
translate : bool
Use centroids to translate vector P and Q unto each other.
Returns
-------
rmsd : float
root-mean squared deviation | [
"Rotate",
"matrix",
"P",
"unto",
"Q",
"using",
"Kabsch",
"algorithm",
"and",
"calculate",
"the",
"RMSD",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L64-L87 | train | 208,209 |
charnley/rmsd | rmsd/calculate_rmsd.py | kabsch_rotate | def kabsch_rotate(P, Q):
"""
Rotate matrix P unto matrix Q using Kabsch algorithm.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
P : array
(N,D) matrix, where N is points and D is dimension,
rotated
"""
U = kabsch(P, Q)
# Rotate P
P = np.dot(P, U)
return P | python | def kabsch_rotate(P, Q):
"""
Rotate matrix P unto matrix Q using Kabsch algorithm.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
P : array
(N,D) matrix, where N is points and D is dimension,
rotated
"""
U = kabsch(P, Q)
# Rotate P
P = np.dot(P, U)
return P | [
"def",
"kabsch_rotate",
"(",
"P",
",",
"Q",
")",
":",
"U",
"=",
"kabsch",
"(",
"P",
",",
"Q",
")",
"# Rotate P",
"P",
"=",
"np",
".",
"dot",
"(",
"P",
",",
"U",
")",
"return",
"P"
] | Rotate matrix P unto matrix Q using Kabsch algorithm.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
P : array
(N,D) matrix, where N is points and D is dimension,
rotated | [
"Rotate",
"matrix",
"P",
"unto",
"matrix",
"Q",
"using",
"Kabsch",
"algorithm",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L90-L112 | train | 208,210 |
charnley/rmsd | rmsd/calculate_rmsd.py | kabsch | def kabsch(P, Q):
"""
Using the Kabsch algorithm with two sets of paired point P and Q, centered
around the centroid. Each vector set is represented as an NxD
matrix, where D is the the dimension of the space.
The algorithm works in three steps:
- a centroid translation of P and Q (assumed done before this function
call)
- the computation of a covariance matrix C
- computation of the optimal rotation matrix U
For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
U : matrix
Rotation matrix (D,D)
"""
# Computation of the covariance matrix
C = np.dot(np.transpose(P), Q)
# Computation of the optimal rotation matrix
# This can be done using singular value decomposition (SVD)
# Getting the sign of the det(V)*(W) to decide
# whether we need to correct our rotation matrix to ensure a
# right-handed coordinate system.
# And finally calculating the optimal rotation matrix U
# see http://en.wikipedia.org/wiki/Kabsch_algorithm
V, S, W = np.linalg.svd(C)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:, -1] = -V[:, -1]
# Create Rotation matrix U
U = np.dot(V, W)
return U | python | def kabsch(P, Q):
"""
Using the Kabsch algorithm with two sets of paired point P and Q, centered
around the centroid. Each vector set is represented as an NxD
matrix, where D is the the dimension of the space.
The algorithm works in three steps:
- a centroid translation of P and Q (assumed done before this function
call)
- the computation of a covariance matrix C
- computation of the optimal rotation matrix U
For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
U : matrix
Rotation matrix (D,D)
"""
# Computation of the covariance matrix
C = np.dot(np.transpose(P), Q)
# Computation of the optimal rotation matrix
# This can be done using singular value decomposition (SVD)
# Getting the sign of the det(V)*(W) to decide
# whether we need to correct our rotation matrix to ensure a
# right-handed coordinate system.
# And finally calculating the optimal rotation matrix U
# see http://en.wikipedia.org/wiki/Kabsch_algorithm
V, S, W = np.linalg.svd(C)
d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
if d:
S[-1] = -S[-1]
V[:, -1] = -V[:, -1]
# Create Rotation matrix U
U = np.dot(V, W)
return U | [
"def",
"kabsch",
"(",
"P",
",",
"Q",
")",
":",
"# Computation of the covariance matrix",
"C",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"transpose",
"(",
"P",
")",
",",
"Q",
")",
"# Computation of the optimal rotation matrix",
"# This can be done using singular value d... | Using the Kabsch algorithm with two sets of paired point P and Q, centered
around the centroid. Each vector set is represented as an NxD
matrix, where D is the the dimension of the space.
The algorithm works in three steps:
- a centroid translation of P and Q (assumed done before this function
call)
- the computation of a covariance matrix C
- computation of the optimal rotation matrix U
For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
U : matrix
Rotation matrix (D,D) | [
"Using",
"the",
"Kabsch",
"algorithm",
"with",
"two",
"sets",
"of",
"paired",
"point",
"P",
"and",
"Q",
"centered",
"around",
"the",
"centroid",
".",
"Each",
"vector",
"set",
"is",
"represented",
"as",
"an",
"NxD",
"matrix",
"where",
"D",
"is",
"the",
"t... | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L115-L162 | train | 208,211 |
charnley/rmsd | rmsd/calculate_rmsd.py | quaternion_rotate | def quaternion_rotate(X, Y):
"""
Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D)
"""
N = X.shape[0]
W = np.asarray([makeW(*Y[k]) for k in range(N)])
Q = np.asarray([makeQ(*X[k]) for k in range(N)])
Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)])
W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)])
A = np.sum(Qt_dot_W, axis=0)
eigen = np.linalg.eigh(A)
r = eigen[1][:, eigen[0].argmax()]
rot = quaternion_transform(r)
return rot | python | def quaternion_rotate(X, Y):
"""
Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D)
"""
N = X.shape[0]
W = np.asarray([makeW(*Y[k]) for k in range(N)])
Q = np.asarray([makeQ(*X[k]) for k in range(N)])
Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)])
W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)])
A = np.sum(Qt_dot_W, axis=0)
eigen = np.linalg.eigh(A)
r = eigen[1][:, eigen[0].argmax()]
rot = quaternion_transform(r)
return rot | [
"def",
"quaternion_rotate",
"(",
"X",
",",
"Y",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"W",
"=",
"np",
".",
"asarray",
"(",
"[",
"makeW",
"(",
"*",
"Y",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"range",
"(",
"N",
")",
"]",
")"... | Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D) | [
"Calculate",
"the",
"rotation"
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L222-L247 | train | 208,212 |
charnley/rmsd | rmsd/calculate_rmsd.py | reorder_distance | def reorder_distance(p_atoms, q_atoms, p_coord, q_coord):
"""
Re-orders the input atom list and xyz coordinates by atom type and then by
distance of each atom from the centroid.
Parameters
----------
atoms : array
(N,1) matrix, where N is points holding the atoms' names
coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
atoms_reordered : array
(N,1) matrix, where N is points holding the ordered atoms' names
coords_reordered : array
(N,D) matrix, where N is points and D is dimension (rows re-ordered)
"""
# Find unique atoms
unique_atoms = np.unique(p_atoms)
# generate full view from q shape to fill in atom view on the fly
view_reorder = np.zeros(q_atoms.shape, dtype=int)
for atom in unique_atoms:
p_atom_idx, = np.where(p_atoms == atom)
q_atom_idx, = np.where(q_atoms == atom)
A_coord = p_coord[p_atom_idx]
B_coord = q_coord[q_atom_idx]
# Calculate distance from each atom to centroid
A_norms = np.linalg.norm(A_coord, axis=1)
B_norms = np.linalg.norm(B_coord, axis=1)
reorder_indices_A = np.argsort(A_norms)
reorder_indices_B = np.argsort(B_norms)
# Project the order of P onto Q
translator = np.argsort(reorder_indices_A)
view = reorder_indices_B[translator]
view_reorder[p_atom_idx] = q_atom_idx[view]
return view_reorder | python | def reorder_distance(p_atoms, q_atoms, p_coord, q_coord):
"""
Re-orders the input atom list and xyz coordinates by atom type and then by
distance of each atom from the centroid.
Parameters
----------
atoms : array
(N,1) matrix, where N is points holding the atoms' names
coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
atoms_reordered : array
(N,1) matrix, where N is points holding the ordered atoms' names
coords_reordered : array
(N,D) matrix, where N is points and D is dimension (rows re-ordered)
"""
# Find unique atoms
unique_atoms = np.unique(p_atoms)
# generate full view from q shape to fill in atom view on the fly
view_reorder = np.zeros(q_atoms.shape, dtype=int)
for atom in unique_atoms:
p_atom_idx, = np.where(p_atoms == atom)
q_atom_idx, = np.where(q_atoms == atom)
A_coord = p_coord[p_atom_idx]
B_coord = q_coord[q_atom_idx]
# Calculate distance from each atom to centroid
A_norms = np.linalg.norm(A_coord, axis=1)
B_norms = np.linalg.norm(B_coord, axis=1)
reorder_indices_A = np.argsort(A_norms)
reorder_indices_B = np.argsort(B_norms)
# Project the order of P onto Q
translator = np.argsort(reorder_indices_A)
view = reorder_indices_B[translator]
view_reorder[p_atom_idx] = q_atom_idx[view]
return view_reorder | [
"def",
"reorder_distance",
"(",
"p_atoms",
",",
"q_atoms",
",",
"p_coord",
",",
"q_coord",
")",
":",
"# Find unique atoms",
"unique_atoms",
"=",
"np",
".",
"unique",
"(",
"p_atoms",
")",
"# generate full view from q shape to fill in atom view on the fly",
"view_reorder",
... | Re-orders the input atom list and xyz coordinates by atom type and then by
distance of each atom from the centroid.
Parameters
----------
atoms : array
(N,1) matrix, where N is points holding the atoms' names
coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
atoms_reordered : array
(N,1) matrix, where N is points holding the ordered atoms' names
coords_reordered : array
(N,D) matrix, where N is points and D is dimension (rows re-ordered) | [
"Re",
"-",
"orders",
"the",
"input",
"atom",
"list",
"and",
"xyz",
"coordinates",
"by",
"atom",
"type",
"and",
"then",
"by",
"distance",
"of",
"each",
"atom",
"from",
"the",
"centroid",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L273-L319 | train | 208,213 |
charnley/rmsd | rmsd/calculate_rmsd.py | hungarian | def hungarian(A, B):
"""
Hungarian reordering.
Assume A and B are coordinates for atoms of SAME type only
"""
# should be kabasch here i think
distances = cdist(A, B, 'euclidean')
# Perform Hungarian analysis on distance matrix between atoms of 1st
# structure and trial structure
indices_a, indices_b = linear_sum_assignment(distances)
return indices_b | python | def hungarian(A, B):
"""
Hungarian reordering.
Assume A and B are coordinates for atoms of SAME type only
"""
# should be kabasch here i think
distances = cdist(A, B, 'euclidean')
# Perform Hungarian analysis on distance matrix between atoms of 1st
# structure and trial structure
indices_a, indices_b = linear_sum_assignment(distances)
return indices_b | [
"def",
"hungarian",
"(",
"A",
",",
"B",
")",
":",
"# should be kabasch here i think",
"distances",
"=",
"cdist",
"(",
"A",
",",
"B",
",",
"'euclidean'",
")",
"# Perform Hungarian analysis on distance matrix between atoms of 1st",
"# structure and trial structure",
"indices_... | Hungarian reordering.
Assume A and B are coordinates for atoms of SAME type only | [
"Hungarian",
"reordering",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L322-L336 | train | 208,214 |
charnley/rmsd | rmsd/calculate_rmsd.py | brute_permutation | def brute_permutation(A, B):
"""
Re-orders the input atom list and xyz coordinates using the brute force
method of permuting all rows of the input coordinates
Parameters
----------
A : array
(N,D) matrix, where N is points and D is dimension
B : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
view : array
(N,1) matrix, reordered view of B projected to A
"""
rmsd_min = np.inf
view_min = None
# Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in
# brute-force method
num_atoms = A.shape[0]
initial_order = list(range(num_atoms))
for reorder_indices in generate_permutations(initial_order, num_atoms):
# Re-order the atom array and coordinate matrix
coords_ordered = B[reorder_indices]
# Calculate the RMSD between structure 1 and the Hungarian re-ordered
# structure 2
rmsd_temp = kabsch_rmsd(A, coords_ordered)
# Replaces the atoms and coordinates with the current structure if the
# RMSD is lower
if rmsd_temp < rmsd_min:
rmsd_min = rmsd_temp
view_min = copy.deepcopy(reorder_indices)
return view_min | python | def brute_permutation(A, B):
"""
Re-orders the input atom list and xyz coordinates using the brute force
method of permuting all rows of the input coordinates
Parameters
----------
A : array
(N,D) matrix, where N is points and D is dimension
B : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
view : array
(N,1) matrix, reordered view of B projected to A
"""
rmsd_min = np.inf
view_min = None
# Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in
# brute-force method
num_atoms = A.shape[0]
initial_order = list(range(num_atoms))
for reorder_indices in generate_permutations(initial_order, num_atoms):
# Re-order the atom array and coordinate matrix
coords_ordered = B[reorder_indices]
# Calculate the RMSD between structure 1 and the Hungarian re-ordered
# structure 2
rmsd_temp = kabsch_rmsd(A, coords_ordered)
# Replaces the atoms and coordinates with the current structure if the
# RMSD is lower
if rmsd_temp < rmsd_min:
rmsd_min = rmsd_temp
view_min = copy.deepcopy(reorder_indices)
return view_min | [
"def",
"brute_permutation",
"(",
"A",
",",
"B",
")",
":",
"rmsd_min",
"=",
"np",
".",
"inf",
"view_min",
"=",
"None",
"# Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in",
"# brute-force method",
"num_atoms",
"=",
"A",
".",
"shape",
"[",
"0",
... | Re-orders the input atom list and xyz coordinates using the brute force
method of permuting all rows of the input coordinates
Parameters
----------
A : array
(N,D) matrix, where N is points and D is dimension
B : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
view : array
(N,1) matrix, reordered view of B projected to A | [
"Re",
"-",
"orders",
"the",
"input",
"atom",
"list",
"and",
"xyz",
"coordinates",
"using",
"the",
"brute",
"force",
"method",
"of",
"permuting",
"all",
"rows",
"of",
"the",
"input",
"coordinates"
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L406-L448 | train | 208,215 |
charnley/rmsd | rmsd/calculate_rmsd.py | check_reflections | def check_reflections(p_atoms, q_atoms, p_coord, q_coord,
reorder_method=reorder_hungarian,
rotation_method=kabsch_rmsd,
keep_stereo=False):
"""
Minimize RMSD using reflection planes for molecule P and Q
Warning: This will affect stereo-chemistry
Parameters
----------
p_atoms : array
(N,1) matrix, where N is points holding the atoms' names
q_atoms : array
(N,1) matrix, where N is points holding the atoms' names
p_coord : array
(N,D) matrix, where N is points and D is dimension
q_coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
min_rmsd
min_swap
min_reflection
min_review
"""
min_rmsd = np.inf
min_swap = None
min_reflection = None
min_review = None
tmp_review = None
swap_mask = [1,-1,-1,1,-1,1]
reflection_mask = [1,-1,-1,-1,1,1,1,-1]
for swap, i in zip(AXIS_SWAPS, swap_mask):
for reflection, j in zip(AXIS_REFLECTIONS, reflection_mask):
if keep_stereo and i * j == -1: continue # skip enantiomers
tmp_atoms = copy.copy(q_atoms)
tmp_coord = copy.deepcopy(q_coord)
tmp_coord = tmp_coord[:, swap]
tmp_coord = np.dot(tmp_coord, np.diag(reflection))
tmp_coord -= centroid(tmp_coord)
# Reorder
if reorder_method is not None:
tmp_review = reorder_method(p_atoms, tmp_atoms, p_coord, tmp_coord)
tmp_coord = tmp_coord[tmp_review]
tmp_atoms = tmp_atoms[tmp_review]
# Rotation
if rotation_method is None:
this_rmsd = rmsd(p_coord, tmp_coord)
else:
this_rmsd = rotation_method(p_coord, tmp_coord)
if this_rmsd < min_rmsd:
min_rmsd = this_rmsd
min_swap = swap
min_reflection = reflection
min_review = tmp_review
if not (p_atoms == q_atoms[min_review]).all():
print("error: Not aligned")
quit()
return min_rmsd, min_swap, min_reflection, min_review | python | def check_reflections(p_atoms, q_atoms, p_coord, q_coord,
reorder_method=reorder_hungarian,
rotation_method=kabsch_rmsd,
keep_stereo=False):
"""
Minimize RMSD using reflection planes for molecule P and Q
Warning: This will affect stereo-chemistry
Parameters
----------
p_atoms : array
(N,1) matrix, where N is points holding the atoms' names
q_atoms : array
(N,1) matrix, where N is points holding the atoms' names
p_coord : array
(N,D) matrix, where N is points and D is dimension
q_coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
min_rmsd
min_swap
min_reflection
min_review
"""
min_rmsd = np.inf
min_swap = None
min_reflection = None
min_review = None
tmp_review = None
swap_mask = [1,-1,-1,1,-1,1]
reflection_mask = [1,-1,-1,-1,1,1,1,-1]
for swap, i in zip(AXIS_SWAPS, swap_mask):
for reflection, j in zip(AXIS_REFLECTIONS, reflection_mask):
if keep_stereo and i * j == -1: continue # skip enantiomers
tmp_atoms = copy.copy(q_atoms)
tmp_coord = copy.deepcopy(q_coord)
tmp_coord = tmp_coord[:, swap]
tmp_coord = np.dot(tmp_coord, np.diag(reflection))
tmp_coord -= centroid(tmp_coord)
# Reorder
if reorder_method is not None:
tmp_review = reorder_method(p_atoms, tmp_atoms, p_coord, tmp_coord)
tmp_coord = tmp_coord[tmp_review]
tmp_atoms = tmp_atoms[tmp_review]
# Rotation
if rotation_method is None:
this_rmsd = rmsd(p_coord, tmp_coord)
else:
this_rmsd = rotation_method(p_coord, tmp_coord)
if this_rmsd < min_rmsd:
min_rmsd = this_rmsd
min_swap = swap
min_reflection = reflection
min_review = tmp_review
if not (p_atoms == q_atoms[min_review]).all():
print("error: Not aligned")
quit()
return min_rmsd, min_swap, min_reflection, min_review | [
"def",
"check_reflections",
"(",
"p_atoms",
",",
"q_atoms",
",",
"p_coord",
",",
"q_coord",
",",
"reorder_method",
"=",
"reorder_hungarian",
",",
"rotation_method",
"=",
"kabsch_rmsd",
",",
"keep_stereo",
"=",
"False",
")",
":",
"min_rmsd",
"=",
"np",
".",
"in... | Minimize RMSD using reflection planes for molecule P and Q
Warning: This will affect stereo-chemistry
Parameters
----------
p_atoms : array
(N,1) matrix, where N is points holding the atoms' names
q_atoms : array
(N,1) matrix, where N is points holding the atoms' names
p_coord : array
(N,D) matrix, where N is points and D is dimension
q_coord : array
(N,D) matrix, where N is points and D is dimension
Returns
-------
min_rmsd
min_swap
min_reflection
min_review | [
"Minimize",
"RMSD",
"using",
"reflection",
"planes",
"for",
"molecule",
"P",
"and",
"Q"
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L495-L564 | train | 208,216 |
charnley/rmsd | rmsd/calculate_rmsd.py | print_coordinates | def print_coordinates(atoms, V, title=""):
"""
Print coordinates V with corresponding atoms to stdout in XYZ format.
Parameters
----------
atoms : list
List of element types
V : array
(N,3) matrix of atomic coordinates
title : string (optional)
Title of molecule
"""
print(set_coordinates(atoms, V, title=title))
return | python | def print_coordinates(atoms, V, title=""):
"""
Print coordinates V with corresponding atoms to stdout in XYZ format.
Parameters
----------
atoms : list
List of element types
V : array
(N,3) matrix of atomic coordinates
title : string (optional)
Title of molecule
"""
print(set_coordinates(atoms, V, title=title))
return | [
"def",
"print_coordinates",
"(",
"atoms",
",",
"V",
",",
"title",
"=",
"\"\"",
")",
":",
"print",
"(",
"set_coordinates",
"(",
"atoms",
",",
"V",
",",
"title",
"=",
"title",
")",
")",
"return"
] | Print coordinates V with corresponding atoms to stdout in XYZ format.
Parameters
----------
atoms : list
List of element types
V : array
(N,3) matrix of atomic coordinates
title : string (optional)
Title of molecule | [
"Print",
"coordinates",
"V",
"with",
"corresponding",
"atoms",
"to",
"stdout",
"in",
"XYZ",
"format",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L603-L620 | train | 208,217 |
charnley/rmsd | rmsd/calculate_rmsd.py | get_coordinates_pdb | def get_coordinates_pdb(filename):
"""
Get coordinates from the first chain in a pdb file
and return a vectorset with all the coordinates.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms
"""
# PDB files tend to be a bit of a mess. The x, y and z coordinates
# are supposed to be in column 31-38, 39-46 and 47-54, but this is
# not always the case.
# Because of this the three first columns containing a decimal is used.
# Since the format doesn't require a space between columns, we use the
# above column indices as a fallback.
x_column = None
V = list()
# Same with atoms and atom naming.
# The most robust way to do this is probably
# to assume that the atomtype is given in column 3.
atoms = list()
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
if line.startswith("TER") or line.startswith("END"):
break
if line.startswith("ATOM"):
tokens = line.split()
# Try to get the atomtype
try:
atom = tokens[2][0]
if atom in ("H", "C", "N", "O", "S", "P"):
atoms.append(atom)
else:
# e.g. 1HD1
atom = tokens[2][1]
if atom == "H":
atoms.append(atom)
else:
raise Exception
except:
exit("error: Parsing atomtype for the following line: \n{0:s}".format(line))
if x_column == None:
try:
# look for x column
for i, x in enumerate(tokens):
if "." in x and "." in tokens[i + 1] and "." in tokens[i + 2]:
x_column = i
break
except IndexError:
exit("error: Parsing coordinates for the following line: \n{0:s}".format(line))
# Try to read the coordinates
try:
V.append(np.asarray(tokens[x_column:x_column + 3], dtype=float))
except:
# If that doesn't work, use hardcoded indices
try:
x = line[30:38]
y = line[38:46]
z = line[46:54]
V.append(np.asarray([x, y ,z], dtype=float))
except:
exit("error: Parsing input for the following line: \n{0:s}".format(line))
V = np.asarray(V)
atoms = np.asarray(atoms)
assert V.shape[0] == atoms.size
return atoms, V | python | def get_coordinates_pdb(filename):
"""
Get coordinates from the first chain in a pdb file
and return a vectorset with all the coordinates.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms
"""
# PDB files tend to be a bit of a mess. The x, y and z coordinates
# are supposed to be in column 31-38, 39-46 and 47-54, but this is
# not always the case.
# Because of this the three first columns containing a decimal is used.
# Since the format doesn't require a space between columns, we use the
# above column indices as a fallback.
x_column = None
V = list()
# Same with atoms and atom naming.
# The most robust way to do this is probably
# to assume that the atomtype is given in column 3.
atoms = list()
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
if line.startswith("TER") or line.startswith("END"):
break
if line.startswith("ATOM"):
tokens = line.split()
# Try to get the atomtype
try:
atom = tokens[2][0]
if atom in ("H", "C", "N", "O", "S", "P"):
atoms.append(atom)
else:
# e.g. 1HD1
atom = tokens[2][1]
if atom == "H":
atoms.append(atom)
else:
raise Exception
except:
exit("error: Parsing atomtype for the following line: \n{0:s}".format(line))
if x_column == None:
try:
# look for x column
for i, x in enumerate(tokens):
if "." in x and "." in tokens[i + 1] and "." in tokens[i + 2]:
x_column = i
break
except IndexError:
exit("error: Parsing coordinates for the following line: \n{0:s}".format(line))
# Try to read the coordinates
try:
V.append(np.asarray(tokens[x_column:x_column + 3], dtype=float))
except:
# If that doesn't work, use hardcoded indices
try:
x = line[30:38]
y = line[38:46]
z = line[46:54]
V.append(np.asarray([x, y ,z], dtype=float))
except:
exit("error: Parsing input for the following line: \n{0:s}".format(line))
V = np.asarray(V)
atoms = np.asarray(atoms)
assert V.shape[0] == atoms.size
return atoms, V | [
"def",
"get_coordinates_pdb",
"(",
"filename",
")",
":",
"# PDB files tend to be a bit of a mess. The x, y and z coordinates",
"# are supposed to be in column 31-38, 39-46 and 47-54, but this is",
"# not always the case.",
"# Because of this the three first columns containing a decimal is used.",
... | Get coordinates from the first chain in a pdb file
and return a vectorset with all the coordinates.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms | [
"Get",
"coordinates",
"from",
"the",
"first",
"chain",
"in",
"a",
"pdb",
"file",
"and",
"return",
"a",
"vectorset",
"with",
"all",
"the",
"coordinates",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L649-L733 | train | 208,218 |
charnley/rmsd | rmsd/calculate_rmsd.py | get_coordinates_xyz | def get_coordinates_xyz(filename):
"""
Get coordinates from filename and return a vectorset with all the
coordinates, in XYZ format.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms
"""
f = open(filename, 'r')
V = list()
atoms = list()
n_atoms = 0
# Read the first line to obtain the number of atoms to read
try:
n_atoms = int(f.readline())
except ValueError:
exit("error: Could not obtain the number of atoms in the .xyz file.")
# Skip the title line
f.readline()
# Use the number of atoms to not read beyond the end of a file
for lines_read, line in enumerate(f):
if lines_read == n_atoms:
break
atom = re.findall(r'[a-zA-Z]+', line)[0]
atom = atom.upper()
numbers = re.findall(r'[-]?\d+\.\d*(?:[Ee][-\+]\d+)?', line)
numbers = [float(number) for number in numbers]
# The numbers are not valid unless we obtain exacly three
if len(numbers) >= 3:
V.append(np.array(numbers)[:3])
atoms.append(atom)
else:
exit("Reading the .xyz file failed in line {0}. Please check the format.".format(lines_read + 2))
f.close()
atoms = np.array(atoms)
V = np.array(V)
return atoms, V | python | def get_coordinates_xyz(filename):
"""
Get coordinates from filename and return a vectorset with all the
coordinates, in XYZ format.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms
"""
f = open(filename, 'r')
V = list()
atoms = list()
n_atoms = 0
# Read the first line to obtain the number of atoms to read
try:
n_atoms = int(f.readline())
except ValueError:
exit("error: Could not obtain the number of atoms in the .xyz file.")
# Skip the title line
f.readline()
# Use the number of atoms to not read beyond the end of a file
for lines_read, line in enumerate(f):
if lines_read == n_atoms:
break
atom = re.findall(r'[a-zA-Z]+', line)[0]
atom = atom.upper()
numbers = re.findall(r'[-]?\d+\.\d*(?:[Ee][-\+]\d+)?', line)
numbers = [float(number) for number in numbers]
# The numbers are not valid unless we obtain exacly three
if len(numbers) >= 3:
V.append(np.array(numbers)[:3])
atoms.append(atom)
else:
exit("Reading the .xyz file failed in line {0}. Please check the format.".format(lines_read + 2))
f.close()
atoms = np.array(atoms)
V = np.array(V)
return atoms, V | [
"def",
"get_coordinates_xyz",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"V",
"=",
"list",
"(",
")",
"atoms",
"=",
"list",
"(",
")",
"n_atoms",
"=",
"0",
"# Read the first line to obtain the number of atoms to read",
"try",
... | Get coordinates from filename and return a vectorset with all the
coordinates, in XYZ format.
Parameters
----------
filename : string
Filename to read
Returns
-------
atoms : list
List of atomic types
V : array
(N,3) where N is number of atoms | [
"Get",
"coordinates",
"from",
"filename",
"and",
"return",
"a",
"vectorset",
"with",
"all",
"the",
"coordinates",
"in",
"XYZ",
"format",
"."
] | cd8af499fb63529a1b5b1f880fdb2dab2731544a | https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L736-L790 | train | 208,219 |
log2timeline/dfvfs | dfvfs/vfs/zip_file_entry.py | ZipFileEntry.GetZipInfo | def GetZipInfo(self):
"""Retrieves the ZIP info object.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect.
"""
if not self._zip_info:
location = getattr(self.path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if not location.startswith(self._file_system.LOCATION_ROOT):
raise errors.PathSpecError('Invalid location in path specification.')
if len(location) == 1:
return None
zip_file = self._file_system.GetZipFile()
try:
self._zip_info = zip_file.getinfo(location[1:])
except KeyError:
pass
return self._zip_info | python | def GetZipInfo(self):
"""Retrieves the ZIP info object.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect.
"""
if not self._zip_info:
location = getattr(self.path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if not location.startswith(self._file_system.LOCATION_ROOT):
raise errors.PathSpecError('Invalid location in path specification.')
if len(location) == 1:
return None
zip_file = self._file_system.GetZipFile()
try:
self._zip_info = zip_file.getinfo(location[1:])
except KeyError:
pass
return self._zip_info | [
"def",
"GetZipInfo",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_zip_info",
":",
"location",
"=",
"getattr",
"(",
"self",
".",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"location",
"is",
"None",
":",
"raise",
"errors",
".",
"PathSp... | Retrieves the ZIP info object.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect. | [
"Retrieves",
"the",
"ZIP",
"info",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/zip_file_entry.py#L246-L272 | train | 208,220 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | VolumeScanner._NormalizedVolumeIdentifiers | def _NormalizedVolumeIdentifiers(
self, volume_system, volume_identifiers, prefix='v'):
"""Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: volume identifiers with prefix.
Raises:
ScannerError: if the volume identifier is not supported or no volume
could be found that corresponds with the identifier.
"""
normalized_volume_identifiers = []
for volume_identifier in volume_identifiers:
if isinstance(volume_identifier, int):
volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)
elif not volume_identifier.startswith(prefix):
try:
volume_identifier = int(volume_identifier, 10)
volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)
except (TypeError, ValueError):
pass
try:
volume = volume_system.GetVolumeByIdentifier(volume_identifier)
except KeyError:
volume = None
if not volume:
raise errors.ScannerError(
'Volume missing for identifier: {0:s}.'.format(volume_identifier))
normalized_volume_identifiers.append(volume_identifier)
return normalized_volume_identifiers | python | def _NormalizedVolumeIdentifiers(
self, volume_system, volume_identifiers, prefix='v'):
"""Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: volume identifiers with prefix.
Raises:
ScannerError: if the volume identifier is not supported or no volume
could be found that corresponds with the identifier.
"""
normalized_volume_identifiers = []
for volume_identifier in volume_identifiers:
if isinstance(volume_identifier, int):
volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)
elif not volume_identifier.startswith(prefix):
try:
volume_identifier = int(volume_identifier, 10)
volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier)
except (TypeError, ValueError):
pass
try:
volume = volume_system.GetVolumeByIdentifier(volume_identifier)
except KeyError:
volume = None
if not volume:
raise errors.ScannerError(
'Volume missing for identifier: {0:s}.'.format(volume_identifier))
normalized_volume_identifiers.append(volume_identifier)
return normalized_volume_identifiers | [
"def",
"_NormalizedVolumeIdentifiers",
"(",
"self",
",",
"volume_system",
",",
"volume_identifiers",
",",
"prefix",
"=",
"'v'",
")",
":",
"normalized_volume_identifiers",
"=",
"[",
"]",
"for",
"volume_identifier",
"in",
"volume_identifiers",
":",
"if",
"isinstance",
... | Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: volume identifiers with prefix.
Raises:
ScannerError: if the volume identifier is not supported or no volume
could be found that corresponds with the identifier. | [
"Normalizes",
"volume",
"identifiers",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L230-L270 | train | 208,221 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | VolumeScanner._ScanVolume | def _ScanVolume(self, scan_context, scan_node, base_path_specs):
"""Scans a volume scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the format of or within the source
is not supported or the scan node is invalid.
"""
if not scan_node or not scan_node.path_spec:
raise errors.ScannerError('Invalid or missing scan node.')
if scan_context.IsLockedScanNode(scan_node.path_spec):
# The source scanner found a locked volume and we need a credential to
# unlock it.
self._ScanEncryptedVolume(scan_context, scan_node)
if scan_context.IsLockedScanNode(scan_node.path_spec):
return
if scan_node.IsVolumeSystemRoot():
self._ScanVolumeSystemRoot(scan_context, scan_node, base_path_specs)
elif scan_node.IsFileSystem():
self._ScanFileSystem(scan_node, base_path_specs)
elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:
# TODO: look into building VSS store on demand.
# We "optimize" here for user experience, alternatively we could scan for
# a file system instead of hard coding a TSK child path specification.
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_TSK, location='/',
parent=scan_node.path_spec)
base_path_specs.append(path_spec)
else:
for sub_scan_node in scan_node.sub_nodes:
self._ScanVolume(scan_context, sub_scan_node, base_path_specs) | python | def _ScanVolume(self, scan_context, scan_node, base_path_specs):
"""Scans a volume scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the format of or within the source
is not supported or the scan node is invalid.
"""
if not scan_node or not scan_node.path_spec:
raise errors.ScannerError('Invalid or missing scan node.')
if scan_context.IsLockedScanNode(scan_node.path_spec):
# The source scanner found a locked volume and we need a credential to
# unlock it.
self._ScanEncryptedVolume(scan_context, scan_node)
if scan_context.IsLockedScanNode(scan_node.path_spec):
return
if scan_node.IsVolumeSystemRoot():
self._ScanVolumeSystemRoot(scan_context, scan_node, base_path_specs)
elif scan_node.IsFileSystem():
self._ScanFileSystem(scan_node, base_path_specs)
elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:
# TODO: look into building VSS store on demand.
# We "optimize" here for user experience, alternatively we could scan for
# a file system instead of hard coding a TSK child path specification.
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_TSK, location='/',
parent=scan_node.path_spec)
base_path_specs.append(path_spec)
else:
for sub_scan_node in scan_node.sub_nodes:
self._ScanVolume(scan_context, sub_scan_node, base_path_specs) | [
"def",
"_ScanVolume",
"(",
"self",
",",
"scan_context",
",",
"scan_node",
",",
"base_path_specs",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"ScannerError",
"(",
"'Invalid or missing scan node.'",
... | Scans a volume scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the format of or within the source
is not supported or the scan node is invalid. | [
"Scans",
"a",
"volume",
"scan",
"node",
"for",
"volume",
"and",
"file",
"systems",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L318-L360 | train | 208,222 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | VolumeScanner._ScanVolumeSystemRoot | def _ScanVolumeSystemRoot(self, scan_context, scan_node, base_path_specs):
"""Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the scan node is invalid, the scan node type is not
supported or if a sub scan node cannot be retrieved.
"""
if not scan_node or not scan_node.path_spec:
raise errors.ScannerError('Invalid scan node.')
if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER:
volume_identifiers = self._GetAPFSVolumeIdentifiers(scan_node)
elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:
volume_identifiers = self._GetVSSStoreIdentifiers(scan_node)
# Process VSS stores (snapshots) starting with the most recent one.
volume_identifiers.reverse()
else:
raise errors.ScannerError(
'Unsupported volume system type: {0:s}.'.format(
scan_node.type_indicator))
for volume_identifier in volume_identifiers:
location = '/{0:s}'.format(volume_identifier)
sub_scan_node = scan_node.GetSubNodeByLocation(location)
if not sub_scan_node:
raise errors.ScannerError(
'Scan node missing for volume identifier: {0:s}.'.format(
volume_identifier))
self._ScanVolume(scan_context, sub_scan_node, base_path_specs) | python | def _ScanVolumeSystemRoot(self, scan_context, scan_node, base_path_specs):
"""Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the scan node is invalid, the scan node type is not
supported or if a sub scan node cannot be retrieved.
"""
if not scan_node or not scan_node.path_spec:
raise errors.ScannerError('Invalid scan node.')
if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER:
volume_identifiers = self._GetAPFSVolumeIdentifiers(scan_node)
elif scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:
volume_identifiers = self._GetVSSStoreIdentifiers(scan_node)
# Process VSS stores (snapshots) starting with the most recent one.
volume_identifiers.reverse()
else:
raise errors.ScannerError(
'Unsupported volume system type: {0:s}.'.format(
scan_node.type_indicator))
for volume_identifier in volume_identifiers:
location = '/{0:s}'.format(volume_identifier)
sub_scan_node = scan_node.GetSubNodeByLocation(location)
if not sub_scan_node:
raise errors.ScannerError(
'Scan node missing for volume identifier: {0:s}.'.format(
volume_identifier))
self._ScanVolume(scan_context, sub_scan_node, base_path_specs) | [
"def",
"_ScanVolumeSystemRoot",
"(",
"self",
",",
"scan_context",
",",
"scan_node",
",",
"base_path_specs",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"ScannerError",
"(",
"'Invalid scan node.'",
... | Scans a volume system root scan node for volume and file systems.
Args:
scan_context (SourceScannerContext): source scanner context.
scan_node (SourceScanNode): volume system root scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
ScannerError: if the scan node is invalid, the scan node type is not
supported or if a sub scan node cannot be retrieved. | [
"Scans",
"a",
"volume",
"system",
"root",
"scan",
"node",
"for",
"volume",
"and",
"file",
"systems",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L362-L398 | train | 208,223 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | VolumeScanner.GetBasePathSpecs | def GetBasePathSpecs(self, source_path):
"""Determines the base path specifications.
Args:
source_path (str): source path.
Returns:
list[PathSpec]: path specifications.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
if not source_path:
raise errors.ScannerError('Invalid source path.')
# Note that os.path.exists() does not support Windows device paths.
if (not source_path.startswith('\\\\.\\') and
not os.path.exists(source_path)):
raise errors.ScannerError(
'No such device, file or directory: {0:s}.'.format(source_path))
scan_context = source_scanner.SourceScannerContext()
scan_context.OpenSourcePath(source_path)
try:
self._source_scanner.Scan(scan_context)
except (ValueError, errors.BackEndError) as exception:
raise errors.ScannerError(
'Unable to scan source with error: {0!s}'.format(exception))
self._source_path = source_path
self._source_type = scan_context.source_type
if self._source_type not in [
definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE,
definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE]:
scan_node = scan_context.GetRootScanNode()
return [scan_node.path_spec]
# Get the first node where where we need to decide what to process.
scan_node = scan_context.GetRootScanNode()
while len(scan_node.sub_nodes) == 1:
scan_node = scan_node.sub_nodes[0]
base_path_specs = []
if scan_node.type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION:
self._ScanVolume(scan_context, scan_node, base_path_specs)
else:
# Determine which partition needs to be processed.
partition_identifiers = self._GetTSKPartitionIdentifiers(scan_node)
for partition_identifier in partition_identifiers:
location = '/{0:s}'.format(partition_identifier)
sub_scan_node = scan_node.GetSubNodeByLocation(location)
self._ScanVolume(scan_context, sub_scan_node, base_path_specs)
return base_path_specs | python | def GetBasePathSpecs(self, source_path):
"""Determines the base path specifications.
Args:
source_path (str): source path.
Returns:
list[PathSpec]: path specifications.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
if not source_path:
raise errors.ScannerError('Invalid source path.')
# Note that os.path.exists() does not support Windows device paths.
if (not source_path.startswith('\\\\.\\') and
not os.path.exists(source_path)):
raise errors.ScannerError(
'No such device, file or directory: {0:s}.'.format(source_path))
scan_context = source_scanner.SourceScannerContext()
scan_context.OpenSourcePath(source_path)
try:
self._source_scanner.Scan(scan_context)
except (ValueError, errors.BackEndError) as exception:
raise errors.ScannerError(
'Unable to scan source with error: {0!s}'.format(exception))
self._source_path = source_path
self._source_type = scan_context.source_type
if self._source_type not in [
definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE,
definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE]:
scan_node = scan_context.GetRootScanNode()
return [scan_node.path_spec]
# Get the first node where where we need to decide what to process.
scan_node = scan_context.GetRootScanNode()
while len(scan_node.sub_nodes) == 1:
scan_node = scan_node.sub_nodes[0]
base_path_specs = []
if scan_node.type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION:
self._ScanVolume(scan_context, scan_node, base_path_specs)
else:
# Determine which partition needs to be processed.
partition_identifiers = self._GetTSKPartitionIdentifiers(scan_node)
for partition_identifier in partition_identifiers:
location = '/{0:s}'.format(partition_identifier)
sub_scan_node = scan_node.GetSubNodeByLocation(location)
self._ScanVolume(scan_context, sub_scan_node, base_path_specs)
return base_path_specs | [
"def",
"GetBasePathSpecs",
"(",
"self",
",",
"source_path",
")",
":",
"if",
"not",
"source_path",
":",
"raise",
"errors",
".",
"ScannerError",
"(",
"'Invalid source path.'",
")",
"# Note that os.path.exists() does not support Windows device paths.",
"if",
"(",
"not",
"s... | Determines the base path specifications.
Args:
source_path (str): source path.
Returns:
list[PathSpec]: path specifications.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported. | [
"Determines",
"the",
"base",
"path",
"specifications",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L400-L458 | train | 208,224 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | WindowsVolumeScanner._ScanFileSystemForWindowsDirectory | def _ScanFileSystemForWindowsDirectory(self, path_resolver):
"""Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found.
"""
result = False
for windows_path in self._WINDOWS_DIRECTORIES:
windows_path_spec = path_resolver.ResolvePath(windows_path)
result = windows_path_spec is not None
if result:
self._windows_directory = windows_path
break
return result | python | def _ScanFileSystemForWindowsDirectory(self, path_resolver):
"""Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found.
"""
result = False
for windows_path in self._WINDOWS_DIRECTORIES:
windows_path_spec = path_resolver.ResolvePath(windows_path)
result = windows_path_spec is not None
if result:
self._windows_directory = windows_path
break
return result | [
"def",
"_ScanFileSystemForWindowsDirectory",
"(",
"self",
",",
"path_resolver",
")",
":",
"result",
"=",
"False",
"for",
"windows_path",
"in",
"self",
".",
"_WINDOWS_DIRECTORIES",
":",
"windows_path_spec",
"=",
"path_resolver",
".",
"ResolvePath",
"(",
"windows_path",... | Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found. | [
"Scans",
"a",
"file",
"system",
"for",
"a",
"known",
"Windows",
"directory",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L511-L529 | train | 208,225 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | WindowsVolumeScanner.OpenFile | def OpenFile(self, windows_path):
"""Opens the file specificed by the Windows path.
Args:
windows_path (str): Windows path to the file.
Returns:
FileIO: file-like object or None if the file does not exist.
"""
path_spec = self._path_resolver.ResolvePath(windows_path)
if path_spec is None:
return None
return self._file_system.GetFileObjectByPathSpec(path_spec) | python | def OpenFile(self, windows_path):
"""Opens the file specificed by the Windows path.
Args:
windows_path (str): Windows path to the file.
Returns:
FileIO: file-like object or None if the file does not exist.
"""
path_spec = self._path_resolver.ResolvePath(windows_path)
if path_spec is None:
return None
return self._file_system.GetFileObjectByPathSpec(path_spec) | [
"def",
"OpenFile",
"(",
"self",
",",
"windows_path",
")",
":",
"path_spec",
"=",
"self",
".",
"_path_resolver",
".",
"ResolvePath",
"(",
"windows_path",
")",
"if",
"path_spec",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_file_system",
".",
... | Opens the file specificed by the Windows path.
Args:
windows_path (str): Windows path to the file.
Returns:
FileIO: file-like object or None if the file does not exist. | [
"Opens",
"the",
"file",
"specificed",
"by",
"the",
"Windows",
"path",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L531-L544 | train | 208,226 |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | WindowsVolumeScanner.ScanForWindowsVolume | def ScanForWindowsVolume(self, source_path):
"""Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
windows_path_specs = self.GetBasePathSpecs(source_path)
if (not windows_path_specs or
self._source_type == definitions.SOURCE_TYPE_FILE):
return False
file_system_path_spec = windows_path_specs[0]
self._file_system = resolver.Resolver.OpenFileSystem(file_system_path_spec)
if file_system_path_spec.type_indicator == definitions.TYPE_INDICATOR_OS:
mount_point = file_system_path_spec
else:
mount_point = file_system_path_spec.parent
self._path_resolver = windows_path_resolver.WindowsPathResolver(
self._file_system, mount_point)
# The source is a directory or single volume storage media image.
if not self._windows_directory:
self._ScanFileSystemForWindowsDirectory(self._path_resolver)
if not self._windows_directory:
return False
self._path_resolver.SetEnvironmentVariable(
'SystemRoot', self._windows_directory)
self._path_resolver.SetEnvironmentVariable(
'WinDir', self._windows_directory)
return True | python | def ScanForWindowsVolume(self, source_path):
"""Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
windows_path_specs = self.GetBasePathSpecs(source_path)
if (not windows_path_specs or
self._source_type == definitions.SOURCE_TYPE_FILE):
return False
file_system_path_spec = windows_path_specs[0]
self._file_system = resolver.Resolver.OpenFileSystem(file_system_path_spec)
if file_system_path_spec.type_indicator == definitions.TYPE_INDICATOR_OS:
mount_point = file_system_path_spec
else:
mount_point = file_system_path_spec.parent
self._path_resolver = windows_path_resolver.WindowsPathResolver(
self._file_system, mount_point)
# The source is a directory or single volume storage media image.
if not self._windows_directory:
self._ScanFileSystemForWindowsDirectory(self._path_resolver)
if not self._windows_directory:
return False
self._path_resolver.SetEnvironmentVariable(
'SystemRoot', self._windows_directory)
self._path_resolver.SetEnvironmentVariable(
'WinDir', self._windows_directory)
return True | [
"def",
"ScanForWindowsVolume",
"(",
"self",
",",
"source_path",
")",
":",
"windows_path_specs",
"=",
"self",
".",
"GetBasePathSpecs",
"(",
"source_path",
")",
"if",
"(",
"not",
"windows_path_specs",
"or",
"self",
".",
"_source_type",
"==",
"definitions",
".",
"S... | Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported. | [
"Scans",
"for",
"a",
"Windows",
"volume",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L546-L588 | train | 208,227 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer._FlushCache | def _FlushCache(cls, format_categories):
"""Flushes the cached objects for the specified format categories.
Args:
format_categories (set[str]): format categories.
"""
if definitions.FORMAT_CATEGORY_ARCHIVE in format_categories:
cls._archive_remainder_list = None
cls._archive_scanner = None
cls._archive_store = None
if definitions.FORMAT_CATEGORY_COMPRESSED_STREAM in format_categories:
cls._compressed_stream_remainder_list = None
cls._compressed_stream_scanner = None
cls._compressed_stream_store = None
if definitions.FORMAT_CATEGORY_FILE_SYSTEM in format_categories:
cls._file_system_remainder_list = None
cls._file_system_scanner = None
cls._file_system_store = None
if definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE in format_categories:
cls._storage_media_image_remainder_list = None
cls._storage_media_image_scanner = None
cls._storage_media_image_store = None
if definitions.FORMAT_CATEGORY_VOLUME_SYSTEM in format_categories:
cls._volume_system_remainder_list = None
cls._volume_system_scanner = None
cls._volume_system_store = None | python | def _FlushCache(cls, format_categories):
"""Flushes the cached objects for the specified format categories.
Args:
format_categories (set[str]): format categories.
"""
if definitions.FORMAT_CATEGORY_ARCHIVE in format_categories:
cls._archive_remainder_list = None
cls._archive_scanner = None
cls._archive_store = None
if definitions.FORMAT_CATEGORY_COMPRESSED_STREAM in format_categories:
cls._compressed_stream_remainder_list = None
cls._compressed_stream_scanner = None
cls._compressed_stream_store = None
if definitions.FORMAT_CATEGORY_FILE_SYSTEM in format_categories:
cls._file_system_remainder_list = None
cls._file_system_scanner = None
cls._file_system_store = None
if definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE in format_categories:
cls._storage_media_image_remainder_list = None
cls._storage_media_image_scanner = None
cls._storage_media_image_store = None
if definitions.FORMAT_CATEGORY_VOLUME_SYSTEM in format_categories:
cls._volume_system_remainder_list = None
cls._volume_system_scanner = None
cls._volume_system_store = None | [
"def",
"_FlushCache",
"(",
"cls",
",",
"format_categories",
")",
":",
"if",
"definitions",
".",
"FORMAT_CATEGORY_ARCHIVE",
"in",
"format_categories",
":",
"cls",
".",
"_archive_remainder_list",
"=",
"None",
"cls",
".",
"_archive_scanner",
"=",
"None",
"cls",
".",
... | Flushes the cached objects for the specified format categories.
Args:
format_categories (set[str]): format categories. | [
"Flushes",
"the",
"cached",
"objects",
"for",
"the",
"specified",
"format",
"categories",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L71-L100 | train | 208,228 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer._GetSignatureScanner | def _GetSignatureScanner(cls, specification_store):
"""Initializes a signature scanner based on a specification store.
Args:
specification_store (FormatSpecificationStore): specification store.
Returns:
pysigscan.scanner: signature scanner.
"""
signature_scanner = pysigscan.scanner()
signature_scanner.set_scan_buffer_size(cls._SCAN_BUFFER_SIZE)
for format_specification in specification_store.specifications:
for signature in format_specification.signatures:
pattern_offset = signature.offset
if pattern_offset is None:
signature_flags = pysigscan.signature_flags.NO_OFFSET
elif pattern_offset < 0:
pattern_offset *= -1
signature_flags = pysigscan.signature_flags.RELATIVE_FROM_END
else:
signature_flags = pysigscan.signature_flags.RELATIVE_FROM_START
signature_scanner.add_signature(
signature.identifier, pattern_offset, signature.pattern,
signature_flags)
return signature_scanner | python | def _GetSignatureScanner(cls, specification_store):
"""Initializes a signature scanner based on a specification store.
Args:
specification_store (FormatSpecificationStore): specification store.
Returns:
pysigscan.scanner: signature scanner.
"""
signature_scanner = pysigscan.scanner()
signature_scanner.set_scan_buffer_size(cls._SCAN_BUFFER_SIZE)
for format_specification in specification_store.specifications:
for signature in format_specification.signatures:
pattern_offset = signature.offset
if pattern_offset is None:
signature_flags = pysigscan.signature_flags.NO_OFFSET
elif pattern_offset < 0:
pattern_offset *= -1
signature_flags = pysigscan.signature_flags.RELATIVE_FROM_END
else:
signature_flags = pysigscan.signature_flags.RELATIVE_FROM_START
signature_scanner.add_signature(
signature.identifier, pattern_offset, signature.pattern,
signature_flags)
return signature_scanner | [
"def",
"_GetSignatureScanner",
"(",
"cls",
",",
"specification_store",
")",
":",
"signature_scanner",
"=",
"pysigscan",
".",
"scanner",
"(",
")",
"signature_scanner",
".",
"set_scan_buffer_size",
"(",
"cls",
".",
"_SCAN_BUFFER_SIZE",
")",
"for",
"format_specification"... | Initializes a signature scanner based on a specification store.
Args:
specification_store (FormatSpecificationStore): specification store.
Returns:
pysigscan.scanner: signature scanner. | [
"Initializes",
"a",
"signature",
"scanner",
"based",
"on",
"a",
"specification",
"store",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L103-L131 | train | 208,229 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer._GetSpecificationStore | def _GetSpecificationStore(cls, format_category):
"""Retrieves the specification store for specified format category.
Args:
format_category (str): format category.
Returns:
tuple[FormatSpecificationStore, list[AnalyzerHelper]]: a format
specification store and remaining analyzer helpers that do not have
a format specification.
"""
specification_store = specification.FormatSpecificationStore()
remainder_list = []
for analyzer_helper in iter(cls._analyzer_helpers.values()):
if not analyzer_helper.IsEnabled():
continue
if format_category in analyzer_helper.format_categories:
format_specification = analyzer_helper.GetFormatSpecification()
if format_specification is not None:
specification_store.AddSpecification(format_specification)
else:
remainder_list.append(analyzer_helper)
return specification_store, remainder_list | python | def _GetSpecificationStore(cls, format_category):
"""Retrieves the specification store for specified format category.
Args:
format_category (str): format category.
Returns:
tuple[FormatSpecificationStore, list[AnalyzerHelper]]: a format
specification store and remaining analyzer helpers that do not have
a format specification.
"""
specification_store = specification.FormatSpecificationStore()
remainder_list = []
for analyzer_helper in iter(cls._analyzer_helpers.values()):
if not analyzer_helper.IsEnabled():
continue
if format_category in analyzer_helper.format_categories:
format_specification = analyzer_helper.GetFormatSpecification()
if format_specification is not None:
specification_store.AddSpecification(format_specification)
else:
remainder_list.append(analyzer_helper)
return specification_store, remainder_list | [
"def",
"_GetSpecificationStore",
"(",
"cls",
",",
"format_category",
")",
":",
"specification_store",
"=",
"specification",
".",
"FormatSpecificationStore",
"(",
")",
"remainder_list",
"=",
"[",
"]",
"for",
"analyzer_helper",
"in",
"iter",
"(",
"cls",
".",
"_analy... | Retrieves the specification store for specified format category.
Args:
format_category (str): format category.
Returns:
tuple[FormatSpecificationStore, list[AnalyzerHelper]]: a format
specification store and remaining analyzer helpers that do not have
a format specification. | [
"Retrieves",
"the",
"specification",
"store",
"for",
"specified",
"format",
"category",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L134-L160 | train | 208,230 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer._GetTypeIndicators | def _GetTypeIndicators(
cls, signature_scanner, specification_store, remainder_list, path_spec,
resolver_context=None):
"""Determines if a file contains a supported format types.
Args:
signature_scanner (pysigscan.scanner): signature scanner.
specification_store (FormatSpecificationStore): specification store.
remainder_list (list[AnalyzerHelper]): remaining analyzer helpers that
do not have a format specification.
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
type_indicator_list = []
file_object = resolver.Resolver.OpenFileObject(
path_spec, resolver_context=resolver_context)
scan_state = pysigscan.scan_state()
try:
signature_scanner.scan_file_object(scan_state, file_object)
for scan_result in iter(scan_state.scan_results):
format_specification = specification_store.GetSpecificationBySignature(
scan_result.identifier)
if format_specification.identifier not in type_indicator_list:
type_indicator_list.append(format_specification.identifier)
for analyzer_helper in remainder_list:
result = analyzer_helper.AnalyzeFileObject(file_object)
if result is not None:
type_indicator_list.append(result)
finally:
file_object.close()
return type_indicator_list | python | def _GetTypeIndicators(
cls, signature_scanner, specification_store, remainder_list, path_spec,
resolver_context=None):
"""Determines if a file contains a supported format types.
Args:
signature_scanner (pysigscan.scanner): signature scanner.
specification_store (FormatSpecificationStore): specification store.
remainder_list (list[AnalyzerHelper]): remaining analyzer helpers that
do not have a format specification.
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
type_indicator_list = []
file_object = resolver.Resolver.OpenFileObject(
path_spec, resolver_context=resolver_context)
scan_state = pysigscan.scan_state()
try:
signature_scanner.scan_file_object(scan_state, file_object)
for scan_result in iter(scan_state.scan_results):
format_specification = specification_store.GetSpecificationBySignature(
scan_result.identifier)
if format_specification.identifier not in type_indicator_list:
type_indicator_list.append(format_specification.identifier)
for analyzer_helper in remainder_list:
result = analyzer_helper.AnalyzeFileObject(file_object)
if result is not None:
type_indicator_list.append(result)
finally:
file_object.close()
return type_indicator_list | [
"def",
"_GetTypeIndicators",
"(",
"cls",
",",
"signature_scanner",
",",
"specification_store",
",",
"remainder_list",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"type_indicator_list",
"=",
"[",
"]",
"file_object",
"=",
"resolver",
".",
"Reso... | Determines if a file contains a supported format types.
Args:
signature_scanner (pysigscan.scanner): signature scanner.
specification_store (FormatSpecificationStore): specification store.
remainder_list (list[AnalyzerHelper]): remaining analyzer helpers that
do not have a format specification.
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"format",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L163-L205 | train | 208,231 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.DeregisterHelper | def DeregisterHelper(cls, analyzer_helper):
"""Deregisters a format analyzer helper.
Args:
analyzer_helper (AnalyzerHelper): analyzer helper.
Raises:
KeyError: if analyzer helper object is not set for the corresponding
type indicator.
"""
if analyzer_helper.type_indicator not in cls._analyzer_helpers:
raise KeyError(
'Analyzer helper object not set for type indicator: {0:s}.'.format(
analyzer_helper.type_indicator))
analyzer_helper = cls._analyzer_helpers[analyzer_helper.type_indicator]
cls._FlushCache(analyzer_helper.format_categories)
del cls._analyzer_helpers[analyzer_helper.type_indicator] | python | def DeregisterHelper(cls, analyzer_helper):
"""Deregisters a format analyzer helper.
Args:
analyzer_helper (AnalyzerHelper): analyzer helper.
Raises:
KeyError: if analyzer helper object is not set for the corresponding
type indicator.
"""
if analyzer_helper.type_indicator not in cls._analyzer_helpers:
raise KeyError(
'Analyzer helper object not set for type indicator: {0:s}.'.format(
analyzer_helper.type_indicator))
analyzer_helper = cls._analyzer_helpers[analyzer_helper.type_indicator]
cls._FlushCache(analyzer_helper.format_categories)
del cls._analyzer_helpers[analyzer_helper.type_indicator] | [
"def",
"DeregisterHelper",
"(",
"cls",
",",
"analyzer_helper",
")",
":",
"if",
"analyzer_helper",
".",
"type_indicator",
"not",
"in",
"cls",
".",
"_analyzer_helpers",
":",
"raise",
"KeyError",
"(",
"'Analyzer helper object not set for type indicator: {0:s}.'",
".",
"for... | Deregisters a format analyzer helper.
Args:
analyzer_helper (AnalyzerHelper): analyzer helper.
Raises:
KeyError: if analyzer helper object is not set for the corresponding
type indicator. | [
"Deregisters",
"a",
"format",
"analyzer",
"helper",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L208-L227 | train | 208,232 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.GetArchiveTypeIndicators | def GetArchiveTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._archive_remainder_list is None or
cls._archive_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_ARCHIVE)
cls._archive_remainder_list = remainder_list
cls._archive_store = specification_store
if cls._archive_scanner is None:
cls._archive_scanner = cls._GetSignatureScanner(cls._archive_store)
return cls._GetTypeIndicators(
cls._archive_scanner, cls._archive_store,
cls._archive_remainder_list, path_spec,
resolver_context=resolver_context) | python | def GetArchiveTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._archive_remainder_list is None or
cls._archive_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_ARCHIVE)
cls._archive_remainder_list = remainder_list
cls._archive_store = specification_store
if cls._archive_scanner is None:
cls._archive_scanner = cls._GetSignatureScanner(cls._archive_store)
return cls._GetTypeIndicators(
cls._archive_scanner, cls._archive_store,
cls._archive_remainder_list, path_spec,
resolver_context=resolver_context) | [
"def",
"GetArchiveTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_archive_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_archive_store",
"is",
"None",
")",
":",
"specification_store",
... | Determines if a file contains a supported archive types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"archive",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L230-L254 | train | 208,233 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.GetCompressedStreamTypeIndicators | def GetCompressedStreamTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported compressed stream types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._compressed_stream_remainder_list is None or
cls._compressed_stream_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_COMPRESSED_STREAM)
cls._compressed_stream_remainder_list = remainder_list
cls._compressed_stream_store = specification_store
if cls._compressed_stream_scanner is None:
cls._compressed_stream_scanner = cls._GetSignatureScanner(
cls._compressed_stream_store)
return cls._GetTypeIndicators(
cls._compressed_stream_scanner, cls._compressed_stream_store,
cls._compressed_stream_remainder_list, path_spec,
resolver_context=resolver_context) | python | def GetCompressedStreamTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported compressed stream types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._compressed_stream_remainder_list is None or
cls._compressed_stream_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_COMPRESSED_STREAM)
cls._compressed_stream_remainder_list = remainder_list
cls._compressed_stream_store = specification_store
if cls._compressed_stream_scanner is None:
cls._compressed_stream_scanner = cls._GetSignatureScanner(
cls._compressed_stream_store)
return cls._GetTypeIndicators(
cls._compressed_stream_scanner, cls._compressed_stream_store,
cls._compressed_stream_remainder_list, path_spec,
resolver_context=resolver_context) | [
"def",
"GetCompressedStreamTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_compressed_stream_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_compressed_stream_store",
"is",
"None",
")",
":"... | Determines if a file contains a supported compressed stream types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"compressed",
"stream",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L257-L282 | train | 208,234 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.GetFileSystemTypeIndicators | def GetFileSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported file system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._file_system_remainder_list is None or
cls._file_system_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_FILE_SYSTEM)
cls._file_system_remainder_list = remainder_list
cls._file_system_store = specification_store
if cls._file_system_scanner is None:
cls._file_system_scanner = cls._GetSignatureScanner(
cls._file_system_store)
return cls._GetTypeIndicators(
cls._file_system_scanner, cls._file_system_store,
cls._file_system_remainder_list, path_spec,
resolver_context=resolver_context) | python | def GetFileSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported file system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._file_system_remainder_list is None or
cls._file_system_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_FILE_SYSTEM)
cls._file_system_remainder_list = remainder_list
cls._file_system_store = specification_store
if cls._file_system_scanner is None:
cls._file_system_scanner = cls._GetSignatureScanner(
cls._file_system_store)
return cls._GetTypeIndicators(
cls._file_system_scanner, cls._file_system_store,
cls._file_system_remainder_list, path_spec,
resolver_context=resolver_context) | [
"def",
"GetFileSystemTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_file_system_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_file_system_store",
"is",
"None",
")",
":",
"specification... | Determines if a file contains a supported file system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"file",
"system",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L285-L310 | train | 208,235 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.GetStorageMediaImageTypeIndicators | def GetStorageMediaImageTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported storage media image types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._storage_media_image_remainder_list is None or
cls._storage_media_image_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE)
cls._storage_media_image_remainder_list = remainder_list
cls._storage_media_image_store = specification_store
if cls._storage_media_image_scanner is None:
cls._storage_media_image_scanner = cls._GetSignatureScanner(
cls._storage_media_image_store)
return cls._GetTypeIndicators(
cls._storage_media_image_scanner, cls._storage_media_image_store,
cls._storage_media_image_remainder_list, path_spec,
resolver_context=resolver_context) | python | def GetStorageMediaImageTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported storage media image types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._storage_media_image_remainder_list is None or
cls._storage_media_image_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE)
cls._storage_media_image_remainder_list = remainder_list
cls._storage_media_image_store = specification_store
if cls._storage_media_image_scanner is None:
cls._storage_media_image_scanner = cls._GetSignatureScanner(
cls._storage_media_image_store)
return cls._GetTypeIndicators(
cls._storage_media_image_scanner, cls._storage_media_image_store,
cls._storage_media_image_remainder_list, path_spec,
resolver_context=resolver_context) | [
"def",
"GetStorageMediaImageTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_storage_media_image_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_storage_media_image_store",
"is",
"None",
")",
... | Determines if a file contains a supported storage media image types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"storage",
"media",
"image",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L313-L338 | train | 208,236 |
log2timeline/dfvfs | dfvfs/analyzer/analyzer.py | Analyzer.GetVolumeSystemTypeIndicators | def GetVolumeSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported volume system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._volume_system_remainder_list is None or
cls._volume_system_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_VOLUME_SYSTEM)
cls._volume_system_remainder_list = remainder_list
cls._volume_system_store = specification_store
if cls._volume_system_scanner is None:
cls._volume_system_scanner = cls._GetSignatureScanner(
cls._volume_system_store)
return cls._GetTypeIndicators(
cls._volume_system_scanner, cls._volume_system_store,
cls._volume_system_remainder_list, path_spec,
resolver_context=resolver_context) | python | def GetVolumeSystemTypeIndicators(cls, path_spec, resolver_context=None):
"""Determines if a file contains a supported volume system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators.
"""
if (cls._volume_system_remainder_list is None or
cls._volume_system_store is None):
specification_store, remainder_list = cls._GetSpecificationStore(
definitions.FORMAT_CATEGORY_VOLUME_SYSTEM)
cls._volume_system_remainder_list = remainder_list
cls._volume_system_store = specification_store
if cls._volume_system_scanner is None:
cls._volume_system_scanner = cls._GetSignatureScanner(
cls._volume_system_store)
return cls._GetTypeIndicators(
cls._volume_system_scanner, cls._volume_system_store,
cls._volume_system_remainder_list, path_spec,
resolver_context=resolver_context) | [
"def",
"GetVolumeSystemTypeIndicators",
"(",
"cls",
",",
"path_spec",
",",
"resolver_context",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_volume_system_remainder_list",
"is",
"None",
"or",
"cls",
".",
"_volume_system_store",
"is",
"None",
")",
":",
"specifi... | Determines if a file contains a supported volume system types.
Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.
Returns:
list[str]: supported format type indicators. | [
"Determines",
"if",
"a",
"file",
"contains",
"a",
"supported",
"volume",
"system",
"types",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/analyzer/analyzer.py#L341-L366 | train | 208,237 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | TSKFileSystem.GetFsType | def GetFsType(self):
"""Retrieves the file system type.
Returns:
pytsk3.TSK_FS_TYPE_ENUM: file system type.
"""
if self._tsk_fs_type is None:
self._tsk_fs_type = pytsk3.TSK_FS_TYPE_UNSUPP
if (not self._tsk_file_system or
not hasattr(self._tsk_file_system, 'info')):
return self._tsk_fs_type
self._tsk_fs_type = getattr(
self._tsk_file_system.info, 'ftype', pytsk3.TSK_FS_TYPE_UNSUPP)
return self._tsk_fs_type | python | def GetFsType(self):
"""Retrieves the file system type.
Returns:
pytsk3.TSK_FS_TYPE_ENUM: file system type.
"""
if self._tsk_fs_type is None:
self._tsk_fs_type = pytsk3.TSK_FS_TYPE_UNSUPP
if (not self._tsk_file_system or
not hasattr(self._tsk_file_system, 'info')):
return self._tsk_fs_type
self._tsk_fs_type = getattr(
self._tsk_file_system.info, 'ftype', pytsk3.TSK_FS_TYPE_UNSUPP)
return self._tsk_fs_type | [
"def",
"GetFsType",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tsk_fs_type",
"is",
"None",
":",
"self",
".",
"_tsk_fs_type",
"=",
"pytsk3",
".",
"TSK_FS_TYPE_UNSUPP",
"if",
"(",
"not",
"self",
".",
"_tsk_file_system",
"or",
"not",
"hasattr",
"(",
"self",
... | Retrieves the file system type.
Returns:
pytsk3.TSK_FS_TYPE_ENUM: file system type. | [
"Retrieves",
"the",
"file",
"system",
"type",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L147-L162 | train | 208,238 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | TSKFileSystem.GetTSKFileByPathSpec | def GetTSKFileByPathSpec(self, path_spec):
"""Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location.
"""
# Opening a file by inode number is faster than opening a file
# by location.
inode = getattr(path_spec, 'inode', None)
location = getattr(path_spec, 'location', None)
if inode is not None:
tsk_file = self._tsk_file_system.open_meta(inode=inode)
elif location is not None:
tsk_file = self._tsk_file_system.open(location)
else:
raise errors.PathSpecError(
'Path specification missing inode and location.')
return tsk_file | python | def GetTSKFileByPathSpec(self, path_spec):
"""Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location.
"""
# Opening a file by inode number is faster than opening a file
# by location.
inode = getattr(path_spec, 'inode', None)
location = getattr(path_spec, 'location', None)
if inode is not None:
tsk_file = self._tsk_file_system.open_meta(inode=inode)
elif location is not None:
tsk_file = self._tsk_file_system.open(location)
else:
raise errors.PathSpecError(
'Path specification missing inode and location.')
return tsk_file | [
"def",
"GetTSKFileByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"# Opening a file by inode number is faster than opening a file",
"# by location.",
"inode",
"=",
"getattr",
"(",
"path_spec",
",",
"'inode'",
",",
"None",
")",
"location",
"=",
"getattr",
"(",
"p... | Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location. | [
"Retrieves",
"the",
"SleuthKit",
"file",
"object",
"for",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L199-L224 | train | 208,239 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | TSKFileSystem.IsHFS | def IsHFS(self):
"""Determines if the file system is HFS, HFS+ or HFSX.
Returns:
bool: True if the file system is HFS.
"""
tsk_fs_type = self.GetFsType()
return tsk_fs_type in [
pytsk3.TSK_FS_TYPE_HFS, pytsk3.TSK_FS_TYPE_HFS_DETECT] | python | def IsHFS(self):
"""Determines if the file system is HFS, HFS+ or HFSX.
Returns:
bool: True if the file system is HFS.
"""
tsk_fs_type = self.GetFsType()
return tsk_fs_type in [
pytsk3.TSK_FS_TYPE_HFS, pytsk3.TSK_FS_TYPE_HFS_DETECT] | [
"def",
"IsHFS",
"(",
"self",
")",
":",
"tsk_fs_type",
"=",
"self",
".",
"GetFsType",
"(",
")",
"return",
"tsk_fs_type",
"in",
"[",
"pytsk3",
".",
"TSK_FS_TYPE_HFS",
",",
"pytsk3",
".",
"TSK_FS_TYPE_HFS_DETECT",
"]"
] | Determines if the file system is HFS, HFS+ or HFSX.
Returns:
bool: True if the file system is HFS. | [
"Determines",
"if",
"the",
"file",
"system",
"is",
"HFS",
"HFS",
"+",
"or",
"HFSX",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L226-L234 | train | 208,240 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | TSKFileSystem.IsNTFS | def IsNTFS(self):
"""Determines if the file system is NTFS.
Returns:
bool: True if the file system is NTFS.
"""
tsk_fs_type = self.GetFsType()
return tsk_fs_type in [
pytsk3.TSK_FS_TYPE_NTFS, pytsk3.TSK_FS_TYPE_NTFS_DETECT] | python | def IsNTFS(self):
"""Determines if the file system is NTFS.
Returns:
bool: True if the file system is NTFS.
"""
tsk_fs_type = self.GetFsType()
return tsk_fs_type in [
pytsk3.TSK_FS_TYPE_NTFS, pytsk3.TSK_FS_TYPE_NTFS_DETECT] | [
"def",
"IsNTFS",
"(",
"self",
")",
":",
"tsk_fs_type",
"=",
"self",
".",
"GetFsType",
"(",
")",
"return",
"tsk_fs_type",
"in",
"[",
"pytsk3",
".",
"TSK_FS_TYPE_NTFS",
",",
"pytsk3",
".",
"TSK_FS_TYPE_NTFS_DETECT",
"]"
] | Determines if the file system is NTFS.
Returns:
bool: True if the file system is NTFS. | [
"Determines",
"if",
"the",
"file",
"system",
"is",
"NTFS",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L236-L244 | train | 208,241 |
log2timeline/dfvfs | dfvfs/lib/sqlite_database.py | SQLiteDatabaseFile.Close | def Close(self):
"""Closes the database file object.
Raises:
IOError: if the close failed.
OSError: if the close failed.
"""
if self._connection:
self._cursor = None
self._connection.close()
self._connection = None
# TODO: move this to a central temp file manager and have it track errors.
# https://github.com/log2timeline/dfvfs/issues/92
try:
os.remove(self._temp_file_path)
except (IOError, OSError):
pass
self._temp_file_path = '' | python | def Close(self):
"""Closes the database file object.
Raises:
IOError: if the close failed.
OSError: if the close failed.
"""
if self._connection:
self._cursor = None
self._connection.close()
self._connection = None
# TODO: move this to a central temp file manager and have it track errors.
# https://github.com/log2timeline/dfvfs/issues/92
try:
os.remove(self._temp_file_path)
except (IOError, OSError):
pass
self._temp_file_path = '' | [
"def",
"Close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_cursor",
"=",
"None",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"self",
".",
"_connection",
"=",
"None",
"# TODO: move this to a central temp file manager an... | Closes the database file object.
Raises:
IOError: if the close failed.
OSError: if the close failed. | [
"Closes",
"the",
"database",
"file",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L40-L59 | train | 208,242 |
log2timeline/dfvfs | dfvfs/lib/sqlite_database.py | SQLiteDatabaseFile.HasColumn | def HasColumn(self, table_name, column_name):
"""Determines if a specific column exists.
Args:
table_name (str): name of the table.
column_name (str): name of the column.
Returns:
bool: True if the column exists.
Raises:
IOError: if the database file is not opened.
OSError: if the database file is not opened.
"""
if not self._connection:
raise IOError('Not opened.')
if not column_name:
return False
table_name = table_name.lower()
column_names = self._column_names_per_table.get(table_name, None)
if column_names is None:
column_names = []
self._cursor.execute(self._HAS_COLUMN_QUERY.format(table_name))
for row in self._cursor.fetchall():
if not row[1]:
continue
row_column_name = row[1]
if isinstance(row_column_name, bytes):
row_column_name = row_column_name.decode('utf-8')
column_names.append(row_column_name.lower())
self._column_names_per_table[table_name] = column_names
column_name = column_name.lower()
return column_name in column_names | python | def HasColumn(self, table_name, column_name):
"""Determines if a specific column exists.
Args:
table_name (str): name of the table.
column_name (str): name of the column.
Returns:
bool: True if the column exists.
Raises:
IOError: if the database file is not opened.
OSError: if the database file is not opened.
"""
if not self._connection:
raise IOError('Not opened.')
if not column_name:
return False
table_name = table_name.lower()
column_names = self._column_names_per_table.get(table_name, None)
if column_names is None:
column_names = []
self._cursor.execute(self._HAS_COLUMN_QUERY.format(table_name))
for row in self._cursor.fetchall():
if not row[1]:
continue
row_column_name = row[1]
if isinstance(row_column_name, bytes):
row_column_name = row_column_name.decode('utf-8')
column_names.append(row_column_name.lower())
self._column_names_per_table[table_name] = column_names
column_name = column_name.lower()
return column_name in column_names | [
"def",
"HasColumn",
"(",
"self",
",",
"table_name",
",",
"column_name",
")",
":",
"if",
"not",
"self",
".",
"_connection",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"if",
"not",
"column_name",
":",
"return",
"False",
"table_name",
"=",
"table_name"... | Determines if a specific column exists.
Args:
table_name (str): name of the table.
column_name (str): name of the column.
Returns:
bool: True if the column exists.
Raises:
IOError: if the database file is not opened.
OSError: if the database file is not opened. | [
"Determines",
"if",
"a",
"specific",
"column",
"exists",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L95-L134 | train | 208,243 |
log2timeline/dfvfs | dfvfs/lib/sqlite_database.py | SQLiteDatabaseFile.Open | def Open(self, file_object):
"""Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid.
"""
if not file_object:
raise ValueError('Missing file-like object.')
# Since pysqlite3 does not provide an exclusive read-only mode and
# cannot interact with a file-like object directly we make a temporary
# copy. Before making a copy we check the header signature.
file_object.seek(0, os.SEEK_SET)
data = file_object.read(len(self._HEADER_SIGNATURE))
if data != self._HEADER_SIGNATURE:
file_object.close()
raise IOError('Unsupported SQLite database signature.')
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
self._temp_file_path = temp_file.name
while data:
temp_file.write(data)
data = file_object.read(self._COPY_BUFFER_SIZE)
self._connection = sqlite3.connect(self._temp_file_path)
self._connection.text_factory = bytes
self._cursor = self._connection.cursor() | python | def Open(self, file_object):
"""Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid.
"""
if not file_object:
raise ValueError('Missing file-like object.')
# Since pysqlite3 does not provide an exclusive read-only mode and
# cannot interact with a file-like object directly we make a temporary
# copy. Before making a copy we check the header signature.
file_object.seek(0, os.SEEK_SET)
data = file_object.read(len(self._HEADER_SIGNATURE))
if data != self._HEADER_SIGNATURE:
file_object.close()
raise IOError('Unsupported SQLite database signature.')
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
self._temp_file_path = temp_file.name
while data:
temp_file.write(data)
data = file_object.read(self._COPY_BUFFER_SIZE)
self._connection = sqlite3.connect(self._temp_file_path)
self._connection.text_factory = bytes
self._cursor = self._connection.cursor() | [
"def",
"Open",
"(",
"self",
",",
"file_object",
")",
":",
"if",
"not",
"file_object",
":",
"raise",
"ValueError",
"(",
"'Missing file-like object.'",
")",
"# Since pysqlite3 does not provide an exclusive read-only mode and",
"# cannot interact with a file-like object directly we ... | Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid. | [
"Opens",
"the",
"database",
"file",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L172-L205 | train | 208,244 |
log2timeline/dfvfs | dfvfs/lib/sqlite_database.py | SQLiteDatabaseFile.Query | def Query(self, query, parameters=None):
"""Queries the database file.
Args:
query (str): SQL query.
parameters (Optional[dict|tuple]): query parameters.
Returns:
list[sqlite3.Row]: rows resulting from the query.
"""
# TODO: catch Warning and return None.
# Note that we cannot pass parameters as a keyword argument here.
# A parameters value of None is not supported.
if parameters:
self._cursor.execute(query, parameters)
else:
self._cursor.execute(query)
return self._cursor.fetchall() | python | def Query(self, query, parameters=None):
"""Queries the database file.
Args:
query (str): SQL query.
parameters (Optional[dict|tuple]): query parameters.
Returns:
list[sqlite3.Row]: rows resulting from the query.
"""
# TODO: catch Warning and return None.
# Note that we cannot pass parameters as a keyword argument here.
# A parameters value of None is not supported.
if parameters:
self._cursor.execute(query, parameters)
else:
self._cursor.execute(query)
return self._cursor.fetchall() | [
"def",
"Query",
"(",
"self",
",",
"query",
",",
"parameters",
"=",
"None",
")",
":",
"# TODO: catch Warning and return None.",
"# Note that we cannot pass parameters as a keyword argument here.",
"# A parameters value of None is not supported.",
"if",
"parameters",
":",
"self",
... | Queries the database file.
Args:
query (str): SQL query.
parameters (Optional[dict|tuple]): query parameters.
Returns:
list[sqlite3.Row]: rows resulting from the query. | [
"Queries",
"the",
"database",
"file",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L207-L225 | train | 208,245 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context._GetFileSystemCacheIdentifier | def _GetFileSystemCacheIdentifier(self, path_spec):
"""Determines the file system cache identifier for the path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
str: identifier of the VFS object.
"""
string_parts = []
string_parts.append(getattr(path_spec.parent, 'comparable', ''))
string_parts.append('type: {0:s}'.format(path_spec.type_indicator))
return ''.join(string_parts) | python | def _GetFileSystemCacheIdentifier(self, path_spec):
"""Determines the file system cache identifier for the path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
str: identifier of the VFS object.
"""
string_parts = []
string_parts.append(getattr(path_spec.parent, 'comparable', ''))
string_parts.append('type: {0:s}'.format(path_spec.type_indicator))
return ''.join(string_parts) | [
"def",
"_GetFileSystemCacheIdentifier",
"(",
"self",
",",
"path_spec",
")",
":",
"string_parts",
"=",
"[",
"]",
"string_parts",
".",
"append",
"(",
"getattr",
"(",
"path_spec",
".",
"parent",
",",
"'comparable'",
",",
"''",
")",
")",
"string_parts",
".",
"ap... | Determines the file system cache identifier for the path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
str: identifier of the VFS object. | [
"Determines",
"the",
"file",
"system",
"cache",
"identifier",
"for",
"the",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L29-L43 | train | 208,246 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.CacheFileObject | def CacheFileObject(self, path_spec, file_object):
"""Caches a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_object (FileIO): file-like object.
"""
self._file_object_cache.CacheObject(path_spec.comparable, file_object) | python | def CacheFileObject(self, path_spec, file_object):
"""Caches a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_object (FileIO): file-like object.
"""
self._file_object_cache.CacheObject(path_spec.comparable, file_object) | [
"def",
"CacheFileObject",
"(",
"self",
",",
"path_spec",
",",
"file_object",
")",
":",
"self",
".",
"_file_object_cache",
".",
"CacheObject",
"(",
"path_spec",
".",
"comparable",
",",
"file_object",
")"
] | Caches a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_object (FileIO): file-like object. | [
"Caches",
"a",
"file",
"-",
"like",
"object",
"based",
"on",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L45-L52 | train | 208,247 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.CacheFileSystem | def CacheFileSystem(self, path_spec, file_system):
"""Caches a file system object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_system (FileSystem): file system object.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
self._file_system_cache.CacheObject(identifier, file_system) | python | def CacheFileSystem(self, path_spec, file_system):
"""Caches a file system object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_system (FileSystem): file system object.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
self._file_system_cache.CacheObject(identifier, file_system) | [
"def",
"CacheFileSystem",
"(",
"self",
",",
"path_spec",
",",
"file_system",
")",
":",
"identifier",
"=",
"self",
".",
"_GetFileSystemCacheIdentifier",
"(",
"path_spec",
")",
"self",
".",
"_file_system_cache",
".",
"CacheObject",
"(",
"identifier",
",",
"file_syst... | Caches a file system object based on a path specification.
Args:
path_spec (PathSpec): path specification.
file_system (FileSystem): file system object. | [
"Caches",
"a",
"file",
"system",
"object",
"based",
"on",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L54-L62 | train | 208,248 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.ForceRemoveFileObject | def ForceRemoveFileObject(self, path_spec):
"""Forces the removal of a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file-like object was cached.
"""
cache_value = self._file_object_cache.GetCacheValue(path_spec.comparable)
if not cache_value:
return False
while not cache_value.IsDereferenced():
cache_value.vfs_object.close()
return True | python | def ForceRemoveFileObject(self, path_spec):
"""Forces the removal of a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file-like object was cached.
"""
cache_value = self._file_object_cache.GetCacheValue(path_spec.comparable)
if not cache_value:
return False
while not cache_value.IsDereferenced():
cache_value.vfs_object.close()
return True | [
"def",
"ForceRemoveFileObject",
"(",
"self",
",",
"path_spec",
")",
":",
"cache_value",
"=",
"self",
".",
"_file_object_cache",
".",
"GetCacheValue",
"(",
"path_spec",
".",
"comparable",
")",
"if",
"not",
"cache_value",
":",
"return",
"False",
"while",
"not",
... | Forces the removal of a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file-like object was cached. | [
"Forces",
"the",
"removal",
"of",
"a",
"file",
"-",
"like",
"object",
"based",
"on",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L69-L85 | train | 208,249 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.GetFileObjectReferenceCount | def GetFileObjectReferenceCount(self, path_spec):
"""Retrieves the reference count of a cached file-like object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file-like object for
the corresponding path specification cached.
"""
cache_value = self._file_object_cache.GetCacheValue(path_spec.comparable)
if not cache_value:
return None
return cache_value.reference_count | python | def GetFileObjectReferenceCount(self, path_spec):
"""Retrieves the reference count of a cached file-like object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file-like object for
the corresponding path specification cached.
"""
cache_value = self._file_object_cache.GetCacheValue(path_spec.comparable)
if not cache_value:
return None
return cache_value.reference_count | [
"def",
"GetFileObjectReferenceCount",
"(",
"self",
",",
"path_spec",
")",
":",
"cache_value",
"=",
"self",
".",
"_file_object_cache",
".",
"GetCacheValue",
"(",
"path_spec",
".",
"comparable",
")",
"if",
"not",
"cache_value",
":",
"return",
"None",
"return",
"ca... | Retrieves the reference count of a cached file-like object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file-like object for
the corresponding path specification cached. | [
"Retrieves",
"the",
"reference",
"count",
"of",
"a",
"cached",
"file",
"-",
"like",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L98-L112 | train | 208,250 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.GetFileSystem | def GetFileSystem(self, path_spec):
"""Retrieves a file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileSystem: a file system object or None if not cached.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
return self._file_system_cache.GetObject(identifier) | python | def GetFileSystem(self, path_spec):
"""Retrieves a file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileSystem: a file system object or None if not cached.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
return self._file_system_cache.GetObject(identifier) | [
"def",
"GetFileSystem",
"(",
"self",
",",
"path_spec",
")",
":",
"identifier",
"=",
"self",
".",
"_GetFileSystemCacheIdentifier",
"(",
"path_spec",
")",
"return",
"self",
".",
"_file_system_cache",
".",
"GetObject",
"(",
"identifier",
")"
] | Retrieves a file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileSystem: a file system object or None if not cached. | [
"Retrieves",
"a",
"file",
"system",
"object",
"defined",
"by",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L114-L124 | train | 208,251 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.GetFileSystemReferenceCount | def GetFileSystemReferenceCount(self, path_spec):
"""Retrieves the reference count of a cached file system object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file system object for
the corresponding path specification cached.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
cache_value = self._file_system_cache.GetCacheValue(identifier)
if not cache_value:
return None
return cache_value.reference_count | python | def GetFileSystemReferenceCount(self, path_spec):
"""Retrieves the reference count of a cached file system object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file system object for
the corresponding path specification cached.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
cache_value = self._file_system_cache.GetCacheValue(identifier)
if not cache_value:
return None
return cache_value.reference_count | [
"def",
"GetFileSystemReferenceCount",
"(",
"self",
",",
"path_spec",
")",
":",
"identifier",
"=",
"self",
".",
"_GetFileSystemCacheIdentifier",
"(",
"path_spec",
")",
"cache_value",
"=",
"self",
".",
"_file_system_cache",
".",
"GetCacheValue",
"(",
"identifier",
")"... | Retrieves the reference count of a cached file system object.
Args:
path_spec (PathSpec): path specification.
Returns:
int: reference count or None if there is no file system object for
the corresponding path specification cached. | [
"Retrieves",
"the",
"reference",
"count",
"of",
"a",
"cached",
"file",
"system",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L126-L141 | train | 208,252 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.GrabFileSystem | def GrabFileSystem(self, path_spec):
"""Grabs a cached file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
self._file_system_cache.GrabObject(identifier) | python | def GrabFileSystem(self, path_spec):
"""Grabs a cached file system object defined by path specification.
Args:
path_spec (PathSpec): path specification.
"""
identifier = self._GetFileSystemCacheIdentifier(path_spec)
self._file_system_cache.GrabObject(identifier) | [
"def",
"GrabFileSystem",
"(",
"self",
",",
"path_spec",
")",
":",
"identifier",
"=",
"self",
".",
"_GetFileSystemCacheIdentifier",
"(",
"path_spec",
")",
"self",
".",
"_file_system_cache",
".",
"GrabObject",
"(",
"identifier",
")"
] | Grabs a cached file system object defined by path specification.
Args:
path_spec (PathSpec): path specification. | [
"Grabs",
"a",
"cached",
"file",
"system",
"object",
"defined",
"by",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L151-L158 | train | 208,253 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.ReleaseFileObject | def ReleaseFileObject(self, file_object):
"""Releases a cached file-like object.
Args:
file_object (FileIO): file-like object.
Returns:
bool: True if the file-like object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file-like object is not cached or an inconsistency
is detected in the cache.
"""
identifier, cache_value = self._file_object_cache.GetCacheValueByObject(
file_object)
if not identifier:
raise RuntimeError('Object not cached.')
if not cache_value:
raise RuntimeError('Invalid cache value.')
self._file_object_cache.ReleaseObject(identifier)
result = cache_value.IsDereferenced()
if result:
self._file_object_cache.RemoveObject(identifier)
return result | python | def ReleaseFileObject(self, file_object):
"""Releases a cached file-like object.
Args:
file_object (FileIO): file-like object.
Returns:
bool: True if the file-like object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file-like object is not cached or an inconsistency
is detected in the cache.
"""
identifier, cache_value = self._file_object_cache.GetCacheValueByObject(
file_object)
if not identifier:
raise RuntimeError('Object not cached.')
if not cache_value:
raise RuntimeError('Invalid cache value.')
self._file_object_cache.ReleaseObject(identifier)
result = cache_value.IsDereferenced()
if result:
self._file_object_cache.RemoveObject(identifier)
return result | [
"def",
"ReleaseFileObject",
"(",
"self",
",",
"file_object",
")",
":",
"identifier",
",",
"cache_value",
"=",
"self",
".",
"_file_object_cache",
".",
"GetCacheValueByObject",
"(",
"file_object",
")",
"if",
"not",
"identifier",
":",
"raise",
"RuntimeError",
"(",
... | Releases a cached file-like object.
Args:
file_object (FileIO): file-like object.
Returns:
bool: True if the file-like object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file-like object is not cached or an inconsistency
is detected in the cache. | [
"Releases",
"a",
"cached",
"file",
"-",
"like",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L160-L189 | train | 208,254 |
log2timeline/dfvfs | dfvfs/resolver/context.py | Context.ReleaseFileSystem | def ReleaseFileSystem(self, file_system):
"""Releases a cached file system object.
Args:
file_system (FileSystem): file system object.
Returns:
bool: True if the file system object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file system object is not cached or an inconsistency
is detected in the cache.
"""
identifier, cache_value = self._file_system_cache.GetCacheValueByObject(
file_system)
if not identifier:
raise RuntimeError('Object not cached.')
if not cache_value:
raise RuntimeError('Invalid cache value.')
self._file_system_cache.ReleaseObject(identifier)
result = cache_value.IsDereferenced()
if result:
self._file_system_cache.RemoveObject(identifier)
return result | python | def ReleaseFileSystem(self, file_system):
"""Releases a cached file system object.
Args:
file_system (FileSystem): file system object.
Returns:
bool: True if the file system object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file system object is not cached or an inconsistency
is detected in the cache.
"""
identifier, cache_value = self._file_system_cache.GetCacheValueByObject(
file_system)
if not identifier:
raise RuntimeError('Object not cached.')
if not cache_value:
raise RuntimeError('Invalid cache value.')
self._file_system_cache.ReleaseObject(identifier)
result = cache_value.IsDereferenced()
if result:
self._file_system_cache.RemoveObject(identifier)
return result | [
"def",
"ReleaseFileSystem",
"(",
"self",
",",
"file_system",
")",
":",
"identifier",
",",
"cache_value",
"=",
"self",
".",
"_file_system_cache",
".",
"GetCacheValueByObject",
"(",
"file_system",
")",
"if",
"not",
"identifier",
":",
"raise",
"RuntimeError",
"(",
... | Releases a cached file system object.
Args:
file_system (FileSystem): file system object.
Returns:
bool: True if the file system object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file system object is not cached or an inconsistency
is detected in the cache. | [
"Releases",
"a",
"cached",
"file",
"system",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L191-L220 | train | 208,255 |
log2timeline/dfvfs | dfvfs/file_io/encoded_stream_io.py | EncodedStream._GetDecodedStreamSize | def _GetDecodedStreamSize(self):
"""Retrieves the decoded stream size.
Returns:
int: decoded stream size.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b''
encoded_data_offset = 0
encoded_data_size = self._file_object.get_size()
decoded_stream_size = 0
while encoded_data_offset < encoded_data_size:
read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
if read_count == 0:
break
encoded_data_offset += read_count
decoded_stream_size += self._decoded_data_size
return decoded_stream_size | python | def _GetDecodedStreamSize(self):
"""Retrieves the decoded stream size.
Returns:
int: decoded stream size.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b''
encoded_data_offset = 0
encoded_data_size = self._file_object.get_size()
decoded_stream_size = 0
while encoded_data_offset < encoded_data_size:
read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
if read_count == 0:
break
encoded_data_offset += read_count
decoded_stream_size += self._decoded_data_size
return decoded_stream_size | [
"def",
"_GetDecodedStreamSize",
"(",
"self",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decoder",
"=",
"self",
".",
"_GetDecoder",
"(",
")",
"self",
".",
"_decoded_data",
"=",
"b''",
"e... | Retrieves the decoded stream size.
Returns:
int: decoded stream size. | [
"Retrieves",
"the",
"decoded",
"stream",
"size",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/encoded_stream_io.py#L75-L98 | train | 208,256 |
log2timeline/dfvfs | dfvfs/file_io/encoded_stream_io.py | EncodedStream._AlignDecodedDataOffset | def _AlignDecodedDataOffset(self, decoded_data_offset):
"""Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b''
encoded_data_offset = 0
encoded_data_size = self._file_object.get_size()
while encoded_data_offset < encoded_data_size:
read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
if read_count == 0:
break
encoded_data_offset += read_count
if decoded_data_offset < self._decoded_data_size:
self._decoded_data_offset = decoded_data_offset
break
decoded_data_offset -= self._decoded_data_size | python | def _AlignDecodedDataOffset(self, decoded_data_offset):
"""Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b''
encoded_data_offset = 0
encoded_data_size = self._file_object.get_size()
while encoded_data_offset < encoded_data_size:
read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
if read_count == 0:
break
encoded_data_offset += read_count
if decoded_data_offset < self._decoded_data_size:
self._decoded_data_offset = decoded_data_offset
break
decoded_data_offset -= self._decoded_data_size | [
"def",
"_AlignDecodedDataOffset",
"(",
"self",
",",
"decoded_data_offset",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decoder",
"=",
"self",
".",
"_GetDecoder",
"(",
")",
"self",
".",
"_d... | Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset. | [
"Aligns",
"the",
"encoded",
"file",
"with",
"the",
"decoded",
"data",
"offset",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/encoded_stream_io.py#L131-L156 | train | 208,257 |
log2timeline/dfvfs | dfvfs/file_io/encoded_stream_io.py | EncodedStream._ReadEncodedData | def _ReadEncodedData(self, read_size):
"""Reads encoded data from the file-like object.
Args:
read_size (int): number of bytes of encoded data to read.
Returns:
int: number of bytes of encoded data read.
"""
encoded_data = self._file_object.read(read_size)
read_count = len(encoded_data)
self._encoded_data = b''.join([self._encoded_data, encoded_data])
self._decoded_data, self._encoded_data = (
self._decoder.Decode(self._encoded_data))
self._decoded_data_size = len(self._decoded_data)
return read_count | python | def _ReadEncodedData(self, read_size):
"""Reads encoded data from the file-like object.
Args:
read_size (int): number of bytes of encoded data to read.
Returns:
int: number of bytes of encoded data read.
"""
encoded_data = self._file_object.read(read_size)
read_count = len(encoded_data)
self._encoded_data = b''.join([self._encoded_data, encoded_data])
self._decoded_data, self._encoded_data = (
self._decoder.Decode(self._encoded_data))
self._decoded_data_size = len(self._decoded_data)
return read_count | [
"def",
"_ReadEncodedData",
"(",
"self",
",",
"read_size",
")",
":",
"encoded_data",
"=",
"self",
".",
"_file_object",
".",
"read",
"(",
"read_size",
")",
"read_count",
"=",
"len",
"(",
"encoded_data",
")",
"self",
".",
"_encoded_data",
"=",
"b''",
".",
"jo... | Reads encoded data from the file-like object.
Args:
read_size (int): number of bytes of encoded data to read.
Returns:
int: number of bytes of encoded data read. | [
"Reads",
"encoded",
"data",
"from",
"the",
"file",
"-",
"like",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/encoded_stream_io.py#L158-L178 | train | 208,258 |
log2timeline/dfvfs | dfvfs/file_io/encoded_stream_io.py | EncodedStream.SetDecodedStreamSize | def SetDecodedStreamSize(self, decoded_stream_size):
"""Sets the decoded stream size.
This function is used to set the decoded stream size if it can be
determined separately.
Args:
decoded_stream_size (int): size of the decoded stream in bytes.
Raises:
IOError: if the file-like object is already open.
OSError: if the file-like object is already open.
ValueError: if the decoded stream size is invalid.
"""
if self._is_open:
raise IOError('Already open.')
if decoded_stream_size < 0:
raise ValueError((
'Invalid decoded stream size: {0:d} value out of '
'bounds.').format(decoded_stream_size))
self._decoded_stream_size = decoded_stream_size | python | def SetDecodedStreamSize(self, decoded_stream_size):
"""Sets the decoded stream size.
This function is used to set the decoded stream size if it can be
determined separately.
Args:
decoded_stream_size (int): size of the decoded stream in bytes.
Raises:
IOError: if the file-like object is already open.
OSError: if the file-like object is already open.
ValueError: if the decoded stream size is invalid.
"""
if self._is_open:
raise IOError('Already open.')
if decoded_stream_size < 0:
raise ValueError((
'Invalid decoded stream size: {0:d} value out of '
'bounds.').format(decoded_stream_size))
self._decoded_stream_size = decoded_stream_size | [
"def",
"SetDecodedStreamSize",
"(",
"self",
",",
"decoded_stream_size",
")",
":",
"if",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Already open.'",
")",
"if",
"decoded_stream_size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid decoded ... | Sets the decoded stream size.
This function is used to set the decoded stream size if it can be
determined separately.
Args:
decoded_stream_size (int): size of the decoded stream in bytes.
Raises:
IOError: if the file-like object is already open.
OSError: if the file-like object is already open.
ValueError: if the decoded stream size is invalid. | [
"Sets",
"the",
"decoded",
"stream",
"size",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/encoded_stream_io.py#L180-L202 | train | 208,259 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | Volume._AddAttribute | def _AddAttribute(self, attribute):
"""Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier.
"""
if attribute.identifier in self._attributes:
raise KeyError((
'Volume attribute object already set for volume attribute '
'identifier: {0:s}.').format(attribute.identifier))
self._attributes[attribute.identifier] = attribute | python | def _AddAttribute(self, attribute):
"""Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier.
"""
if attribute.identifier in self._attributes:
raise KeyError((
'Volume attribute object already set for volume attribute '
'identifier: {0:s}.').format(attribute.identifier))
self._attributes[attribute.identifier] = attribute | [
"def",
"_AddAttribute",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"attribute",
".",
"identifier",
"in",
"self",
".",
"_attributes",
":",
"raise",
"KeyError",
"(",
"(",
"'Volume attribute object already set for volume attribute '",
"'identifier: {0:s}.'",
")",
"."... | Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier. | [
"Adds",
"an",
"attribute",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L59-L74 | train | 208,260 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | Volume.GetAttribute | def GetAttribute(self, identifier):
"""Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if identifier not in self._attributes:
return None
return self._attributes[identifier] | python | def GetAttribute(self, identifier):
"""Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if identifier not in self._attributes:
return None
return self._attributes[identifier] | [
"def",
"GetAttribute",
"(",
"self",
",",
"identifier",
")",
":",
"if",
"not",
"self",
".",
"_is_parsed",
":",
"self",
".",
"_Parse",
"(",
")",
"self",
".",
"_is_parsed",
"=",
"True",
"if",
"identifier",
"not",
"in",
"self",
".",
"_attributes",
":",
"re... | Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available. | [
"Retrieves",
"a",
"specific",
"attribute",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L116-L132 | train | 208,261 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | VolumeSystem._AddVolume | def _AddVolume(self, volume):
"""Adds a volume.
Args:
volume (Volume): a volume.
Raises:
KeyError: if volume is already set for the corresponding volume
identifier.
"""
if volume.identifier in self._volumes:
raise KeyError(
'Volume object already set for volume identifier: {0:s}'.format(
volume.identifier))
self._volumes[volume.identifier] = volume
self._volume_identifiers.append(volume.identifier) | python | def _AddVolume(self, volume):
"""Adds a volume.
Args:
volume (Volume): a volume.
Raises:
KeyError: if volume is already set for the corresponding volume
identifier.
"""
if volume.identifier in self._volumes:
raise KeyError(
'Volume object already set for volume identifier: {0:s}'.format(
volume.identifier))
self._volumes[volume.identifier] = volume
self._volume_identifiers.append(volume.identifier) | [
"def",
"_AddVolume",
"(",
"self",
",",
"volume",
")",
":",
"if",
"volume",
".",
"identifier",
"in",
"self",
".",
"_volumes",
":",
"raise",
"KeyError",
"(",
"'Volume object already set for volume identifier: {0:s}'",
".",
"format",
"(",
"volume",
".",
"identifier",... | Adds a volume.
Args:
volume (Volume): a volume.
Raises:
KeyError: if volume is already set for the corresponding volume
identifier. | [
"Adds",
"a",
"volume",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L154-L170 | train | 208,262 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | VolumeSystem.GetSectionByIndex | def GetSectionByIndex(self, section_index):
"""Retrieves a specific section based on the index.
Args:
section_index (int): index of the section.
Returns:
VolumeExtent: a volume extent or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if section_index < 0 or section_index >= len(self._sections):
return None
return self._sections[section_index] | python | def GetSectionByIndex(self, section_index):
"""Retrieves a specific section based on the index.
Args:
section_index (int): index of the section.
Returns:
VolumeExtent: a volume extent or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if section_index < 0 or section_index >= len(self._sections):
return None
return self._sections[section_index] | [
"def",
"GetSectionByIndex",
"(",
"self",
",",
"section_index",
")",
":",
"if",
"not",
"self",
".",
"_is_parsed",
":",
"self",
".",
"_Parse",
"(",
")",
"self",
".",
"_is_parsed",
"=",
"True",
"if",
"section_index",
"<",
"0",
"or",
"section_index",
">=",
"... | Retrieves a specific section based on the index.
Args:
section_index (int): index of the section.
Returns:
VolumeExtent: a volume extent or None if not available. | [
"Retrieves",
"a",
"specific",
"section",
"based",
"on",
"the",
"index",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L212-L228 | train | 208,263 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | VolumeSystem.GetVolumeByIdentifier | def GetVolumeByIdentifier(self, volume_identifier):
"""Retrieves a specific volume based on the identifier.
Args:
volume_identifier (str): identifier of the volume within
the volume system.
Returns:
Volume: a volume.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
return self._volumes[volume_identifier] | python | def GetVolumeByIdentifier(self, volume_identifier):
"""Retrieves a specific volume based on the identifier.
Args:
volume_identifier (str): identifier of the volume within
the volume system.
Returns:
Volume: a volume.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
return self._volumes[volume_identifier] | [
"def",
"GetVolumeByIdentifier",
"(",
"self",
",",
"volume_identifier",
")",
":",
"if",
"not",
"self",
".",
"_is_parsed",
":",
"self",
".",
"_Parse",
"(",
")",
"self",
".",
"_is_parsed",
"=",
"True",
"return",
"self",
".",
"_volumes",
"[",
"volume_identifier"... | Retrieves a specific volume based on the identifier.
Args:
volume_identifier (str): identifier of the volume within
the volume system.
Returns:
Volume: a volume. | [
"Retrieves",
"a",
"specific",
"volume",
"based",
"on",
"the",
"identifier",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L230-L244 | train | 208,264 |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | VolumeSystem.GetVolumeByIndex | def GetVolumeByIndex(self, volume_index):
"""Retrieves a specific volume based on the index.
Args:
volume_index (int): index of the volume.
Returns:
Volume: a volume or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if volume_index < 0 or volume_index >= len(self._volume_identifiers):
return None
volume_identifier = self._volume_identifiers[volume_index]
return self._volumes[volume_identifier] | python | def GetVolumeByIndex(self, volume_index):
"""Retrieves a specific volume based on the index.
Args:
volume_index (int): index of the volume.
Returns:
Volume: a volume or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if volume_index < 0 or volume_index >= len(self._volume_identifiers):
return None
volume_identifier = self._volume_identifiers[volume_index]
return self._volumes[volume_identifier] | [
"def",
"GetVolumeByIndex",
"(",
"self",
",",
"volume_index",
")",
":",
"if",
"not",
"self",
".",
"_is_parsed",
":",
"self",
".",
"_Parse",
"(",
")",
"self",
".",
"_is_parsed",
"=",
"True",
"if",
"volume_index",
"<",
"0",
"or",
"volume_index",
">=",
"len"... | Retrieves a specific volume based on the index.
Args:
volume_index (int): index of the volume.
Returns:
Volume: a volume or None if not available. | [
"Retrieves",
"a",
"specific",
"volume",
"based",
"on",
"the",
"index",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L246-L263 | train | 208,265 |
log2timeline/dfvfs | dfvfs/file_io/compressed_stream_io.py | CompressedStream._GetUncompressedStreamSize | def _GetUncompressedStreamSize(self):
"""Retrieves the uncompressed stream size.
Returns:
int: uncompressed stream size.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decompressor = self._GetDecompressor()
self._uncompressed_data = b''
compressed_data_offset = 0
compressed_data_size = self._file_object.get_size()
uncompressed_stream_size = 0
while compressed_data_offset < compressed_data_size:
read_count = self._ReadCompressedData(self._COMPRESSED_DATA_BUFFER_SIZE)
if read_count == 0:
break
compressed_data_offset += read_count
uncompressed_stream_size += self._uncompressed_data_size
return uncompressed_stream_size | python | def _GetUncompressedStreamSize(self):
"""Retrieves the uncompressed stream size.
Returns:
int: uncompressed stream size.
"""
self._file_object.seek(0, os.SEEK_SET)
self._decompressor = self._GetDecompressor()
self._uncompressed_data = b''
compressed_data_offset = 0
compressed_data_size = self._file_object.get_size()
uncompressed_stream_size = 0
while compressed_data_offset < compressed_data_size:
read_count = self._ReadCompressedData(self._COMPRESSED_DATA_BUFFER_SIZE)
if read_count == 0:
break
compressed_data_offset += read_count
uncompressed_stream_size += self._uncompressed_data_size
return uncompressed_stream_size | [
"def",
"_GetUncompressedStreamSize",
"(",
"self",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decompressor",
"=",
"self",
".",
"_GetDecompressor",
"(",
")",
"self",
".",
"_uncompressed_data",
... | Retrieves the uncompressed stream size.
Returns:
int: uncompressed stream size. | [
"Retrieves",
"the",
"uncompressed",
"stream",
"size",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/compressed_stream_io.py#L77-L100 | train | 208,266 |
log2timeline/dfvfs | dfvfs/vfs/vshadow_file_system.py | VShadowFileSystem.GetVShadowStoreByPathSpec | def GetVShadowStoreByPathSpec(self, path_spec):
"""Retrieves a VSS store for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyvshadow.store: a VSS store or None if not available.
"""
store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)
if store_index is None:
return None
return self._vshadow_volume.get_store(store_index) | python | def GetVShadowStoreByPathSpec(self, path_spec):
"""Retrieves a VSS store for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyvshadow.store: a VSS store or None if not available.
"""
store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)
if store_index is None:
return None
return self._vshadow_volume.get_store(store_index) | [
"def",
"GetVShadowStoreByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"store_index",
"=",
"vshadow",
".",
"VShadowPathSpecGetStoreIndex",
"(",
"path_spec",
")",
"if",
"store_index",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_vshadow_volum... | Retrieves a VSS store for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyvshadow.store: a VSS store or None if not available. | [
"Retrieves",
"a",
"VSS",
"store",
"for",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/vshadow_file_system.py#L133-L146 | train | 208,267 |
log2timeline/dfvfs | dfvfs/lib/decorators.py | deprecated | def deprecated(function): # pylint: disable=invalid-name
"""Decorator to mark functions or methods as deprecated."""
def IssueDeprecationWarning(*args, **kwargs):
"""Issue a deprecation warning."""
warnings.simplefilter('default', DeprecationWarning)
warnings.warn('Call to deprecated function: {0:s}.'.format(
function.__name__), category=DeprecationWarning, stacklevel=2)
return function(*args, **kwargs)
IssueDeprecationWarning.__name__ = function.__name__
IssueDeprecationWarning.__doc__ = function.__doc__
IssueDeprecationWarning.__dict__.update(function.__dict__)
return IssueDeprecationWarning | python | def deprecated(function): # pylint: disable=invalid-name
"""Decorator to mark functions or methods as deprecated."""
def IssueDeprecationWarning(*args, **kwargs):
"""Issue a deprecation warning."""
warnings.simplefilter('default', DeprecationWarning)
warnings.warn('Call to deprecated function: {0:s}.'.format(
function.__name__), category=DeprecationWarning, stacklevel=2)
return function(*args, **kwargs)
IssueDeprecationWarning.__name__ = function.__name__
IssueDeprecationWarning.__doc__ = function.__doc__
IssueDeprecationWarning.__dict__.update(function.__dict__)
return IssueDeprecationWarning | [
"def",
"deprecated",
"(",
"function",
")",
":",
"# pylint: disable=invalid-name",
"def",
"IssueDeprecationWarning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Issue a deprecation warning.\"\"\"",
"warnings",
".",
"simplefilter",
"(",
"'default'",
",",... | Decorator to mark functions or methods as deprecated. | [
"Decorator",
"to",
"mark",
"functions",
"or",
"methods",
"as",
"deprecated",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/decorators.py#L9-L23 | train | 208,268 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckFileEntryType | def _CheckFileEntryType(self, file_entry):
"""Checks the file entry type find specifications.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if
not or None if no file entry type specification is defined.
"""
if not self._file_entry_types:
return None
return (
self._CheckIsDevice(file_entry) or self._CheckIsDirectory(file_entry) or
self._CheckIsFile(file_entry) or self._CheckIsLink(file_entry) or
self._CheckIsPipe(file_entry) or self._CheckIsSocket(file_entry)) | python | def _CheckFileEntryType(self, file_entry):
"""Checks the file entry type find specifications.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if
not or None if no file entry type specification is defined.
"""
if not self._file_entry_types:
return None
return (
self._CheckIsDevice(file_entry) or self._CheckIsDirectory(file_entry) or
self._CheckIsFile(file_entry) or self._CheckIsLink(file_entry) or
self._CheckIsPipe(file_entry) or self._CheckIsSocket(file_entry)) | [
"def",
"_CheckFileEntryType",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"not",
"self",
".",
"_file_entry_types",
":",
"return",
"None",
"return",
"(",
"self",
".",
"_CheckIsDevice",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsDirectory",
"(",
"... | Checks the file entry type find specifications.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if
not or None if no file entry type specification is defined. | [
"Checks",
"the",
"file",
"entry",
"type",
"find",
"specifications",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L117-L133 | train | 208,269 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsDevice | def _CheckIsDevice(self, file_entry):
"""Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
return False
return file_entry.IsDevice() | python | def _CheckIsDevice(self, file_entry):
"""Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
return False
return file_entry.IsDevice() | [
"def",
"_CheckIsDevice",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_DEVICE",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsDevice",
"(",
")"
] | Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_device",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L149-L160 | train | 208,270 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsDirectory | def _CheckIsDirectory(self, file_entry):
"""Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DIRECTORY not in self._file_entry_types:
return False
return file_entry.IsDirectory() | python | def _CheckIsDirectory(self, file_entry):
"""Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DIRECTORY not in self._file_entry_types:
return False
return file_entry.IsDirectory() | [
"def",
"_CheckIsDirectory",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_DIRECTORY",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsDirectory",
"(",
")"
] | Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_directory",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L162-L173 | train | 208,271 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsFile | def _CheckIsFile(self, file_entry):
"""Checks the is_file find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_FILE not in self._file_entry_types:
return False
return file_entry.IsFile() | python | def _CheckIsFile(self, file_entry):
"""Checks the is_file find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_FILE not in self._file_entry_types:
return False
return file_entry.IsFile() | [
"def",
"_CheckIsFile",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_FILE",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsFile",
"(",
")"
] | Checks the is_file find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_file",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L175-L186 | train | 208,272 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsLink | def _CheckIsLink(self, file_entry):
"""Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types:
return False
return file_entry.IsLink() | python | def _CheckIsLink(self, file_entry):
"""Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types:
return False
return file_entry.IsLink() | [
"def",
"_CheckIsLink",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_LINK",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsLink",
"(",
")"
] | Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_link",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L188-L199 | train | 208,273 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsPipe | def _CheckIsPipe(self, file_entry):
"""Checks the is_pipe find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_PIPE not in self._file_entry_types:
return False
return file_entry.IsPipe() | python | def _CheckIsPipe(self, file_entry):
"""Checks the is_pipe find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_PIPE not in self._file_entry_types:
return False
return file_entry.IsPipe() | [
"def",
"_CheckIsPipe",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_PIPE",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsPipe",
"(",
")"
] | Checks the is_pipe find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_pipe",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L201-L212 | train | 208,274 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckIsSocket | def _CheckIsSocket(self, file_entry):
"""Checks the is_socket find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_SOCKET not in self._file_entry_types:
return False
return file_entry.IsSocket() | python | def _CheckIsSocket(self, file_entry):
"""Checks the is_socket find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_SOCKET not in self._file_entry_types:
return False
return file_entry.IsSocket() | [
"def",
"_CheckIsSocket",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"definitions",
".",
"FILE_ENTRY_TYPE_SOCKET",
"not",
"in",
"self",
".",
"_file_entry_types",
":",
"return",
"False",
"return",
"file_entry",
".",
"IsSocket",
"(",
")"
] | Checks the is_socket find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"is_socket",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L214-L225 | train | 208,275 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec._CheckLocation | def _CheckLocation(self, file_entry, search_depth):
"""Checks the location find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if self._location_segments is None:
return False
if search_depth < 0 or search_depth > self._number_of_location_segments:
return False
# Note that the root has no entry in the location segments and
# no name to match.
if search_depth == 0:
segment_name = ''
else:
segment_name = self._location_segments[search_depth - 1]
if self._is_regex:
if isinstance(segment_name, py2to3.STRING_TYPES):
# Allow '\n' to be matched by '.' and make '\w', '\W', '\b', '\B',
# '\d', '\D', '\s' and '\S' Unicode safe.
flags = re.DOTALL | re.UNICODE
if not self._is_case_sensitive:
flags |= re.IGNORECASE
try:
segment_name = r'^{0:s}$'.format(segment_name)
segment_name = re.compile(segment_name, flags=flags)
except sre_constants.error:
# TODO: set self._location_segments[search_depth - 1] to None ?
return False
self._location_segments[search_depth - 1] = segment_name
elif not self._is_case_sensitive:
segment_name = segment_name.lower()
self._location_segments[search_depth - 1] = segment_name
if search_depth > 0:
if self._is_regex:
if not segment_name.match(file_entry.name): # pylint: disable=no-member
return False
elif self._is_case_sensitive:
if segment_name != file_entry.name:
return False
elif segment_name != file_entry.name.lower():
return False
return True | python | def _CheckLocation(self, file_entry, search_depth):
"""Checks the location find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if self._location_segments is None:
return False
if search_depth < 0 or search_depth > self._number_of_location_segments:
return False
# Note that the root has no entry in the location segments and
# no name to match.
if search_depth == 0:
segment_name = ''
else:
segment_name = self._location_segments[search_depth - 1]
if self._is_regex:
if isinstance(segment_name, py2to3.STRING_TYPES):
# Allow '\n' to be matched by '.' and make '\w', '\W', '\b', '\B',
# '\d', '\D', '\s' and '\S' Unicode safe.
flags = re.DOTALL | re.UNICODE
if not self._is_case_sensitive:
flags |= re.IGNORECASE
try:
segment_name = r'^{0:s}$'.format(segment_name)
segment_name = re.compile(segment_name, flags=flags)
except sre_constants.error:
# TODO: set self._location_segments[search_depth - 1] to None ?
return False
self._location_segments[search_depth - 1] = segment_name
elif not self._is_case_sensitive:
segment_name = segment_name.lower()
self._location_segments[search_depth - 1] = segment_name
if search_depth > 0:
if self._is_regex:
if not segment_name.match(file_entry.name): # pylint: disable=no-member
return False
elif self._is_case_sensitive:
if segment_name != file_entry.name:
return False
elif segment_name != file_entry.name.lower():
return False
return True | [
"def",
"_CheckLocation",
"(",
"self",
",",
"file_entry",
",",
"search_depth",
")",
":",
"if",
"self",
".",
"_location_segments",
"is",
"None",
":",
"return",
"False",
"if",
"search_depth",
"<",
"0",
"or",
"search_depth",
">",
"self",
".",
"_number_of_location_... | Checks the location find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
bool: True if the file entry matches the find specification, False if not. | [
"Checks",
"the",
"location",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L227-L283 | train | 208,276 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec.Matches | def Matches(self, file_entry, search_depth):
"""Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches the find specification, False
otherwise.
bool: True if the location matches, False if not or None if no location
specified.
"""
if self._location_segments is None:
location_match = None
else:
location_match = self._CheckLocation(file_entry, search_depth)
if not location_match:
return False, location_match
if search_depth != self._number_of_location_segments:
return False, location_match
match = self._CheckFileEntryType(file_entry)
if match is not None and not match:
return False, location_match
match = self._CheckIsAllocated(file_entry)
if match is not None and not match:
return False, location_match
return True, location_match | python | def Matches(self, file_entry, search_depth):
"""Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches the find specification, False
otherwise.
bool: True if the location matches, False if not or None if no location
specified.
"""
if self._location_segments is None:
location_match = None
else:
location_match = self._CheckLocation(file_entry, search_depth)
if not location_match:
return False, location_match
if search_depth != self._number_of_location_segments:
return False, location_match
match = self._CheckFileEntryType(file_entry)
if match is not None and not match:
return False, location_match
match = self._CheckIsAllocated(file_entry)
if match is not None and not match:
return False, location_match
return True, location_match | [
"def",
"Matches",
"(",
"self",
",",
"file_entry",
",",
"search_depth",
")",
":",
"if",
"self",
".",
"_location_segments",
"is",
"None",
":",
"location_match",
"=",
"None",
"else",
":",
"location_match",
"=",
"self",
".",
"_CheckLocation",
"(",
"file_entry",
... | Determines if the file entry matches the find specification.
Args:
file_entry (FileEntry): file entry.
search_depth (int): number of location path segments to compare.
Returns:
tuple: contains:
bool: True if the file entry matches the find specification, False
otherwise.
bool: True if the location matches, False if not or None if no location
specified. | [
"Determines",
"if",
"the",
"file",
"entry",
"matches",
"the",
"find",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L329-L362 | train | 208,277 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FindSpec.PrepareMatches | def PrepareMatches(self, file_system):
"""Prepare find specification for matching.
Args:
file_system (FileSystem): file system.
"""
if self._location is not None:
self._location_segments = self._SplitPath(
self._location, file_system.PATH_SEPARATOR)
elif self._location_regex is not None:
path_separator = file_system.PATH_SEPARATOR
if path_separator == '\\':
# The backslash '\' is escaped within a regular expression.
path_separator = '\\\\'
self._location_segments = self._SplitPath(
self._location_regex, path_separator)
if self._location_segments is not None:
self._number_of_location_segments = len(self._location_segments) | python | def PrepareMatches(self, file_system):
"""Prepare find specification for matching.
Args:
file_system (FileSystem): file system.
"""
if self._location is not None:
self._location_segments = self._SplitPath(
self._location, file_system.PATH_SEPARATOR)
elif self._location_regex is not None:
path_separator = file_system.PATH_SEPARATOR
if path_separator == '\\':
# The backslash '\' is escaped within a regular expression.
path_separator = '\\\\'
self._location_segments = self._SplitPath(
self._location_regex, path_separator)
if self._location_segments is not None:
self._number_of_location_segments = len(self._location_segments) | [
"def",
"PrepareMatches",
"(",
"self",
",",
"file_system",
")",
":",
"if",
"self",
".",
"_location",
"is",
"not",
"None",
":",
"self",
".",
"_location_segments",
"=",
"self",
".",
"_SplitPath",
"(",
"self",
".",
"_location",
",",
"file_system",
".",
"PATH_S... | Prepare find specification for matching.
Args:
file_system (FileSystem): file system. | [
"Prepare",
"find",
"specification",
"for",
"matching",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L364-L384 | train | 208,278 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FileSystemSearcher._FindInFileEntry | def _FindInFileEntry(self, file_entry, find_specs, search_depth):
"""Searches for matching file entries within the file entry.
Args:
file_entry (FileEntry): file entry.
find_specs (list[FindSpec]): find specifications.
search_depth (int): number of location path segments to compare.
Yields:
PathSpec: path specification of a matching file entry.
"""
sub_find_specs = []
for find_spec in find_specs:
match, location_match = find_spec.Matches(file_entry, search_depth)
if match:
yield file_entry.path_spec
# pylint: disable=singleton-comparison
if location_match != False and not find_spec.AtMaximumDepth(search_depth):
sub_find_specs.append(find_spec)
if not sub_find_specs:
return
search_depth += 1
try:
for sub_file_entry in file_entry.sub_file_entries:
for matching_path_spec in self._FindInFileEntry(
sub_file_entry, sub_find_specs, search_depth):
yield matching_path_spec
except errors.AccessError:
pass | python | def _FindInFileEntry(self, file_entry, find_specs, search_depth):
"""Searches for matching file entries within the file entry.
Args:
file_entry (FileEntry): file entry.
find_specs (list[FindSpec]): find specifications.
search_depth (int): number of location path segments to compare.
Yields:
PathSpec: path specification of a matching file entry.
"""
sub_find_specs = []
for find_spec in find_specs:
match, location_match = find_spec.Matches(file_entry, search_depth)
if match:
yield file_entry.path_spec
# pylint: disable=singleton-comparison
if location_match != False and not find_spec.AtMaximumDepth(search_depth):
sub_find_specs.append(find_spec)
if not sub_find_specs:
return
search_depth += 1
try:
for sub_file_entry in file_entry.sub_file_entries:
for matching_path_spec in self._FindInFileEntry(
sub_file_entry, sub_find_specs, search_depth):
yield matching_path_spec
except errors.AccessError:
pass | [
"def",
"_FindInFileEntry",
"(",
"self",
",",
"file_entry",
",",
"find_specs",
",",
"search_depth",
")",
":",
"sub_find_specs",
"=",
"[",
"]",
"for",
"find_spec",
"in",
"find_specs",
":",
"match",
",",
"location_match",
"=",
"find_spec",
".",
"Matches",
"(",
... | Searches for matching file entries within the file entry.
Args:
file_entry (FileEntry): file entry.
find_specs (list[FindSpec]): find specifications.
search_depth (int): number of location path segments to compare.
Yields:
PathSpec: path specification of a matching file entry. | [
"Searches",
"for",
"matching",
"file",
"entries",
"within",
"the",
"file",
"entry",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L415-L446 | train | 208,279 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FileSystemSearcher.Find | def Find(self, find_specs=None):
"""Searches for matching file entries within the file system.
Args:
find_specs (list[FindSpec]): find specifications. where None
will return all allocated file entries.
Yields:
PathSpec: path specification of a matching file entry.
"""
if not find_specs:
find_specs.append(FindSpec())
for find_spec in find_specs:
find_spec.PrepareMatches(self._file_system)
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
file_entry = self._file_system.GetFileEntryByPathSpec(self._mount_point)
else:
file_entry = self._file_system.GetRootFileEntry()
for matching_path_spec in self._FindInFileEntry(file_entry, find_specs, 0):
yield matching_path_spec | python | def Find(self, find_specs=None):
"""Searches for matching file entries within the file system.
Args:
find_specs (list[FindSpec]): find specifications. where None
will return all allocated file entries.
Yields:
PathSpec: path specification of a matching file entry.
"""
if not find_specs:
find_specs.append(FindSpec())
for find_spec in find_specs:
find_spec.PrepareMatches(self._file_system)
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
file_entry = self._file_system.GetFileEntryByPathSpec(self._mount_point)
else:
file_entry = self._file_system.GetRootFileEntry()
for matching_path_spec in self._FindInFileEntry(file_entry, find_specs, 0):
yield matching_path_spec | [
"def",
"Find",
"(",
"self",
",",
"find_specs",
"=",
"None",
")",
":",
"if",
"not",
"find_specs",
":",
"find_specs",
".",
"append",
"(",
"FindSpec",
"(",
")",
")",
"for",
"find_spec",
"in",
"find_specs",
":",
"find_spec",
".",
"PrepareMatches",
"(",
"self... | Searches for matching file entries within the file system.
Args:
find_specs (list[FindSpec]): find specifications. where None
will return all allocated file entries.
Yields:
PathSpec: path specification of a matching file entry. | [
"Searches",
"for",
"matching",
"file",
"entries",
"within",
"the",
"file",
"system",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L448-L471 | train | 208,280 |
log2timeline/dfvfs | dfvfs/helpers/file_system_searcher.py | FileSystemSearcher.GetRelativePath | def GetRelativePath(self, path_spec):
"""Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative path or None if the relative path could not
be determined.
Raises:
PathSpecError: if the path specification is incorrect.
"""
location = getattr(path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
if not location.startswith(self._mount_point.location):
raise errors.PathSpecError(
'Path specification does not contain mount point.')
else:
if not hasattr(path_spec, 'parent'):
raise errors.PathSpecError('Path specification missing parent.')
if path_spec.parent != self._mount_point:
raise errors.PathSpecError(
'Path specification does not contain mount point.')
path_segments = self._file_system.SplitPath(location)
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
mount_point_path_segments = self._file_system.SplitPath(
self._mount_point.location)
path_segments = path_segments[len(mount_point_path_segments):]
return '{0:s}{1:s}'.format(
self._file_system.PATH_SEPARATOR,
self._file_system.PATH_SEPARATOR.join(path_segments)) | python | def GetRelativePath(self, path_spec):
"""Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative path or None if the relative path could not
be determined.
Raises:
PathSpecError: if the path specification is incorrect.
"""
location = getattr(path_spec, 'location', None)
if location is None:
raise errors.PathSpecError('Path specification missing location.')
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
if not location.startswith(self._mount_point.location):
raise errors.PathSpecError(
'Path specification does not contain mount point.')
else:
if not hasattr(path_spec, 'parent'):
raise errors.PathSpecError('Path specification missing parent.')
if path_spec.parent != self._mount_point:
raise errors.PathSpecError(
'Path specification does not contain mount point.')
path_segments = self._file_system.SplitPath(location)
if path_spec_factory.Factory.IsSystemLevelTypeIndicator(
self._file_system.type_indicator):
mount_point_path_segments = self._file_system.SplitPath(
self._mount_point.location)
path_segments = path_segments[len(mount_point_path_segments):]
return '{0:s}{1:s}'.format(
self._file_system.PATH_SEPARATOR,
self._file_system.PATH_SEPARATOR.join(path_segments)) | [
"def",
"GetRelativePath",
"(",
"self",
",",
"path_spec",
")",
":",
"location",
"=",
"getattr",
"(",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"location",
"is",
"None",
":",
"raise",
"errors",
".",
"PathSpecError",
"(",
"'Path specification missin... | Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative path or None if the relative path could not
be determined.
Raises:
PathSpecError: if the path specification is incorrect. | [
"Returns",
"the",
"relative",
"path",
"based",
"on",
"a",
"resolved",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/file_system_searcher.py#L484-L527 | train | 208,281 |
log2timeline/dfvfs | examples/source_analyzer.py | SourceAnalyzer._PromptUserForEncryptedVolumeCredential | def _PromptUserForEncryptedVolumeCredential(
self, scan_context, locked_scan_node, output_writer):
"""Prompts the user to provide a credential for an encrypted volume.
Args:
scan_context (SourceScannerContext): the source scanner context.
locked_scan_node (SourceScanNode): the locked scan node.
output_writer (StdoutWriter): the output writer.
"""
credentials = credentials_manager.CredentialsManager.GetCredentials(
locked_scan_node.path_spec)
# TODO: print volume description.
if locked_scan_node.type_indicator == (
definitions.TYPE_INDICATOR_APFS_CONTAINER):
line = 'Found an APFS encrypted volume.'
elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE:
line = 'Found a BitLocker encrypted volume.'
elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_FVDE:
line = 'Found a CoreStorage (FVDE) encrypted volume.'
else:
line = 'Found an encrypted volume.'
output_writer.WriteLine(line)
credentials_list = list(credentials.CREDENTIALS)
credentials_list.append('skip')
# TODO: check which credentials are available.
output_writer.WriteLine('Supported credentials:')
output_writer.WriteLine('')
for index, name in enumerate(credentials_list):
output_writer.WriteLine(' {0:d}. {1:s}'.format(index + 1, name))
output_writer.WriteLine('')
result = False
while not result:
output_writer.WriteString(
'Select a credential to unlock the volume: ')
# TODO: add an input reader.
input_line = sys.stdin.readline()
input_line = input_line.strip()
if input_line in credentials_list:
credential_identifier = input_line
else:
try:
credential_identifier = int(input_line, 10)
credential_identifier = credentials_list[credential_identifier - 1]
except (IndexError, ValueError):
output_writer.WriteLine(
'Unsupported credential: {0:s}'.format(input_line))
continue
if credential_identifier == 'skip':
break
getpass_string = 'Enter credential data: '
if sys.platform.startswith('win') and sys.version_info[0] < 3:
# For Python 2 on Windows getpass (win_getpass) requires an encoded
# byte string. For Python 3 we need it to be a Unicode string.
getpass_string = self._EncodeString(getpass_string)
credential_data = getpass.getpass(getpass_string)
output_writer.WriteLine('')
result = self._source_scanner.Unlock(
scan_context, locked_scan_node.path_spec, credential_identifier,
credential_data)
if not result:
output_writer.WriteLine('Unable to unlock volume.')
output_writer.WriteLine('') | python | def _PromptUserForEncryptedVolumeCredential(
self, scan_context, locked_scan_node, output_writer):
"""Prompts the user to provide a credential for an encrypted volume.
Args:
scan_context (SourceScannerContext): the source scanner context.
locked_scan_node (SourceScanNode): the locked scan node.
output_writer (StdoutWriter): the output writer.
"""
credentials = credentials_manager.CredentialsManager.GetCredentials(
locked_scan_node.path_spec)
# TODO: print volume description.
if locked_scan_node.type_indicator == (
definitions.TYPE_INDICATOR_APFS_CONTAINER):
line = 'Found an APFS encrypted volume.'
elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE:
line = 'Found a BitLocker encrypted volume.'
elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_FVDE:
line = 'Found a CoreStorage (FVDE) encrypted volume.'
else:
line = 'Found an encrypted volume.'
output_writer.WriteLine(line)
credentials_list = list(credentials.CREDENTIALS)
credentials_list.append('skip')
# TODO: check which credentials are available.
output_writer.WriteLine('Supported credentials:')
output_writer.WriteLine('')
for index, name in enumerate(credentials_list):
output_writer.WriteLine(' {0:d}. {1:s}'.format(index + 1, name))
output_writer.WriteLine('')
result = False
while not result:
output_writer.WriteString(
'Select a credential to unlock the volume: ')
# TODO: add an input reader.
input_line = sys.stdin.readline()
input_line = input_line.strip()
if input_line in credentials_list:
credential_identifier = input_line
else:
try:
credential_identifier = int(input_line, 10)
credential_identifier = credentials_list[credential_identifier - 1]
except (IndexError, ValueError):
output_writer.WriteLine(
'Unsupported credential: {0:s}'.format(input_line))
continue
if credential_identifier == 'skip':
break
getpass_string = 'Enter credential data: '
if sys.platform.startswith('win') and sys.version_info[0] < 3:
# For Python 2 on Windows getpass (win_getpass) requires an encoded
# byte string. For Python 3 we need it to be a Unicode string.
getpass_string = self._EncodeString(getpass_string)
credential_data = getpass.getpass(getpass_string)
output_writer.WriteLine('')
result = self._source_scanner.Unlock(
scan_context, locked_scan_node.path_spec, credential_identifier,
credential_data)
if not result:
output_writer.WriteLine('Unable to unlock volume.')
output_writer.WriteLine('') | [
"def",
"_PromptUserForEncryptedVolumeCredential",
"(",
"self",
",",
"scan_context",
",",
"locked_scan_node",
",",
"output_writer",
")",
":",
"credentials",
"=",
"credentials_manager",
".",
"CredentialsManager",
".",
"GetCredentials",
"(",
"locked_scan_node",
".",
"path_sp... | Prompts the user to provide a credential for an encrypted volume.
Args:
scan_context (SourceScannerContext): the source scanner context.
locked_scan_node (SourceScanNode): the locked scan node.
output_writer (StdoutWriter): the output writer. | [
"Prompts",
"the",
"user",
"to",
"provide",
"a",
"credential",
"for",
"an",
"encrypted",
"volume",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/source_analyzer.py#L64-L136 | train | 208,282 |
log2timeline/dfvfs | examples/source_analyzer.py | SourceAnalyzer.Analyze | def Analyze(self, source_path, output_writer):
"""Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
if not os.path.exists(source_path):
raise RuntimeError('No such source: {0:s}.'.format(source_path))
scan_context = source_scanner.SourceScannerContext()
scan_path_spec = None
scan_step = 0
scan_context.OpenSourcePath(source_path)
while True:
self._source_scanner.Scan(
scan_context, auto_recurse=self._auto_recurse,
scan_path_spec=scan_path_spec)
if not scan_context.updated:
break
if not self._auto_recurse:
output_writer.WriteScanContext(scan_context, scan_step=scan_step)
scan_step += 1
# The source is a directory or file.
if scan_context.source_type in [
definitions.SOURCE_TYPE_DIRECTORY, definitions.SOURCE_TYPE_FILE]:
break
# The source scanner found a locked volume, e.g. an encrypted volume,
# and we need a credential to unlock the volume.
for locked_scan_node in scan_context.locked_scan_nodes:
self._PromptUserForEncryptedVolumeCredential(
scan_context, locked_scan_node, output_writer)
if not self._auto_recurse:
scan_node = scan_context.GetUnscannedScanNode()
if not scan_node:
return
scan_path_spec = scan_node.path_spec
if self._auto_recurse:
output_writer.WriteScanContext(scan_context) | python | def Analyze(self, source_path, output_writer):
"""Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.
"""
if not os.path.exists(source_path):
raise RuntimeError('No such source: {0:s}.'.format(source_path))
scan_context = source_scanner.SourceScannerContext()
scan_path_spec = None
scan_step = 0
scan_context.OpenSourcePath(source_path)
while True:
self._source_scanner.Scan(
scan_context, auto_recurse=self._auto_recurse,
scan_path_spec=scan_path_spec)
if not scan_context.updated:
break
if not self._auto_recurse:
output_writer.WriteScanContext(scan_context, scan_step=scan_step)
scan_step += 1
# The source is a directory or file.
if scan_context.source_type in [
definitions.SOURCE_TYPE_DIRECTORY, definitions.SOURCE_TYPE_FILE]:
break
# The source scanner found a locked volume, e.g. an encrypted volume,
# and we need a credential to unlock the volume.
for locked_scan_node in scan_context.locked_scan_nodes:
self._PromptUserForEncryptedVolumeCredential(
scan_context, locked_scan_node, output_writer)
if not self._auto_recurse:
scan_node = scan_context.GetUnscannedScanNode()
if not scan_node:
return
scan_path_spec = scan_node.path_spec
if self._auto_recurse:
output_writer.WriteScanContext(scan_context) | [
"def",
"Analyze",
"(",
"self",
",",
"source_path",
",",
"output_writer",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source_path",
")",
":",
"raise",
"RuntimeError",
"(",
"'No such source: {0:s}.'",
".",
"format",
"(",
"source_path",
")",
... | Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported. | [
"Analyzes",
"the",
"source",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/source_analyzer.py#L138-L189 | train | 208,283 |
log2timeline/dfvfs | examples/source_analyzer.py | StdoutWriter.WriteScanContext | def WriteScanContext(self, scan_context, scan_step=None):
"""Writes the source scanner context to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_step (Optional[int]): the scan step, where None represents no step.
"""
if scan_step is not None:
print('Scan step: {0:d}'.format(scan_step))
print('Source type\t\t: {0:s}'.format(scan_context.source_type))
print('')
scan_node = scan_context.GetRootScanNode()
self.WriteScanNode(scan_context, scan_node)
print('') | python | def WriteScanContext(self, scan_context, scan_step=None):
"""Writes the source scanner context to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_step (Optional[int]): the scan step, where None represents no step.
"""
if scan_step is not None:
print('Scan step: {0:d}'.format(scan_step))
print('Source type\t\t: {0:s}'.format(scan_context.source_type))
print('')
scan_node = scan_context.GetRootScanNode()
self.WriteScanNode(scan_context, scan_node)
print('') | [
"def",
"WriteScanContext",
"(",
"self",
",",
"scan_context",
",",
"scan_step",
"=",
"None",
")",
":",
"if",
"scan_step",
"is",
"not",
"None",
":",
"print",
"(",
"'Scan step: {0:d}'",
".",
"format",
"(",
"scan_step",
")",
")",
"print",
"(",
"'Source type\\t\\... | Writes the source scanner context to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_step (Optional[int]): the scan step, where None represents no step. | [
"Writes",
"the",
"source",
"scanner",
"context",
"to",
"stdout",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/source_analyzer.py#L215-L230 | train | 208,284 |
log2timeline/dfvfs | examples/source_analyzer.py | StdoutWriter.WriteScanNode | def WriteScanNode(self, scan_context, scan_node, indentation=''):
"""Writes the source scanner node to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_node (SourceScanNode): the scan node.
indentation (Optional[str]): indentation.
"""
if not scan_node:
return
values = []
part_index = getattr(scan_node.path_spec, 'part_index', None)
if part_index is not None:
values.append('{0:d}'.format(part_index))
store_index = getattr(scan_node.path_spec, 'store_index', None)
if store_index is not None:
values.append('{0:d}'.format(store_index))
start_offset = getattr(scan_node.path_spec, 'start_offset', None)
if start_offset is not None:
values.append('start offset: {0:d} (0x{0:08x})'.format(start_offset))
location = getattr(scan_node.path_spec, 'location', None)
if location is not None:
values.append('location: {0:s}'.format(location))
values = ', '.join(values)
flags = ''
if scan_node in scan_context.locked_scan_nodes:
flags = ' [LOCKED]'
print('{0:s}{1:s}: {2:s}{3:s}'.format(
indentation, scan_node.path_spec.type_indicator, values, flags))
indentation = ' {0:s}'.format(indentation)
for sub_scan_node in scan_node.sub_nodes:
self.WriteScanNode(scan_context, sub_scan_node, indentation=indentation) | python | def WriteScanNode(self, scan_context, scan_node, indentation=''):
"""Writes the source scanner node to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_node (SourceScanNode): the scan node.
indentation (Optional[str]): indentation.
"""
if not scan_node:
return
values = []
part_index = getattr(scan_node.path_spec, 'part_index', None)
if part_index is not None:
values.append('{0:d}'.format(part_index))
store_index = getattr(scan_node.path_spec, 'store_index', None)
if store_index is not None:
values.append('{0:d}'.format(store_index))
start_offset = getattr(scan_node.path_spec, 'start_offset', None)
if start_offset is not None:
values.append('start offset: {0:d} (0x{0:08x})'.format(start_offset))
location = getattr(scan_node.path_spec, 'location', None)
if location is not None:
values.append('location: {0:s}'.format(location))
values = ', '.join(values)
flags = ''
if scan_node in scan_context.locked_scan_nodes:
flags = ' [LOCKED]'
print('{0:s}{1:s}: {2:s}{3:s}'.format(
indentation, scan_node.path_spec.type_indicator, values, flags))
indentation = ' {0:s}'.format(indentation)
for sub_scan_node in scan_node.sub_nodes:
self.WriteScanNode(scan_context, sub_scan_node, indentation=indentation) | [
"def",
"WriteScanNode",
"(",
"self",
",",
"scan_context",
",",
"scan_node",
",",
"indentation",
"=",
"''",
")",
":",
"if",
"not",
"scan_node",
":",
"return",
"values",
"=",
"[",
"]",
"part_index",
"=",
"getattr",
"(",
"scan_node",
".",
"path_spec",
",",
... | Writes the source scanner node to stdout.
Args:
scan_context (SourceScannerContext): the source scanner context.
scan_node (SourceScanNode): the scan node.
indentation (Optional[str]): indentation. | [
"Writes",
"the",
"source",
"scanner",
"node",
"to",
"stdout",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/source_analyzer.py#L232-L272 | train | 208,285 |
log2timeline/dfvfs | examples/recursive_hasher.py | RecursiveHasher._CalculateHashDataStream | def _CalculateHashDataStream(self, file_entry, data_stream_name):
"""Calculates a message digest hash of the data of the file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): name of the data stream.
Returns:
bytes: digest hash or None.
"""
hash_context = hashlib.sha256()
try:
file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
except IOError as exception:
logging.warning((
'Unable to open path specification:\n{0:s}'
'with error: {1!s}').format(
file_entry.path_spec.comparable, exception))
return None
if not file_object:
return None
try:
data = file_object.read(self._READ_BUFFER_SIZE)
while data:
hash_context.update(data)
data = file_object.read(self._READ_BUFFER_SIZE)
except IOError as exception:
logging.warning((
'Unable to read from path specification:\n{0:s}'
'with error: {1!s}').format(
file_entry.path_spec.comparable, exception))
return None
finally:
file_object.close()
return hash_context.hexdigest() | python | def _CalculateHashDataStream(self, file_entry, data_stream_name):
"""Calculates a message digest hash of the data of the file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): name of the data stream.
Returns:
bytes: digest hash or None.
"""
hash_context = hashlib.sha256()
try:
file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
except IOError as exception:
logging.warning((
'Unable to open path specification:\n{0:s}'
'with error: {1!s}').format(
file_entry.path_spec.comparable, exception))
return None
if not file_object:
return None
try:
data = file_object.read(self._READ_BUFFER_SIZE)
while data:
hash_context.update(data)
data = file_object.read(self._READ_BUFFER_SIZE)
except IOError as exception:
logging.warning((
'Unable to read from path specification:\n{0:s}'
'with error: {1!s}').format(
file_entry.path_spec.comparable, exception))
return None
finally:
file_object.close()
return hash_context.hexdigest() | [
"def",
"_CalculateHashDataStream",
"(",
"self",
",",
"file_entry",
",",
"data_stream_name",
")",
":",
"hash_context",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"try",
":",
"file_object",
"=",
"file_entry",
".",
"GetFileObject",
"(",
"data_stream_name",
"=",
"data... | Calculates a message digest hash of the data of the file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): name of the data stream.
Returns:
bytes: digest hash or None. | [
"Calculates",
"a",
"message",
"digest",
"hash",
"of",
"the",
"data",
"of",
"the",
"file",
"entry",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L39-L78 | train | 208,286 |
log2timeline/dfvfs | examples/recursive_hasher.py | RecursiveHasher._CalculateHashesFileEntry | def _CalculateHashesFileEntry(
self, file_system, file_entry, parent_full_path, output_writer):
"""Recursive calculates hashes starting with the file entry.
Args:
file_system (dfvfs.FileSystem): file system.
file_entry (dfvfs.FileEntry): file entry.
parent_full_path (str): full path of the parent file entry.
output_writer (StdoutWriter): output writer.
"""
# Since every file system implementation can have their own path
# segment separator we are using JoinPath to be platform and file system
# type independent.
full_path = file_system.JoinPath([parent_full_path, file_entry.name])
for data_stream in file_entry.data_streams:
hash_value = self._CalculateHashDataStream(file_entry, data_stream.name)
display_path = self._GetDisplayPath(
file_entry.path_spec, full_path, data_stream.name)
output_writer.WriteFileHash(display_path, hash_value or 'N/A')
for sub_file_entry in file_entry.sub_file_entries:
self._CalculateHashesFileEntry(
file_system, sub_file_entry, full_path, output_writer) | python | def _CalculateHashesFileEntry(
self, file_system, file_entry, parent_full_path, output_writer):
"""Recursive calculates hashes starting with the file entry.
Args:
file_system (dfvfs.FileSystem): file system.
file_entry (dfvfs.FileEntry): file entry.
parent_full_path (str): full path of the parent file entry.
output_writer (StdoutWriter): output writer.
"""
# Since every file system implementation can have their own path
# segment separator we are using JoinPath to be platform and file system
# type independent.
full_path = file_system.JoinPath([parent_full_path, file_entry.name])
for data_stream in file_entry.data_streams:
hash_value = self._CalculateHashDataStream(file_entry, data_stream.name)
display_path = self._GetDisplayPath(
file_entry.path_spec, full_path, data_stream.name)
output_writer.WriteFileHash(display_path, hash_value or 'N/A')
for sub_file_entry in file_entry.sub_file_entries:
self._CalculateHashesFileEntry(
file_system, sub_file_entry, full_path, output_writer) | [
"def",
"_CalculateHashesFileEntry",
"(",
"self",
",",
"file_system",
",",
"file_entry",
",",
"parent_full_path",
",",
"output_writer",
")",
":",
"# Since every file system implementation can have their own path",
"# segment separator we are using JoinPath to be platform and file system... | Recursive calculates hashes starting with the file entry.
Args:
file_system (dfvfs.FileSystem): file system.
file_entry (dfvfs.FileEntry): file entry.
parent_full_path (str): full path of the parent file entry.
output_writer (StdoutWriter): output writer. | [
"Recursive",
"calculates",
"hashes",
"starting",
"with",
"the",
"file",
"entry",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L80-L102 | train | 208,287 |
log2timeline/dfvfs | examples/recursive_hasher.py | RecursiveHasher._GetDisplayPath | def _GetDisplayPath(self, path_spec, full_path, data_stream_name):
"""Retrieves a path to display.
Args:
path_spec (dfvfs.PathSpec): path specification of the file entry.
full_path (str): full path of the file entry.
data_stream_name (str): name of the data stream.
Returns:
str: path to display.
"""
display_path = ''
if path_spec.HasParent():
parent_path_spec = path_spec.parent
if parent_path_spec and parent_path_spec.type_indicator == (
dfvfs_definitions.TYPE_INDICATOR_TSK_PARTITION):
display_path = ''.join([display_path, parent_path_spec.location])
display_path = ''.join([display_path, full_path])
if data_stream_name:
display_path = ':'.join([display_path, data_stream_name])
return display_path | python | def _GetDisplayPath(self, path_spec, full_path, data_stream_name):
"""Retrieves a path to display.
Args:
path_spec (dfvfs.PathSpec): path specification of the file entry.
full_path (str): full path of the file entry.
data_stream_name (str): name of the data stream.
Returns:
str: path to display.
"""
display_path = ''
if path_spec.HasParent():
parent_path_spec = path_spec.parent
if parent_path_spec and parent_path_spec.type_indicator == (
dfvfs_definitions.TYPE_INDICATOR_TSK_PARTITION):
display_path = ''.join([display_path, parent_path_spec.location])
display_path = ''.join([display_path, full_path])
if data_stream_name:
display_path = ':'.join([display_path, data_stream_name])
return display_path | [
"def",
"_GetDisplayPath",
"(",
"self",
",",
"path_spec",
",",
"full_path",
",",
"data_stream_name",
")",
":",
"display_path",
"=",
"''",
"if",
"path_spec",
".",
"HasParent",
"(",
")",
":",
"parent_path_spec",
"=",
"path_spec",
".",
"parent",
"if",
"parent_path... | Retrieves a path to display.
Args:
path_spec (dfvfs.PathSpec): path specification of the file entry.
full_path (str): full path of the file entry.
data_stream_name (str): name of the data stream.
Returns:
str: path to display. | [
"Retrieves",
"a",
"path",
"to",
"display",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L104-L127 | train | 208,288 |
log2timeline/dfvfs | examples/recursive_hasher.py | RecursiveHasher.CalculateHashes | def CalculateHashes(self, base_path_specs, output_writer):
"""Recursive calculates hashes starting with the base path specification.
Args:
base_path_specs (list[dfvfs.PathSpec]): source path specification.
output_writer (StdoutWriter): output writer.
"""
for base_path_spec in base_path_specs:
file_system = resolver.Resolver.OpenFileSystem(base_path_spec)
file_entry = resolver.Resolver.OpenFileEntry(base_path_spec)
if file_entry is None:
logging.warning('Unable to open base path specification:\n{0:s}'.format(
base_path_spec.comparable))
continue
self._CalculateHashesFileEntry(file_system, file_entry, '', output_writer) | python | def CalculateHashes(self, base_path_specs, output_writer):
"""Recursive calculates hashes starting with the base path specification.
Args:
base_path_specs (list[dfvfs.PathSpec]): source path specification.
output_writer (StdoutWriter): output writer.
"""
for base_path_spec in base_path_specs:
file_system = resolver.Resolver.OpenFileSystem(base_path_spec)
file_entry = resolver.Resolver.OpenFileEntry(base_path_spec)
if file_entry is None:
logging.warning('Unable to open base path specification:\n{0:s}'.format(
base_path_spec.comparable))
continue
self._CalculateHashesFileEntry(file_system, file_entry, '', output_writer) | [
"def",
"CalculateHashes",
"(",
"self",
",",
"base_path_specs",
",",
"output_writer",
")",
":",
"for",
"base_path_spec",
"in",
"base_path_specs",
":",
"file_system",
"=",
"resolver",
".",
"Resolver",
".",
"OpenFileSystem",
"(",
"base_path_spec",
")",
"file_entry",
... | Recursive calculates hashes starting with the base path specification.
Args:
base_path_specs (list[dfvfs.PathSpec]): source path specification.
output_writer (StdoutWriter): output writer. | [
"Recursive",
"calculates",
"hashes",
"starting",
"with",
"the",
"base",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L129-L144 | train | 208,289 |
log2timeline/dfvfs | examples/recursive_hasher.py | OutputWriter._EncodeString | def _EncodeString(self, string):
"""Encodes the string.
Args:
string (str): string to encode.
Returns:
bytes: encoded string.
"""
try:
# Note that encode() will first convert string into a Unicode string
# if necessary.
encoded_string = string.encode(self._encoding, errors=self._errors)
except UnicodeEncodeError:
if self._errors == 'strict':
logging.error(
'Unable to properly write output due to encoding error. '
'Switching to error tolerant encoding which can result in '
'non Basic Latin (C0) characters to be replaced with "?" or '
'"\\ufffd".')
self._errors = 'replace'
encoded_string = string.encode(self._encoding, errors=self._errors)
return encoded_string | python | def _EncodeString(self, string):
"""Encodes the string.
Args:
string (str): string to encode.
Returns:
bytes: encoded string.
"""
try:
# Note that encode() will first convert string into a Unicode string
# if necessary.
encoded_string = string.encode(self._encoding, errors=self._errors)
except UnicodeEncodeError:
if self._errors == 'strict':
logging.error(
'Unable to properly write output due to encoding error. '
'Switching to error tolerant encoding which can result in '
'non Basic Latin (C0) characters to be replaced with "?" or '
'"\\ufffd".')
self._errors = 'replace'
encoded_string = string.encode(self._encoding, errors=self._errors)
return encoded_string | [
"def",
"_EncodeString",
"(",
"self",
",",
"string",
")",
":",
"try",
":",
"# Note that encode() will first convert string into a Unicode string",
"# if necessary.",
"encoded_string",
"=",
"string",
".",
"encode",
"(",
"self",
".",
"_encoding",
",",
"errors",
"=",
"sel... | Encodes the string.
Args:
string (str): string to encode.
Returns:
bytes: encoded string. | [
"Encodes",
"the",
"string",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L160-L184 | train | 208,290 |
log2timeline/dfvfs | examples/recursive_hasher.py | FileOutputWriter.WriteFileHash | def WriteFileHash(self, path, hash_value):
"""Writes the file path and hash to file.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.
"""
string = '{0:s}\t{1:s}\n'.format(hash_value, path)
encoded_string = self._EncodeString(string)
self._file_object.write(encoded_string) | python | def WriteFileHash(self, path, hash_value):
"""Writes the file path and hash to file.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.
"""
string = '{0:s}\t{1:s}\n'.format(hash_value, path)
encoded_string = self._EncodeString(string)
self._file_object.write(encoded_string) | [
"def",
"WriteFileHash",
"(",
"self",
",",
"path",
",",
"hash_value",
")",
":",
"string",
"=",
"'{0:s}\\t{1:s}\\n'",
".",
"format",
"(",
"hash_value",
",",
"path",
")",
"encoded_string",
"=",
"self",
".",
"_EncodeString",
"(",
"string",
")",
"self",
".",
"_... | Writes the file path and hash to file.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data. | [
"Writes",
"the",
"file",
"path",
"and",
"hash",
"to",
"file",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L228-L238 | train | 208,291 |
log2timeline/dfvfs | examples/recursive_hasher.py | StdoutWriter.WriteFileHash | def WriteFileHash(self, path, hash_value):
"""Writes the file path and hash to stdout.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.
"""
string = '{0:s}\t{1:s}'.format(hash_value, path)
encoded_string = self._EncodeString(string)
print(encoded_string) | python | def WriteFileHash(self, path, hash_value):
"""Writes the file path and hash to stdout.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.
"""
string = '{0:s}\t{1:s}'.format(hash_value, path)
encoded_string = self._EncodeString(string)
print(encoded_string) | [
"def",
"WriteFileHash",
"(",
"self",
",",
"path",
",",
"hash_value",
")",
":",
"string",
"=",
"'{0:s}\\t{1:s}'",
".",
"format",
"(",
"hash_value",
",",
"path",
")",
"encoded_string",
"=",
"self",
".",
"_EncodeString",
"(",
"string",
")",
"print",
"(",
"enc... | Writes the file path and hash to stdout.
Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data. | [
"Writes",
"the",
"file",
"path",
"and",
"hash",
"to",
"stdout",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L252-L262 | train | 208,292 |
log2timeline/dfvfs | dfvfs/vfs/os_file_entry.py | OSFileEntry.GetLinkedFileEntry | def GetLinkedFileEntry(self):
"""Retrieves the linked file entry, for example for a symbolic link.
Returns:
OSFileEntry: linked file entry or None if not available.
"""
link = self._GetLink()
if not link:
return None
path_spec = os_path_spec.OSPathSpec(location=link)
return OSFileEntry(self._resolver_context, self._file_system, path_spec) | python | def GetLinkedFileEntry(self):
"""Retrieves the linked file entry, for example for a symbolic link.
Returns:
OSFileEntry: linked file entry or None if not available.
"""
link = self._GetLink()
if not link:
return None
path_spec = os_path_spec.OSPathSpec(location=link)
return OSFileEntry(self._resolver_context, self._file_system, path_spec) | [
"def",
"GetLinkedFileEntry",
"(",
"self",
")",
":",
"link",
"=",
"self",
".",
"_GetLink",
"(",
")",
"if",
"not",
"link",
":",
"return",
"None",
"path_spec",
"=",
"os_path_spec",
".",
"OSPathSpec",
"(",
"location",
"=",
"link",
")",
"return",
"OSFileEntry",... | Retrieves the linked file entry, for example for a symbolic link.
Returns:
OSFileEntry: linked file entry or None if not available. | [
"Retrieves",
"the",
"linked",
"file",
"entry",
"for",
"example",
"for",
"a",
"symbolic",
"link",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/os_file_entry.py#L261-L272 | train | 208,293 |
log2timeline/dfvfs | dfvfs/vfs/apfs_container_file_system.py | APFSContainerFileSystem.GetAPFSVolumeByPathSpec | def GetAPFSVolumeByPathSpec(self, path_spec):
"""Retrieves an APFS volume for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyfsapfs.volume: an APFS volume or None if not available.
"""
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec)
if volume_index is None:
return None
return self._fsapfs_container.get_volume(volume_index) | python | def GetAPFSVolumeByPathSpec(self, path_spec):
"""Retrieves an APFS volume for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyfsapfs.volume: an APFS volume or None if not available.
"""
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec)
if volume_index is None:
return None
return self._fsapfs_container.get_volume(volume_index) | [
"def",
"GetAPFSVolumeByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"volume_index",
"=",
"apfs_helper",
".",
"APFSContainerPathSpecGetVolumeIndex",
"(",
"path_spec",
")",
"if",
"volume_index",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"_fs... | Retrieves an APFS volume for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyfsapfs.volume: an APFS volume or None if not available. | [
"Retrieves",
"an",
"APFS",
"volume",
"for",
"a",
"path",
"specification",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/apfs_container_file_system.py#L102-L115 | train | 208,294 |
log2timeline/dfvfs | dfvfs/lib/glob2regex.py | Glob2Regex | def Glob2Regex(glob_pattern):
"""Converts a glob pattern to a regular expression.
This function supports basic glob patterns that consist of:
* matches everything
? matches any single character
[seq] matches any character in sequence
[!seq] matches any character not in sequence
Args:
glob_pattern (str): glob pattern.
Returns:
str: regular expression pattern.
Raises:
ValueError: if the glob pattern cannot be converted.
"""
if not glob_pattern:
raise ValueError('Missing glob pattern.')
regex_pattern = []
glob_pattern_index = 0
glob_pattern_length = len(glob_pattern)
while glob_pattern_index < glob_pattern_length:
character = glob_pattern[glob_pattern_index]
glob_pattern_index += 1
if character == '*':
regex_pattern.append('.*')
elif character == '?':
regex_pattern.append('.')
elif character != '[':
regex_character = re.escape(character)
regex_pattern.append(regex_character)
else:
glob_group_index = glob_pattern_index
if (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] == '!'):
glob_group_index += 1
if (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] == ']'):
glob_group_index += 1
while (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] != ']'):
glob_group_index += 1
if glob_group_index >= glob_pattern_length:
regex_pattern.append('\\[')
continue
glob_group = glob_pattern[glob_pattern_index:glob_group_index]
glob_pattern_index = glob_group_index + 1
glob_group = glob_group.replace('\\', '\\\\')
if py2to3.PY_3_7_AND_LATER:
glob_group = glob_group.replace('|', '\\|')
regex_pattern.append('[')
if glob_group[0] == '!':
regex_pattern.append('^')
glob_group = glob_group[1:]
elif glob_group[0] == '^':
regex_pattern.append('\\')
regex_pattern.append(glob_group)
regex_pattern.append(']')
return ''.join(regex_pattern) | python | def Glob2Regex(glob_pattern):
"""Converts a glob pattern to a regular expression.
This function supports basic glob patterns that consist of:
* matches everything
? matches any single character
[seq] matches any character in sequence
[!seq] matches any character not in sequence
Args:
glob_pattern (str): glob pattern.
Returns:
str: regular expression pattern.
Raises:
ValueError: if the glob pattern cannot be converted.
"""
if not glob_pattern:
raise ValueError('Missing glob pattern.')
regex_pattern = []
glob_pattern_index = 0
glob_pattern_length = len(glob_pattern)
while glob_pattern_index < glob_pattern_length:
character = glob_pattern[glob_pattern_index]
glob_pattern_index += 1
if character == '*':
regex_pattern.append('.*')
elif character == '?':
regex_pattern.append('.')
elif character != '[':
regex_character = re.escape(character)
regex_pattern.append(regex_character)
else:
glob_group_index = glob_pattern_index
if (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] == '!'):
glob_group_index += 1
if (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] == ']'):
glob_group_index += 1
while (glob_group_index < glob_pattern_length and
glob_pattern[glob_group_index] != ']'):
glob_group_index += 1
if glob_group_index >= glob_pattern_length:
regex_pattern.append('\\[')
continue
glob_group = glob_pattern[glob_pattern_index:glob_group_index]
glob_pattern_index = glob_group_index + 1
glob_group = glob_group.replace('\\', '\\\\')
if py2to3.PY_3_7_AND_LATER:
glob_group = glob_group.replace('|', '\\|')
regex_pattern.append('[')
if glob_group[0] == '!':
regex_pattern.append('^')
glob_group = glob_group[1:]
elif glob_group[0] == '^':
regex_pattern.append('\\')
regex_pattern.append(glob_group)
regex_pattern.append(']')
return ''.join(regex_pattern) | [
"def",
"Glob2Regex",
"(",
"glob_pattern",
")",
":",
"if",
"not",
"glob_pattern",
":",
"raise",
"ValueError",
"(",
"'Missing glob pattern.'",
")",
"regex_pattern",
"=",
"[",
"]",
"glob_pattern_index",
"=",
"0",
"glob_pattern_length",
"=",
"len",
"(",
"glob_pattern"... | Converts a glob pattern to a regular expression.
This function supports basic glob patterns that consist of:
* matches everything
? matches any single character
[seq] matches any character in sequence
[!seq] matches any character not in sequence
Args:
glob_pattern (str): glob pattern.
Returns:
str: regular expression pattern.
Raises:
ValueError: if the glob pattern cannot be converted. | [
"Converts",
"a",
"glob",
"pattern",
"to",
"a",
"regular",
"expression",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/glob2regex.py#L14-L91 | train | 208,295 |
log2timeline/dfvfs | dfvfs/resolver/cache.py | ObjectsCache.CacheObject | def CacheObject(self, identifier, vfs_object):
"""Caches a VFS object.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
vfs_object (object): VFS object to cache.
Raises:
CacheFullError: if he maximum number of cached values is reached.
KeyError: if the VFS object already is cached.
"""
if identifier in self._values:
raise KeyError('Object already cached for identifier: {0:s}'.format(
identifier))
if len(self._values) == self._maximum_number_of_cached_values:
raise errors.CacheFullError('Maximum number of cached values reached.')
self._values[identifier] = ObjectsCacheValue(vfs_object) | python | def CacheObject(self, identifier, vfs_object):
"""Caches a VFS object.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
vfs_object (object): VFS object to cache.
Raises:
CacheFullError: if he maximum number of cached values is reached.
KeyError: if the VFS object already is cached.
"""
if identifier in self._values:
raise KeyError('Object already cached for identifier: {0:s}'.format(
identifier))
if len(self._values) == self._maximum_number_of_cached_values:
raise errors.CacheFullError('Maximum number of cached values reached.')
self._values[identifier] = ObjectsCacheValue(vfs_object) | [
"def",
"CacheObject",
"(",
"self",
",",
"identifier",
",",
"vfs_object",
")",
":",
"if",
"identifier",
"in",
"self",
".",
"_values",
":",
"raise",
"KeyError",
"(",
"'Object already cached for identifier: {0:s}'",
".",
"format",
"(",
"identifier",
")",
")",
"if",... | Caches a VFS object.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
vfs_object (object): VFS object to cache.
Raises:
CacheFullError: if he maximum number of cached values is reached.
KeyError: if the VFS object already is cached. | [
"Caches",
"a",
"VFS",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L67-L87 | train | 208,296 |
log2timeline/dfvfs | dfvfs/resolver/cache.py | ObjectsCache.GetCacheValueByObject | def GetCacheValueByObject(self, vfs_object):
"""Retrieves the cache value for the cached object.
Args:
vfs_object (object): VFS object that was cached.
Returns:
tuple[str, ObjectsCacheValue]: identifier and cache value object or
(None, None) if not cached.
Raises:
RuntimeError: if the cache value is missing.
"""
for identifier, cache_value in iter(self._values.items()):
if not cache_value:
raise RuntimeError('Missing cache value.')
if cache_value.vfs_object == vfs_object:
return identifier, cache_value
return None, None | python | def GetCacheValueByObject(self, vfs_object):
"""Retrieves the cache value for the cached object.
Args:
vfs_object (object): VFS object that was cached.
Returns:
tuple[str, ObjectsCacheValue]: identifier and cache value object or
(None, None) if not cached.
Raises:
RuntimeError: if the cache value is missing.
"""
for identifier, cache_value in iter(self._values.items()):
if not cache_value:
raise RuntimeError('Missing cache value.')
if cache_value.vfs_object == vfs_object:
return identifier, cache_value
return None, None | [
"def",
"GetCacheValueByObject",
"(",
"self",
",",
"vfs_object",
")",
":",
"for",
"identifier",
",",
"cache_value",
"in",
"iter",
"(",
"self",
".",
"_values",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"cache_value",
":",
"raise",
"RuntimeError",
"(",
... | Retrieves the cache value for the cached object.
Args:
vfs_object (object): VFS object that was cached.
Returns:
tuple[str, ObjectsCacheValue]: identifier and cache value object or
(None, None) if not cached.
Raises:
RuntimeError: if the cache value is missing. | [
"Retrieves",
"the",
"cache",
"value",
"for",
"the",
"cached",
"object",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L110-L130 | train | 208,297 |
log2timeline/dfvfs | dfvfs/resolver/cache.py | ObjectsCache.GetObject | def GetObject(self, identifier):
"""Retrieves a cached object based on the identifier.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
Returns:
object: cached VFS object or None if not cached.
"""
cache_value = self._values.get(identifier, None)
if not cache_value:
return None
return cache_value.vfs_object | python | def GetObject(self, identifier):
"""Retrieves a cached object based on the identifier.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
Returns:
object: cached VFS object or None if not cached.
"""
cache_value = self._values.get(identifier, None)
if not cache_value:
return None
return cache_value.vfs_object | [
"def",
"GetObject",
"(",
"self",
",",
"identifier",
")",
":",
"cache_value",
"=",
"self",
".",
"_values",
".",
"get",
"(",
"identifier",
",",
"None",
")",
"if",
"not",
"cache_value",
":",
"return",
"None",
"return",
"cache_value",
".",
"vfs_object"
] | Retrieves a cached object based on the identifier.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
Returns:
object: cached VFS object or None if not cached. | [
"Retrieves",
"a",
"cached",
"object",
"based",
"on",
"the",
"identifier",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L132-L147 | train | 208,298 |
log2timeline/dfvfs | dfvfs/resolver/cache.py | ObjectsCache.GrabObject | def GrabObject(self, identifier):
"""Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing.
"""
if identifier not in self._values:
raise KeyError('Missing cached object for identifier: {0:s}'.format(
identifier))
cache_value = self._values[identifier]
if not cache_value:
raise RuntimeError('Missing cache value for identifier: {0:s}'.format(
identifier))
cache_value.IncrementReferenceCount() | python | def GrabObject(self, identifier):
"""Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing.
"""
if identifier not in self._values:
raise KeyError('Missing cached object for identifier: {0:s}'.format(
identifier))
cache_value = self._values[identifier]
if not cache_value:
raise RuntimeError('Missing cache value for identifier: {0:s}'.format(
identifier))
cache_value.IncrementReferenceCount() | [
"def",
"GrabObject",
"(",
"self",
",",
"identifier",
")",
":",
"if",
"identifier",
"not",
"in",
"self",
".",
"_values",
":",
"raise",
"KeyError",
"(",
"'Missing cached object for identifier: {0:s}'",
".",
"format",
"(",
"identifier",
")",
")",
"cache_value",
"="... | Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing. | [
"Grabs",
"a",
"cached",
"object",
"based",
"on",
"the",
"identifier",
"."
] | 2b3ccd115f9901d89f383397d4a1376a873c83c4 | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L149-L170 | train | 208,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.