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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_whitelist_page | def get_whitelist_page(self, page_number=None, page_size=None):
"""
Gets a paginated list of indicators that the user's company has whitelisted.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: A |Page| of |Indicator| objects.
"""
params = {
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("whitelist", params=params)
return Page.from_dict(resp.json(), content_type=Indicator) | python | def get_whitelist_page(self, page_number=None, page_size=None):
"""
Gets a paginated list of indicators that the user's company has whitelisted.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: A |Page| of |Indicator| objects.
"""
params = {
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("whitelist", params=params)
return Page.from_dict(resp.json(), content_type=Indicator) | [
"def",
"get_whitelist_page",
"(",
"self",
",",
"page_number",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'pageNumber'",
":",
"page_number",
",",
"'pageSize'",
":",
"page_size",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
... | Gets a paginated list of indicators that the user's company has whitelisted.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: A |Page| of |Indicator| objects. | [
"Gets",
"a",
"paginated",
"list",
"of",
"indicators",
"that",
"the",
"user",
"s",
"company",
"has",
"whitelisted",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L401-L415 | train | 43,800 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient.get_related_indicators_page | def get_related_indicators_page(self, indicators=None, enclave_ids=None, page_size=None, page_number=None):
"""
Finds all reports that contain any of the given indicators and returns correlated indicators from those reports.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param page_size: number of results per page
:param page_number: page to start returning results on
:return: A |Page| of |Report| objects.
"""
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("indicators/related", params=params)
return Page.from_dict(resp.json(), content_type=Indicator) | python | def get_related_indicators_page(self, indicators=None, enclave_ids=None, page_size=None, page_number=None):
"""
Finds all reports that contain any of the given indicators and returns correlated indicators from those reports.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param page_size: number of results per page
:param page_number: page to start returning results on
:return: A |Page| of |Report| objects.
"""
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("indicators/related", params=params)
return Page.from_dict(resp.json(), content_type=Indicator) | [
"def",
"get_related_indicators_page",
"(",
"self",
",",
"indicators",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"page_number",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'indicators'",
":",
"indicators",
",",
"'enclav... | Finds all reports that contain any of the given indicators and returns correlated indicators from those reports.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param page_size: number of results per page
:param page_number: page to start returning results on
:return: A |Page| of |Report| objects. | [
"Finds",
"all",
"reports",
"that",
"contain",
"any",
"of",
"the",
"given",
"indicators",
"and",
"returns",
"correlated",
"indicators",
"from",
"those",
"reports",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L434-L454 | train | 43,801 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient._get_indicators_for_report_page_generator | def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.get_indicators_for_report_page, report_id=report_id)
return Page.get_page_generator(get_page, start_page, page_size) | python | def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.get_indicators_for_report_page, report_id=report_id)
return Page.get_page_generator(get_page, start_page, page_size) | [
"def",
"_get_indicators_for_report_page_generator",
"(",
"self",
",",
"report_id",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"get_page",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"get_indicators_for_report_page",
",",
"report_... | Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_indicators_for_report_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L456-L467 | train | 43,802 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient._get_related_indicators_page_generator | def _get_related_indicators_page_generator(self, indicators=None, enclave_ids=None, start_page=0, page_size=None):
"""
Creates a generator from the |get_related_indicators_page| method that returns each
successive page.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.get_related_indicators_page, indicators, enclave_ids)
return Page.get_page_generator(get_page, start_page, page_size) | python | def _get_related_indicators_page_generator(self, indicators=None, enclave_ids=None, start_page=0, page_size=None):
"""
Creates a generator from the |get_related_indicators_page| method that returns each
successive page.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.get_related_indicators_page, indicators, enclave_ids)
return Page.get_page_generator(get_page, start_page, page_size) | [
"def",
"_get_related_indicators_page_generator",
"(",
"self",
",",
"indicators",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"get_page",
"=",
"functools",
".",
"partial",
"(",
"self",
".... | Creates a generator from the |get_related_indicators_page| method that returns each
successive page.
:param indicators: list of indicator values to search for
:param enclave_ids: list of IDs of enclaves to search in
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_related_indicators_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L469-L482 | train | 43,803 |
trustar/trustar-python | trustar/indicator_client.py | IndicatorClient._get_whitelist_page_generator | def _get_whitelist_page_generator(self, start_page=0, page_size=None):
"""
Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator.
"""
return Page.get_page_generator(self.get_whitelist_page, start_page, page_size) | python | def _get_whitelist_page_generator(self, start_page=0, page_size=None):
"""
Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator.
"""
return Page.get_page_generator(self.get_whitelist_page, start_page, page_size) | [
"def",
"_get_whitelist_page_generator",
"(",
"self",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"Page",
".",
"get_page_generator",
"(",
"self",
".",
"get_whitelist_page",
",",
"start_page",
",",
"page_size",
")"
] | Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_whitelist_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/indicator_client.py#L484-L493 | train | 43,804 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.points | def points(self, size=1.0, highlight=None, colorlist=None, opacity=1.0):
"""Display the system as points.
:param float size: the size of the points.
"""
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
if highlight is not None:
if isinstance(highlight, int):
colorlist[highlight] = 0xff0000
if isinstance(highlight, (list, np.ndarray)):
for i in highlight:
colorlist[i] = 0xff0000
sizes = [size] * len(self.topology['atom_types'])
points = self.add_representation('points', {'coordinates': self.coordinates.astype('float32'),
'colors': colorlist,
'sizes': sizes,
'opacity': opacity})
# Update closure
def update(self=self, points=points):
self.update_representation(points, {'coordinates': self.coordinates.astype('float32')})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def points(self, size=1.0, highlight=None, colorlist=None, opacity=1.0):
"""Display the system as points.
:param float size: the size of the points.
"""
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
if highlight is not None:
if isinstance(highlight, int):
colorlist[highlight] = 0xff0000
if isinstance(highlight, (list, np.ndarray)):
for i in highlight:
colorlist[i] = 0xff0000
sizes = [size] * len(self.topology['atom_types'])
points = self.add_representation('points', {'coordinates': self.coordinates.astype('float32'),
'colors': colorlist,
'sizes': sizes,
'opacity': opacity})
# Update closure
def update(self=self, points=points):
self.update_representation(points, {'coordinates': self.coordinates.astype('float32')})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"points",
"(",
"self",
",",
"size",
"=",
"1.0",
",",
"highlight",
"=",
"None",
",",
"colorlist",
"=",
"None",
",",
"opacity",
"=",
"1.0",
")",
":",
"if",
"colorlist",
"is",
"None",
":",
"colorlist",
"=",
"[",
"get_atom_color",
"(",
"t",
")",
... | Display the system as points.
:param float size: the size of the points. | [
"Display",
"the",
"system",
"as",
"points",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L29-L56 | train | 43,805 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.labels | def labels(self, text=None, coordinates=None, colorlist=None, sizes=None, fonts=None, opacity=1.0):
'''Display atomic labels for the system'''
if coordinates is None:
coordinates=self.coordinates
l=len(coordinates)
if text is None:
if len(self.topology.get('atom_types'))==l:
text=[self.topology['atom_types'][i]+str(i+1) for i in range(l)]
else:
text=[str(i+1) for i in range(l)]
text_representation = self.add_representation('text', {'coordinates': coordinates,
'text': text,
'colors': colorlist,
'sizes': sizes,
'fonts': fonts,
'opacity': opacity})
def update(self=self, text_representation=text_representation):
self.update_representation(text_representation, {'coordinates': coordinates})
self.update_callbacks.append(update) | python | def labels(self, text=None, coordinates=None, colorlist=None, sizes=None, fonts=None, opacity=1.0):
'''Display atomic labels for the system'''
if coordinates is None:
coordinates=self.coordinates
l=len(coordinates)
if text is None:
if len(self.topology.get('atom_types'))==l:
text=[self.topology['atom_types'][i]+str(i+1) for i in range(l)]
else:
text=[str(i+1) for i in range(l)]
text_representation = self.add_representation('text', {'coordinates': coordinates,
'text': text,
'colors': colorlist,
'sizes': sizes,
'fonts': fonts,
'opacity': opacity})
def update(self=self, text_representation=text_representation):
self.update_representation(text_representation, {'coordinates': coordinates})
self.update_callbacks.append(update) | [
"def",
"labels",
"(",
"self",
",",
"text",
"=",
"None",
",",
"coordinates",
"=",
"None",
",",
"colorlist",
"=",
"None",
",",
"sizes",
"=",
"None",
",",
"fonts",
"=",
"None",
",",
"opacity",
"=",
"1.0",
")",
":",
"if",
"coordinates",
"is",
"None",
"... | Display atomic labels for the system | [
"Display",
"atomic",
"labels",
"for",
"the",
"system"
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L58-L78 | train | 43,806 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.remove_labels | def remove_labels(self):
'''Remove all atomic labels from the system'''
for rep_id in self.representations.keys():
if self.representations[rep_id]['rep_type']=='text' and rep_id not in self._axes_reps:
self.remove_representation(rep_id) | python | def remove_labels(self):
'''Remove all atomic labels from the system'''
for rep_id in self.representations.keys():
if self.representations[rep_id]['rep_type']=='text' and rep_id not in self._axes_reps:
self.remove_representation(rep_id) | [
"def",
"remove_labels",
"(",
"self",
")",
":",
"for",
"rep_id",
"in",
"self",
".",
"representations",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"representations",
"[",
"rep_id",
"]",
"[",
"'rep_type'",
"]",
"==",
"'text'",
"and",
"rep_id",
"not",
... | Remove all atomic labels from the system | [
"Remove",
"all",
"atomic",
"labels",
"from",
"the",
"system"
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L80-L84 | train | 43,807 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.lines | def lines(self):
'''Display the system bonds as lines.
'''
if "bonds" not in self.topology:
return
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
color_array = np.array([get_atom_color(t) for t in self.topology['atom_types']])
lines = self.add_representation('lines', {'startCoords': self.coordinates[bond_start],
'endCoords': self.coordinates[bond_end],
'startColors': color_array[bond_start].tolist(),
'endColors': color_array[bond_end].tolist()})
def update(self=self, lines=lines):
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
self.update_representation(lines, {'startCoords': self.coordinates[bond_start],
'endCoords': self.coordinates[bond_end]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def lines(self):
'''Display the system bonds as lines.
'''
if "bonds" not in self.topology:
return
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
color_array = np.array([get_atom_color(t) for t in self.topology['atom_types']])
lines = self.add_representation('lines', {'startCoords': self.coordinates[bond_start],
'endCoords': self.coordinates[bond_end],
'startColors': color_array[bond_start].tolist(),
'endColors': color_array[bond_end].tolist()})
def update(self=self, lines=lines):
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
self.update_representation(lines, {'startCoords': self.coordinates[bond_start],
'endCoords': self.coordinates[bond_end]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"lines",
"(",
"self",
")",
":",
"if",
"\"bonds\"",
"not",
"in",
"self",
".",
"topology",
":",
"return",
"bond_start",
",",
"bond_end",
"=",
"zip",
"(",
"*",
"self",
".",
"topology",
"[",
"'bonds'",
"]",
")",
"bond_start",
"=",
"np",
".",
"arra... | Display the system bonds as lines. | [
"Display",
"the",
"system",
"bonds",
"as",
"lines",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L151-L176 | train | 43,808 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.ball_and_sticks | def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
"""Display the system using a ball and stick representation.
"""
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
sizes = [ball_radius] * len(self.topology['atom_types'])
spheres = self.add_representation('spheres', {'coordinates': self.coordinates.astype('float32'),
'colors': colorlist,
'radii': sizes,
'opacity': opacity})
def update(self=self, spheres=spheres):
self.update_representation(spheres, {'coordinates': self.coordinates.astype('float32')})
self.update_callbacks.append(update)
# Add the cylinders
if 'bonds' in self.topology and self.topology['bonds'] is not None:
start_idx, end_idx = zip(*self.topology['bonds'])
# Added this so bonds don't go through atoms when opacity<1.0
new_start_coords = []
new_end_coords = []
for bond_ind, bond in enumerate(self.topology['bonds']):
trim_amt = (ball_radius**2 - stick_radius**2)**0.5 if ball_radius>stick_radius else 0
start_coord = self.coordinates[bond[0]]
end_coord = self.coordinates[bond[1]]
vec = (end_coord-start_coord)/np.linalg.norm(end_coord-start_coord)
new_start_coords.append(start_coord+vec*trim_amt)
new_end_coords.append(end_coord-vec*trim_amt)
cylinders = self.add_representation('cylinders', {'startCoords': np.array(new_start_coords,dtype='float32'),
'endCoords': np.array(new_end_coords,dtype='float32'),
'colors': [0xcccccc] * len(new_start_coords),
'radii': [stick_radius] * len(new_start_coords),
'opacity': opacity})
# Update closure
def update(self=self, rep=cylinders, start_idx=start_idx, end_idx=end_idx):
self.update_representation(rep, {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
"""Display the system using a ball and stick representation.
"""
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
sizes = [ball_radius] * len(self.topology['atom_types'])
spheres = self.add_representation('spheres', {'coordinates': self.coordinates.astype('float32'),
'colors': colorlist,
'radii': sizes,
'opacity': opacity})
def update(self=self, spheres=spheres):
self.update_representation(spheres, {'coordinates': self.coordinates.astype('float32')})
self.update_callbacks.append(update)
# Add the cylinders
if 'bonds' in self.topology and self.topology['bonds'] is not None:
start_idx, end_idx = zip(*self.topology['bonds'])
# Added this so bonds don't go through atoms when opacity<1.0
new_start_coords = []
new_end_coords = []
for bond_ind, bond in enumerate(self.topology['bonds']):
trim_amt = (ball_radius**2 - stick_radius**2)**0.5 if ball_radius>stick_radius else 0
start_coord = self.coordinates[bond[0]]
end_coord = self.coordinates[bond[1]]
vec = (end_coord-start_coord)/np.linalg.norm(end_coord-start_coord)
new_start_coords.append(start_coord+vec*trim_amt)
new_end_coords.append(end_coord-vec*trim_amt)
cylinders = self.add_representation('cylinders', {'startCoords': np.array(new_start_coords,dtype='float32'),
'endCoords': np.array(new_end_coords,dtype='float32'),
'colors': [0xcccccc] * len(new_start_coords),
'radii': [stick_radius] * len(new_start_coords),
'opacity': opacity})
# Update closure
def update(self=self, rep=cylinders, start_idx=start_idx, end_idx=end_idx):
self.update_representation(rep, {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"ball_and_sticks",
"(",
"self",
",",
"ball_radius",
"=",
"0.05",
",",
"stick_radius",
"=",
"0.02",
",",
"colorlist",
"=",
"None",
",",
"opacity",
"=",
"1.0",
")",
":",
"# Add the spheres",
"if",
"colorlist",
"is",
"None",
":",
"colorlist",
"=",
"[",... | Display the system using a ball and stick representation. | [
"Display",
"the",
"system",
"using",
"a",
"ball",
"and",
"stick",
"representation",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L183-L229 | train | 43,809 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.line_ribbon | def line_ribbon(self):
'''Display the protein secondary structure as a white lines that passes through the
backbone chain.
'''
# Control points are the CA (C alphas)
backbone = np.array(self.topology['atom_names']) == 'CA'
smoothline = self.add_representation('smoothline', {'coordinates': self.coordinates[backbone],
'color': 0xffffff})
def update(self=self, smoothline=smoothline):
self.update_representation(smoothline, {'coordinates': self.coordinates[backbone]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def line_ribbon(self):
'''Display the protein secondary structure as a white lines that passes through the
backbone chain.
'''
# Control points are the CA (C alphas)
backbone = np.array(self.topology['atom_names']) == 'CA'
smoothline = self.add_representation('smoothline', {'coordinates': self.coordinates[backbone],
'color': 0xffffff})
def update(self=self, smoothline=smoothline):
self.update_representation(smoothline, {'coordinates': self.coordinates[backbone]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"line_ribbon",
"(",
"self",
")",
":",
"# Control points are the CA (C alphas)",
"backbone",
"=",
"np",
".",
"array",
"(",
"self",
".",
"topology",
"[",
"'atom_names'",
"]",
")",
"==",
"'CA'",
"smoothline",
"=",
"self",
".",
"add_representation",
"(",
"'... | Display the protein secondary structure as a white lines that passes through the
backbone chain. | [
"Display",
"the",
"protein",
"secondary",
"structure",
"as",
"a",
"white",
"lines",
"that",
"passes",
"through",
"the",
"backbone",
"chain",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L231-L245 | train | 43,810 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.cylinder_and_strand | def cylinder_and_strand(self):
'''Display the protein secondary structure as a white,
solid tube and the alpha-helices as yellow cylinders.
'''
top = self.topology
# We build a mini-state machine to find the
# start end of helices and such
in_helix = False
helices_starts = []
helices_ends = []
coils = []
coil = []
for i, typ in enumerate(top['secondary_structure']):
if typ == 'H':
if in_helix == False:
# We become helices
helices_starts.append(top['residue_indices'][i][0])
in_helix = True
# We end the previous coil
coil.append(top['residue_indices'][i][0])
else:
if in_helix == True:
# We stop being helices
helices_ends.append(top['residue_indices'][i][0])
# We start a new coil
coil = []
coils.append(coil)
in_helix = False
# We add control points
coil.append(top['residue_indices'][i][0])
[coil.append(j) for j in top['residue_indices'][i] if top['atom_names'][j] == 'CA']
# We add the coils
coil_representations = []
for control_points in coils:
rid = self.add_representation('smoothtube', {'coordinates': self.coordinates[control_points],
'radius': 0.05,
'resolution': 4,
'color': 0xffffff})
coil_representations.append(rid)
start_idx, end_idx = helices_starts, helices_ends
cylinders = self.add_representation('cylinders', {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)],
'colors': [0xffff00] * len(self.coordinates),
'radii': [0.15] * len(self.coordinates)})
def update(self=self, cylinders=cylinders, coils=coils,
coil_representations=coil_representations,
start_idx=start_idx, end_idx=end_idx, control_points=control_points):
for i, control_points in enumerate(coils):
rid = self.update_representation(coil_representations[i],
{'coordinates': self.coordinates[control_points]})
self.update_representation(cylinders, {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def cylinder_and_strand(self):
'''Display the protein secondary structure as a white,
solid tube and the alpha-helices as yellow cylinders.
'''
top = self.topology
# We build a mini-state machine to find the
# start end of helices and such
in_helix = False
helices_starts = []
helices_ends = []
coils = []
coil = []
for i, typ in enumerate(top['secondary_structure']):
if typ == 'H':
if in_helix == False:
# We become helices
helices_starts.append(top['residue_indices'][i][0])
in_helix = True
# We end the previous coil
coil.append(top['residue_indices'][i][0])
else:
if in_helix == True:
# We stop being helices
helices_ends.append(top['residue_indices'][i][0])
# We start a new coil
coil = []
coils.append(coil)
in_helix = False
# We add control points
coil.append(top['residue_indices'][i][0])
[coil.append(j) for j in top['residue_indices'][i] if top['atom_names'][j] == 'CA']
# We add the coils
coil_representations = []
for control_points in coils:
rid = self.add_representation('smoothtube', {'coordinates': self.coordinates[control_points],
'radius': 0.05,
'resolution': 4,
'color': 0xffffff})
coil_representations.append(rid)
start_idx, end_idx = helices_starts, helices_ends
cylinders = self.add_representation('cylinders', {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)],
'colors': [0xffff00] * len(self.coordinates),
'radii': [0.15] * len(self.coordinates)})
def update(self=self, cylinders=cylinders, coils=coils,
coil_representations=coil_representations,
start_idx=start_idx, end_idx=end_idx, control_points=control_points):
for i, control_points in enumerate(coils):
rid = self.update_representation(coil_representations[i],
{'coordinates': self.coordinates[control_points]})
self.update_representation(cylinders, {'startCoords': self.coordinates[list(start_idx)],
'endCoords': self.coordinates[list(end_idx)]})
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"cylinder_and_strand",
"(",
"self",
")",
":",
"top",
"=",
"self",
".",
"topology",
"# We build a mini-state machine to find the",
"# start end of helices and such",
"in_helix",
"=",
"False",
"helices_starts",
"=",
"[",
"]",
"helices_ends",
"=",
"[",
"]",
"coil... | Display the protein secondary structure as a white,
solid tube and the alpha-helices as yellow cylinders. | [
"Display",
"the",
"protein",
"secondary",
"structure",
"as",
"a",
"white",
"solid",
"tube",
"and",
"the",
"alpha",
"-",
"helices",
"as",
"yellow",
"cylinders",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L247-L310 | train | 43,811 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.cartoon | def cartoon(self, cmap=None):
'''Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white)
'''
# Parse secondary structure
top = self.topology
geom = gg.GeomProteinCartoon(gg.Aes(xyz=self.coordinates,
types=top['atom_names'],
secondary_type=top['secondary_structure']),
cmap=cmap)
primitives = geom.produce(gg.Aes())
ids = [self.add_representation(r['rep_type'], r['options']) for r in primitives]
def update(self=self, geom=geom, ids=ids):
primitives = geom.produce(gg.Aes(xyz=self.coordinates))
[self.update_representation(id_, rep_options)
for id_, rep_options in zip(ids, primitives)]
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | python | def cartoon(self, cmap=None):
'''Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white)
'''
# Parse secondary structure
top = self.topology
geom = gg.GeomProteinCartoon(gg.Aes(xyz=self.coordinates,
types=top['atom_names'],
secondary_type=top['secondary_structure']),
cmap=cmap)
primitives = geom.produce(gg.Aes())
ids = [self.add_representation(r['rep_type'], r['options']) for r in primitives]
def update(self=self, geom=geom, ids=ids):
primitives = geom.produce(gg.Aes(xyz=self.coordinates))
[self.update_representation(id_, rep_options)
for id_, rep_options in zip(ids, primitives)]
self.update_callbacks.append(update)
self.autozoom(self.coordinates) | [
"def",
"cartoon",
"(",
"self",
",",
"cmap",
"=",
"None",
")",
":",
"# Parse secondary structure",
"top",
"=",
"self",
".",
"topology",
"geom",
"=",
"gg",
".",
"GeomProteinCartoon",
"(",
"gg",
".",
"Aes",
"(",
"xyz",
"=",
"self",
".",
"coordinates",
",",
... | Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white) | [
"Display",
"a",
"protein",
"secondary",
"structure",
"as",
"a",
"pymol",
"-",
"like",
"cartoon",
"representation",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L312-L335 | train | 43,812 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.add_isosurface | def add_isosurface(self, function, isolevel=0.3, resolution=32, style="wireframe", color=0xffffff):
'''Add an isosurface to the current scene.
:param callable function: A function that takes x, y, z coordinates as input and is broadcastable using numpy. Typically simple
functions that involve standard arithmetic operations and functions
such as ``x**2 + y**2 + z**2`` or ``np.exp(x**2 + y**2 + z**2)`` will work. If not sure, you can first
pass the function through ``numpy.vectorize``.\
Example: ``mv.add_isosurface(np.vectorize(f))``
:param float isolevel: The value for which the function should be constant.
:param int resolution: The number of grid point to use for the surface. An high value will give better quality but lower performance.
:param str style: The surface style, choose between ``solid``, ``wireframe`` and ``transparent``.
:param int color: The color given as an hexadecimal integer. Example: ``0xffffff`` is white.
'''
avail_styles = ['wireframe', 'solid', 'transparent']
if style not in avail_styles:
raise ValueError('style must be in ' + str(avail_styles))
# We want to make a container that contains the whole molecule
# and surface
area_min = self.coordinates.min(axis=0) - 0.2
area_max = self.coordinates.max(axis=0) + 0.2
x = np.linspace(area_min[0], area_max[0], resolution)
y = np.linspace(area_min[1], area_max[1], resolution)
z = np.linspace(area_min[2], area_max[2], resolution)
xv, yv, zv = np.meshgrid(x, y, z)
spacing = np.array((area_max - area_min)/resolution)
if isolevel >= 0:
triangles = marching_cubes(function(xv, yv, zv), isolevel)
else: # Wrong traingle unwinding roder -- god only knows why
triangles = marching_cubes(-function(xv, yv, zv), -isolevel)
if len(triangles) == 0:
## NO surface
return
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = area_min + spacing/2 + np.array(verts)*spacing
rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),
'faces': faces.astype('int32'),
'style': style,
'color': color})
self.autozoom(verts) | python | def add_isosurface(self, function, isolevel=0.3, resolution=32, style="wireframe", color=0xffffff):
'''Add an isosurface to the current scene.
:param callable function: A function that takes x, y, z coordinates as input and is broadcastable using numpy. Typically simple
functions that involve standard arithmetic operations and functions
such as ``x**2 + y**2 + z**2`` or ``np.exp(x**2 + y**2 + z**2)`` will work. If not sure, you can first
pass the function through ``numpy.vectorize``.\
Example: ``mv.add_isosurface(np.vectorize(f))``
:param float isolevel: The value for which the function should be constant.
:param int resolution: The number of grid point to use for the surface. An high value will give better quality but lower performance.
:param str style: The surface style, choose between ``solid``, ``wireframe`` and ``transparent``.
:param int color: The color given as an hexadecimal integer. Example: ``0xffffff`` is white.
'''
avail_styles = ['wireframe', 'solid', 'transparent']
if style not in avail_styles:
raise ValueError('style must be in ' + str(avail_styles))
# We want to make a container that contains the whole molecule
# and surface
area_min = self.coordinates.min(axis=0) - 0.2
area_max = self.coordinates.max(axis=0) + 0.2
x = np.linspace(area_min[0], area_max[0], resolution)
y = np.linspace(area_min[1], area_max[1], resolution)
z = np.linspace(area_min[2], area_max[2], resolution)
xv, yv, zv = np.meshgrid(x, y, z)
spacing = np.array((area_max - area_min)/resolution)
if isolevel >= 0:
triangles = marching_cubes(function(xv, yv, zv), isolevel)
else: # Wrong traingle unwinding roder -- god only knows why
triangles = marching_cubes(-function(xv, yv, zv), -isolevel)
if len(triangles) == 0:
## NO surface
return
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = area_min + spacing/2 + np.array(verts)*spacing
rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),
'faces': faces.astype('int32'),
'style': style,
'color': color})
self.autozoom(verts) | [
"def",
"add_isosurface",
"(",
"self",
",",
"function",
",",
"isolevel",
"=",
"0.3",
",",
"resolution",
"=",
"32",
",",
"style",
"=",
"\"wireframe\"",
",",
"color",
"=",
"0xffffff",
")",
":",
"avail_styles",
"=",
"[",
"'wireframe'",
",",
"'solid'",
",",
"... | Add an isosurface to the current scene.
:param callable function: A function that takes x, y, z coordinates as input and is broadcastable using numpy. Typically simple
functions that involve standard arithmetic operations and functions
such as ``x**2 + y**2 + z**2`` or ``np.exp(x**2 + y**2 + z**2)`` will work. If not sure, you can first
pass the function through ``numpy.vectorize``.\
Example: ``mv.add_isosurface(np.vectorize(f))``
:param float isolevel: The value for which the function should be constant.
:param int resolution: The number of grid point to use for the surface. An high value will give better quality but lower performance.
:param str style: The surface style, choose between ``solid``, ``wireframe`` and ``transparent``.
:param int color: The color given as an hexadecimal integer. Example: ``0xffffff`` is white. | [
"Add",
"an",
"isosurface",
"to",
"the",
"current",
"scene",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L340-L393 | train | 43,813 |
gabrielelanaro/chemview | chemview/viewer.py | MolecularViewer.add_isosurface_grid_data | def add_isosurface_grid_data(self, data, origin, extent, resolution,
isolevel=0.3, scale=10,
style="wireframe", color=0xffffff):
"""
Add an isosurface to current scence using pre-computed data on a grid
"""
spacing = np.array(extent/resolution)/scale
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else:
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = origin + spacing/2 + np.array(verts)*spacing
rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),
'faces': faces.astype('int32'),
'style': style,
'color': color})
self.autozoom(verts) | python | def add_isosurface_grid_data(self, data, origin, extent, resolution,
isolevel=0.3, scale=10,
style="wireframe", color=0xffffff):
"""
Add an isosurface to current scence using pre-computed data on a grid
"""
spacing = np.array(extent/resolution)/scale
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else:
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = origin + spacing/2 + np.array(verts)*spacing
rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),
'faces': faces.astype('int32'),
'style': style,
'color': color})
self.autozoom(verts) | [
"def",
"add_isosurface_grid_data",
"(",
"self",
",",
"data",
",",
"origin",
",",
"extent",
",",
"resolution",
",",
"isolevel",
"=",
"0.3",
",",
"scale",
"=",
"10",
",",
"style",
"=",
"\"wireframe\"",
",",
"color",
"=",
"0xffffff",
")",
":",
"spacing",
"=... | Add an isosurface to current scence using pre-computed data on a grid | [
"Add",
"an",
"isosurface",
"to",
"current",
"scence",
"using",
"pre",
"-",
"computed",
"data",
"on",
"a",
"grid"
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L395-L418 | train | 43,814 |
trustar/trustar-python | trustar/api_client.py | ApiClient._refresh_token | def _refresh_token(self):
"""
Retrieves the OAuth2 token generated by the user's API key and API secret.
Sets the instance property 'token' to this new token.
If the current token is still live, the server will simply return that.
"""
# use basic auth with API key and secret
client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)
# make request
post_data = {"grant_type": "client_credentials"}
response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
self.last_response = response
# raise exception if status code indicates an error
if 400 <= response.status_code < 600:
message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
"Client" if response.status_code < 500 else "Server",
self._get_trace_id(response),
"unable to get token")
raise HTTPError(message, response=response)
# set token property to the received token
self.token = response.json()["access_token"] | python | def _refresh_token(self):
"""
Retrieves the OAuth2 token generated by the user's API key and API secret.
Sets the instance property 'token' to this new token.
If the current token is still live, the server will simply return that.
"""
# use basic auth with API key and secret
client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)
# make request
post_data = {"grant_type": "client_credentials"}
response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
self.last_response = response
# raise exception if status code indicates an error
if 400 <= response.status_code < 600:
message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
"Client" if response.status_code < 500 else "Server",
self._get_trace_id(response),
"unable to get token")
raise HTTPError(message, response=response)
# set token property to the received token
self.token = response.json()["access_token"] | [
"def",
"_refresh_token",
"(",
"self",
")",
":",
"# use basic auth with API key and secret",
"client_auth",
"=",
"requests",
".",
"auth",
".",
"HTTPBasicAuth",
"(",
"self",
".",
"api_key",
",",
"self",
".",
"api_secret",
")",
"# make request",
"post_data",
"=",
"{"... | Retrieves the OAuth2 token generated by the user's API key and API secret.
Sets the instance property 'token' to this new token.
If the current token is still live, the server will simply return that. | [
"Retrieves",
"the",
"OAuth2",
"token",
"generated",
"by",
"the",
"user",
"s",
"API",
"key",
"and",
"API",
"secret",
".",
"Sets",
"the",
"instance",
"property",
"token",
"to",
"this",
"new",
"token",
".",
"If",
"the",
"current",
"token",
"is",
"still",
"l... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/api_client.py#L97-L121 | train | 43,815 |
trustar/trustar-python | trustar/api_client.py | ApiClient._get_headers | def _get_headers(self, is_json=False):
"""
Create headers dictionary for a request.
:param boolean is_json: Whether the request body is a json.
:return: The headers dictionary.
"""
headers = {"Authorization": "Bearer " + self._get_token()}
if self.client_type is not None:
headers["Client-Type"] = self.client_type
if self.client_version is not None:
headers["Client-Version"] = self.client_version
if self.client_metatag is not None:
headers["Client-Metatag"] = self.client_metatag
if is_json:
headers['Content-Type'] = 'application/json'
return headers | python | def _get_headers(self, is_json=False):
"""
Create headers dictionary for a request.
:param boolean is_json: Whether the request body is a json.
:return: The headers dictionary.
"""
headers = {"Authorization": "Bearer " + self._get_token()}
if self.client_type is not None:
headers["Client-Type"] = self.client_type
if self.client_version is not None:
headers["Client-Version"] = self.client_version
if self.client_metatag is not None:
headers["Client-Metatag"] = self.client_metatag
if is_json:
headers['Content-Type'] = 'application/json'
return headers | [
"def",
"_get_headers",
"(",
"self",
",",
"is_json",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer \"",
"+",
"self",
".",
"_get_token",
"(",
")",
"}",
"if",
"self",
".",
"client_type",
"is",
"not",
"None",
":",
"headers"... | Create headers dictionary for a request.
:param boolean is_json: Whether the request body is a json.
:return: The headers dictionary. | [
"Create",
"headers",
"dictionary",
"for",
"a",
"request",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/api_client.py#L123-L145 | train | 43,816 |
trustar/trustar-python | trustar/api_client.py | ApiClient._is_expired_token_response | def _is_expired_token_response(cls, response):
"""
Determine whether the given response indicates that the token is expired.
:param response: The response object.
:return: True if the response indicates that the token is expired.
"""
EXPIRED_MESSAGE = "Expired oauth2 access token"
INVALID_MESSAGE = "Invalid oauth2 access token"
if response.status_code == 400:
try:
body = response.json()
if str(body.get('error_description')) in [EXPIRED_MESSAGE, INVALID_MESSAGE]:
return True
except:
pass
return False | python | def _is_expired_token_response(cls, response):
"""
Determine whether the given response indicates that the token is expired.
:param response: The response object.
:return: True if the response indicates that the token is expired.
"""
EXPIRED_MESSAGE = "Expired oauth2 access token"
INVALID_MESSAGE = "Invalid oauth2 access token"
if response.status_code == 400:
try:
body = response.json()
if str(body.get('error_description')) in [EXPIRED_MESSAGE, INVALID_MESSAGE]:
return True
except:
pass
return False | [
"def",
"_is_expired_token_response",
"(",
"cls",
",",
"response",
")",
":",
"EXPIRED_MESSAGE",
"=",
"\"Expired oauth2 access token\"",
"INVALID_MESSAGE",
"=",
"\"Invalid oauth2 access token\"",
"if",
"response",
".",
"status_code",
"==",
"400",
":",
"try",
":",
"body",
... | Determine whether the given response indicates that the token is expired.
:param response: The response object.
:return: True if the response indicates that the token is expired. | [
"Determine",
"whether",
"the",
"given",
"response",
"indicates",
"that",
"the",
"token",
"is",
"expired",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/api_client.py#L148-L166 | train | 43,817 |
trustar/trustar-python | trustar/api_client.py | ApiClient.request | def request(self, method, path, headers=None, params=None, data=None, **kwargs):
"""
A wrapper around ``requests.request`` that handles boilerplate code specific to TruStar's API.
:param str method: The method of the request (``GET``, ``PUT``, ``POST``, or ``DELETE``)
:param str path: The path of the request, i.e. the piece of the URL after the base URL
:param dict headers: A dictionary of headers that will be merged with the base headers for the SDK
:param kwargs: Any extra keyword arguments. These will be forwarded to the call to ``requests.request``.
:return: The response object.
"""
retry = self.retry
attempted = False
while not attempted or retry:
# get headers and merge with headers from method parameter if it exists
base_headers = self._get_headers(is_json=method in ["POST", "PUT"])
if headers is not None:
base_headers.update(headers)
url = "{}/{}".format(self.base, path)
# make request
response = requests.request(method=method,
url=url,
headers=base_headers,
verify=self.verify,
params=params,
data=data,
proxies=self.proxies,
**kwargs)
self.last_response = response
attempted = True
# log request
self.logger.debug("%s %s. Trace-Id: %s. Params: %s", method, url, response.headers.get('Trace-Id'), params)
# refresh token if expired
if self._is_expired_token_response(response):
self._refresh_token()
# if "too many requests" status code received, wait until next request will be allowed and retry
elif retry and response.status_code == 429:
wait_time = ceil(response.json().get('waitTime') / 1000)
self.logger.debug("Waiting %d seconds until next request allowed." % wait_time)
# if wait time exceeds max wait time, allow the exception to be thrown
if wait_time <= self.max_wait_time:
time.sleep(wait_time)
else:
retry = False
# request cycle is complete
else:
retry = False
# raise exception if status code indicates an error
if 400 <= response.status_code < 600:
# get response json body, if one exists
resp_json = None
try:
resp_json = response.json()
except:
pass
# get message from json body, if one exists
if resp_json is not None and 'message' in resp_json:
reason = resp_json['message']
else:
reason = "unknown cause"
# construct error message
message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
"Client" if response.status_code < 500 else "Server",
self._get_trace_id(response),
reason)
# raise HTTPError
raise HTTPError(message, response=response)
return response | python | def request(self, method, path, headers=None, params=None, data=None, **kwargs):
"""
A wrapper around ``requests.request`` that handles boilerplate code specific to TruStar's API.
:param str method: The method of the request (``GET``, ``PUT``, ``POST``, or ``DELETE``)
:param str path: The path of the request, i.e. the piece of the URL after the base URL
:param dict headers: A dictionary of headers that will be merged with the base headers for the SDK
:param kwargs: Any extra keyword arguments. These will be forwarded to the call to ``requests.request``.
:return: The response object.
"""
retry = self.retry
attempted = False
while not attempted or retry:
# get headers and merge with headers from method parameter if it exists
base_headers = self._get_headers(is_json=method in ["POST", "PUT"])
if headers is not None:
base_headers.update(headers)
url = "{}/{}".format(self.base, path)
# make request
response = requests.request(method=method,
url=url,
headers=base_headers,
verify=self.verify,
params=params,
data=data,
proxies=self.proxies,
**kwargs)
self.last_response = response
attempted = True
# log request
self.logger.debug("%s %s. Trace-Id: %s. Params: %s", method, url, response.headers.get('Trace-Id'), params)
# refresh token if expired
if self._is_expired_token_response(response):
self._refresh_token()
# if "too many requests" status code received, wait until next request will be allowed and retry
elif retry and response.status_code == 429:
wait_time = ceil(response.json().get('waitTime') / 1000)
self.logger.debug("Waiting %d seconds until next request allowed." % wait_time)
# if wait time exceeds max wait time, allow the exception to be thrown
if wait_time <= self.max_wait_time:
time.sleep(wait_time)
else:
retry = False
# request cycle is complete
else:
retry = False
# raise exception if status code indicates an error
if 400 <= response.status_code < 600:
# get response json body, if one exists
resp_json = None
try:
resp_json = response.json()
except:
pass
# get message from json body, if one exists
if resp_json is not None and 'message' in resp_json:
reason = resp_json['message']
else:
reason = "unknown cause"
# construct error message
message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
"Client" if response.status_code < 500 else "Server",
self._get_trace_id(response),
reason)
# raise HTTPError
raise HTTPError(message, response=response)
return response | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"path",
",",
"headers",
"=",
"None",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retry",
"=",
"self",
".",
"retry",
"attempted",
"=",
"False",
"while",... | A wrapper around ``requests.request`` that handles boilerplate code specific to TruStar's API.
:param str method: The method of the request (``GET``, ``PUT``, ``POST``, or ``DELETE``)
:param str path: The path of the request, i.e. the piece of the URL after the base URL
:param dict headers: A dictionary of headers that will be merged with the base headers for the SDK
:param kwargs: Any extra keyword arguments. These will be forwarded to the call to ``requests.request``.
:return: The response object. | [
"A",
"wrapper",
"around",
"requests",
".",
"request",
"that",
"handles",
"boilerplate",
"code",
"specific",
"to",
"TruStar",
"s",
"API",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/api_client.py#L168-L248 | train | 43,818 |
gabrielelanaro/chemview | chemview/marchingcubes.py | isosurface_from_data | def isosurface_from_data(data, isolevel, origin, spacing):
"""Small wrapper to get directly vertices and faces to feed into programs
"""
spacing = np.array(extent/resolution)
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else: # Wrong traingle unwinding roder -- god only knows why
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = origin + spacing/2 + np.array(verts)*spacing
return verts, faces | python | def isosurface_from_data(data, isolevel, origin, spacing):
"""Small wrapper to get directly vertices and faces to feed into programs
"""
spacing = np.array(extent/resolution)
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else: # Wrong traingle unwinding roder -- god only knows why
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i * 3, i * 3 +1, i * 3 + 2])
verts.extend(t)
faces = np.array(faces)
verts = origin + spacing/2 + np.array(verts)*spacing
return verts, faces | [
"def",
"isosurface_from_data",
"(",
"data",
",",
"isolevel",
",",
"origin",
",",
"spacing",
")",
":",
"spacing",
"=",
"np",
".",
"array",
"(",
"extent",
"/",
"resolution",
")",
"if",
"isolevel",
">=",
"0",
":",
"triangles",
"=",
"marching_cubes",
"(",
"d... | Small wrapper to get directly vertices and faces to feed into programs | [
"Small",
"wrapper",
"to",
"get",
"directly",
"vertices",
"and",
"faces",
"to",
"feed",
"into",
"programs"
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/marchingcubes.py#L28-L44 | train | 43,819 |
openvax/topiary | topiary/rna/gtf.py | _get_gtf_column | def _get_gtf_column(column_name, gtf_path, df):
"""
Helper function which returns a dictionary column or raises an ValueError
abou the absence of that column in a GTF file.
"""
if column_name in df.columns:
return list(df[column_name])
else:
raise ValueError(
"Missing '%s' in columns of %s, available: %s" % (
column_name,
gtf_path,
list(df.columns))) | python | def _get_gtf_column(column_name, gtf_path, df):
"""
Helper function which returns a dictionary column or raises an ValueError
abou the absence of that column in a GTF file.
"""
if column_name in df.columns:
return list(df[column_name])
else:
raise ValueError(
"Missing '%s' in columns of %s, available: %s" % (
column_name,
gtf_path,
list(df.columns))) | [
"def",
"_get_gtf_column",
"(",
"column_name",
",",
"gtf_path",
",",
"df",
")",
":",
"if",
"column_name",
"in",
"df",
".",
"columns",
":",
"return",
"list",
"(",
"df",
"[",
"column_name",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Missing '%s' in... | Helper function which returns a dictionary column or raises an ValueError
abou the absence of that column in a GTF file. | [
"Helper",
"function",
"which",
"returns",
"a",
"dictionary",
"column",
"or",
"raises",
"an",
"ValueError",
"abou",
"the",
"absence",
"of",
"that",
"column",
"in",
"a",
"GTF",
"file",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/gtf.py#L22-L35 | train | 43,820 |
openvax/topiary | topiary/rna/gtf.py | load_transcript_fpkm_dict_from_gtf | def load_transcript_fpkm_dict_from_gtf(
gtf_path,
transcript_id_column_name="reference_id",
fpkm_column_name="FPKM",
feature_column_name="feature"):
"""
Load a GTF file generated by StringTie which contains transcript-level
quantification of abundance. Returns a dictionary mapping Ensembl
IDs of transcripts to FPKM values.
"""
df = gtfparse.read_gtf(
gtf_path,
column_converters={fpkm_column_name: float})
transcript_ids = _get_gtf_column(transcript_id_column_name, gtf_path, df)
fpkm_values = _get_gtf_column(fpkm_column_name, gtf_path, df)
features = _get_gtf_column(feature_column_name, gtf_path, df)
logging.info("Loaded %d rows from %s" % (len(transcript_ids), gtf_path))
logging.info("Found %s transcript entries" % sum(
feature == "transcript" for feature in features))
result = {
transcript_id: float(fpkm)
for (transcript_id, fpkm, feature)
in zip(transcript_ids, fpkm_values, features)
if (
(transcript_id is not None) and
(len(transcript_id) > 0) and
(feature == "transcript")
)
}
logging.info("Keeping %d transcript rows with reference IDs" % (
len(result),))
return result | python | def load_transcript_fpkm_dict_from_gtf(
gtf_path,
transcript_id_column_name="reference_id",
fpkm_column_name="FPKM",
feature_column_name="feature"):
"""
Load a GTF file generated by StringTie which contains transcript-level
quantification of abundance. Returns a dictionary mapping Ensembl
IDs of transcripts to FPKM values.
"""
df = gtfparse.read_gtf(
gtf_path,
column_converters={fpkm_column_name: float})
transcript_ids = _get_gtf_column(transcript_id_column_name, gtf_path, df)
fpkm_values = _get_gtf_column(fpkm_column_name, gtf_path, df)
features = _get_gtf_column(feature_column_name, gtf_path, df)
logging.info("Loaded %d rows from %s" % (len(transcript_ids), gtf_path))
logging.info("Found %s transcript entries" % sum(
feature == "transcript" for feature in features))
result = {
transcript_id: float(fpkm)
for (transcript_id, fpkm, feature)
in zip(transcript_ids, fpkm_values, features)
if (
(transcript_id is not None) and
(len(transcript_id) > 0) and
(feature == "transcript")
)
}
logging.info("Keeping %d transcript rows with reference IDs" % (
len(result),))
return result | [
"def",
"load_transcript_fpkm_dict_from_gtf",
"(",
"gtf_path",
",",
"transcript_id_column_name",
"=",
"\"reference_id\"",
",",
"fpkm_column_name",
"=",
"\"FPKM\"",
",",
"feature_column_name",
"=",
"\"feature\"",
")",
":",
"df",
"=",
"gtfparse",
".",
"read_gtf",
"(",
"g... | Load a GTF file generated by StringTie which contains transcript-level
quantification of abundance. Returns a dictionary mapping Ensembl
IDs of transcripts to FPKM values. | [
"Load",
"a",
"GTF",
"file",
"generated",
"by",
"StringTie",
"which",
"contains",
"transcript",
"-",
"level",
"quantification",
"of",
"abundance",
".",
"Returns",
"a",
"dictionary",
"mapping",
"Ensembl",
"IDs",
"of",
"transcripts",
"to",
"FPKM",
"values",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/gtf.py#L37-L68 | train | 43,821 |
openvax/topiary | topiary/predictor.py | TopiaryPredictor.predict_from_sequences | def predict_from_sequences(self, sequences):
"""
Predict MHC ligands for sub-sequences of each input sequence.
Parameters
----------
sequences : list of str
Multiple amino acid sequences (without any names or IDs)
Returns DataFrame with the following fields:
- source_sequence
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name
"""
# make each sequence its own unique ID
sequence_dict = {
seq: seq
for seq in sequences
}
df = self.predict_from_named_sequences(sequence_dict)
return df.rename(columns={"source_sequence_name": "source_sequence"}) | python | def predict_from_sequences(self, sequences):
"""
Predict MHC ligands for sub-sequences of each input sequence.
Parameters
----------
sequences : list of str
Multiple amino acid sequences (without any names or IDs)
Returns DataFrame with the following fields:
- source_sequence
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name
"""
# make each sequence its own unique ID
sequence_dict = {
seq: seq
for seq in sequences
}
df = self.predict_from_named_sequences(sequence_dict)
return df.rename(columns={"source_sequence_name": "source_sequence"}) | [
"def",
"predict_from_sequences",
"(",
"self",
",",
"sequences",
")",
":",
"# make each sequence its own unique ID",
"sequence_dict",
"=",
"{",
"seq",
":",
"seq",
"for",
"seq",
"in",
"sequences",
"}",
"df",
"=",
"self",
".",
"predict_from_named_sequences",
"(",
"se... | Predict MHC ligands for sub-sequences of each input sequence.
Parameters
----------
sequences : list of str
Multiple amino acid sequences (without any names or IDs)
Returns DataFrame with the following fields:
- source_sequence
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name | [
"Predict",
"MHC",
"ligands",
"for",
"sub",
"-",
"sequences",
"of",
"each",
"input",
"sequence",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/predictor.py#L115-L140 | train | 43,822 |
openvax/topiary | topiary/predictor.py | TopiaryPredictor.predict_from_variants | def predict_from_variants(
self,
variants,
transcript_expression_dict=None,
gene_expression_dict=None):
"""
Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
----------
variants : varcode.VariantCollection
transcript_expression_dict : dict
Maps from Ensembl transcript IDs to FPKM expression values.
gene_expression_dict : dict, optional
Maps from Ensembl gene IDs to FPKM expression values.
Returns DataFrame with the following columns:
- variant
- gene
- gene_id
- transcript_id
- transcript_name
- effect
- effect_type
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name
- contains_mutant_residues
- mutation_start_in_peptide
- mutation_end_in_peptide
Optionall will also include the following columns if corresponding
expression dictionary inputs are provided:
- gene_expression
- transcript_expression
"""
# pre-filter variants by checking if any of the genes or
# transcripts they overlap have sufficient expression.
# I'm tolerating the redundancy of this code since it's much cheaper
# to filter a variant *before* trying to predict its impact/effect
# on the protein sequence.
variants = apply_variant_expression_filters(
variants,
transcript_expression_dict=transcript_expression_dict,
transcript_expression_threshold=self.min_transcript_expression,
gene_expression_dict=gene_expression_dict,
gene_expression_threshold=self.min_gene_expression)
effects = variants.effects(raise_on_error=self.raise_on_error)
return self.predict_from_mutation_effects(
effects=effects,
transcript_expression_dict=transcript_expression_dict,
gene_expression_dict=gene_expression_dict) | python | def predict_from_variants(
self,
variants,
transcript_expression_dict=None,
gene_expression_dict=None):
"""
Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
----------
variants : varcode.VariantCollection
transcript_expression_dict : dict
Maps from Ensembl transcript IDs to FPKM expression values.
gene_expression_dict : dict, optional
Maps from Ensembl gene IDs to FPKM expression values.
Returns DataFrame with the following columns:
- variant
- gene
- gene_id
- transcript_id
- transcript_name
- effect
- effect_type
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name
- contains_mutant_residues
- mutation_start_in_peptide
- mutation_end_in_peptide
Optionall will also include the following columns if corresponding
expression dictionary inputs are provided:
- gene_expression
- transcript_expression
"""
# pre-filter variants by checking if any of the genes or
# transcripts they overlap have sufficient expression.
# I'm tolerating the redundancy of this code since it's much cheaper
# to filter a variant *before* trying to predict its impact/effect
# on the protein sequence.
variants = apply_variant_expression_filters(
variants,
transcript_expression_dict=transcript_expression_dict,
transcript_expression_threshold=self.min_transcript_expression,
gene_expression_dict=gene_expression_dict,
gene_expression_threshold=self.min_gene_expression)
effects = variants.effects(raise_on_error=self.raise_on_error)
return self.predict_from_mutation_effects(
effects=effects,
transcript_expression_dict=transcript_expression_dict,
gene_expression_dict=gene_expression_dict) | [
"def",
"predict_from_variants",
"(",
"self",
",",
"variants",
",",
"transcript_expression_dict",
"=",
"None",
",",
"gene_expression_dict",
"=",
"None",
")",
":",
"# pre-filter variants by checking if any of the genes or",
"# transcripts they overlap have sufficient expression.",
... | Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
----------
variants : varcode.VariantCollection
transcript_expression_dict : dict
Maps from Ensembl transcript IDs to FPKM expression values.
gene_expression_dict : dict, optional
Maps from Ensembl gene IDs to FPKM expression values.
Returns DataFrame with the following columns:
- variant
- gene
- gene_id
- transcript_id
- transcript_name
- effect
- effect_type
- peptide
- peptide_offset
- peptide_length
- allele
- affinity
- percentile_rank
- prediction_method_name
- contains_mutant_residues
- mutation_start_in_peptide
- mutation_end_in_peptide
Optionall will also include the following columns if corresponding
expression dictionary inputs are provided:
- gene_expression
- transcript_expression | [
"Predict",
"epitopes",
"from",
"a",
"Variant",
"collection",
"filtering",
"options",
"and",
"optional",
"gene",
"and",
"transcript",
"expression",
"data",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/predictor.py#L347-L407 | train | 43,823 |
openvax/topiary | topiary/cli/script.py | main | def main(args_list=None):
"""
Script entry-point to predict neo-epitopes from genomic variants using
Topiary.
"""
args = parse_args(args_list)
print("Topiary commandline arguments:")
print(args)
df = predict_epitopes_from_args(args)
write_outputs(df, args)
print("Total count: %d" % len(df)) | python | def main(args_list=None):
"""
Script entry-point to predict neo-epitopes from genomic variants using
Topiary.
"""
args = parse_args(args_list)
print("Topiary commandline arguments:")
print(args)
df = predict_epitopes_from_args(args)
write_outputs(df, args)
print("Total count: %d" % len(df)) | [
"def",
"main",
"(",
"args_list",
"=",
"None",
")",
":",
"args",
"=",
"parse_args",
"(",
"args_list",
")",
"print",
"(",
"\"Topiary commandline arguments:\"",
")",
"print",
"(",
"args",
")",
"df",
"=",
"predict_epitopes_from_args",
"(",
"args",
")",
"write_outp... | Script entry-point to predict neo-epitopes from genomic variants using
Topiary. | [
"Script",
"entry",
"-",
"point",
"to",
"predict",
"neo",
"-",
"epitopes",
"from",
"genomic",
"variants",
"using",
"Topiary",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/cli/script.py#L45-L55 | train | 43,824 |
gabrielelanaro/chemview | chemview/render.py | render_povray | def render_povray(scene, filename='ipython', width=600, height=600,
antialiasing=0.01, extra_opts={}):
'''Render the scene with povray for publication.
:param dict scene: The scene to render
:param string filename: Output filename or 'ipython' to render in the notebook.
:param int width: Width in pixels.
:param int height: Height in pixels.
:param dict extra_opts: Dictionary to merge/override with the passed scene.
'''
if not vapory_available:
raise Exception("To render with povray, you need to have the vapory"
" package installed.")
# Adding extra options
scene = normalize_scene(scene)
scene.update(extra_opts)
# Camera target
aspect = scene['camera']['aspect']
up = np.dot(rmatrixquaternion(scene['camera']['quaternion']), [0, 1, 0])
v_fov = scene['camera']['vfov'] / 180.0 * np.pi
h_fov = 2.0 * np.arctan(np.tan(v_fov/2.0) * aspect) / np.pi * 180
# Setup camera position
camera = vp.Camera( 'location', scene['camera']['location'],
'direction', [0, 0, -1],
'sky', up,
'look_at', scene['camera']['target'],
'angle', h_fov )
global_settings = []
# Setup global illumination
if scene.get('radiosity', False):
# Global Illumination
radiosity = vp.Radiosity(
'brightness', 2.0,
'count', 100,
'error_bound', 0.15,
'gray_threshold', 0.0,
'low_error_factor', 0.2,
'minimum_reuse', 0.015,
'nearest_count', 10,
'recursion_limit', 1, #Docs say 1 is enough
'adc_bailout', 0.01,
'max_sample', 0.5,
'media off',
'normal off',
'always_sample', 1,
'pretrace_start', 0.08,
'pretrace_end', 0.01)
light_sources = []
global_settings.append(radiosity)
else:
# Lights
light_sources = [
vp.LightSource( np.array([2,4,-3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([-2,-4,3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([-1,2,3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([1,-2,-3]) * 1000, 'color', [1,1,1] )
]
# Background -- white for now
background = vp.Background([1, 1, 1])
# Things to display
stuff = _generate_objects(scene['representations'])
scene = vp.Scene( camera, objects = light_sources + stuff + [background],
global_settings=global_settings)
return scene.render(filename, width=width, height=height,
antialiasing = antialiasing) | python | def render_povray(scene, filename='ipython', width=600, height=600,
antialiasing=0.01, extra_opts={}):
'''Render the scene with povray for publication.
:param dict scene: The scene to render
:param string filename: Output filename or 'ipython' to render in the notebook.
:param int width: Width in pixels.
:param int height: Height in pixels.
:param dict extra_opts: Dictionary to merge/override with the passed scene.
'''
if not vapory_available:
raise Exception("To render with povray, you need to have the vapory"
" package installed.")
# Adding extra options
scene = normalize_scene(scene)
scene.update(extra_opts)
# Camera target
aspect = scene['camera']['aspect']
up = np.dot(rmatrixquaternion(scene['camera']['quaternion']), [0, 1, 0])
v_fov = scene['camera']['vfov'] / 180.0 * np.pi
h_fov = 2.0 * np.arctan(np.tan(v_fov/2.0) * aspect) / np.pi * 180
# Setup camera position
camera = vp.Camera( 'location', scene['camera']['location'],
'direction', [0, 0, -1],
'sky', up,
'look_at', scene['camera']['target'],
'angle', h_fov )
global_settings = []
# Setup global illumination
if scene.get('radiosity', False):
# Global Illumination
radiosity = vp.Radiosity(
'brightness', 2.0,
'count', 100,
'error_bound', 0.15,
'gray_threshold', 0.0,
'low_error_factor', 0.2,
'minimum_reuse', 0.015,
'nearest_count', 10,
'recursion_limit', 1, #Docs say 1 is enough
'adc_bailout', 0.01,
'max_sample', 0.5,
'media off',
'normal off',
'always_sample', 1,
'pretrace_start', 0.08,
'pretrace_end', 0.01)
light_sources = []
global_settings.append(radiosity)
else:
# Lights
light_sources = [
vp.LightSource( np.array([2,4,-3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([-2,-4,3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([-1,2,3]) * 1000, 'color', [1,1,1] ),
vp.LightSource( np.array([1,-2,-3]) * 1000, 'color', [1,1,1] )
]
# Background -- white for now
background = vp.Background([1, 1, 1])
# Things to display
stuff = _generate_objects(scene['representations'])
scene = vp.Scene( camera, objects = light_sources + stuff + [background],
global_settings=global_settings)
return scene.render(filename, width=width, height=height,
antialiasing = antialiasing) | [
"def",
"render_povray",
"(",
"scene",
",",
"filename",
"=",
"'ipython'",
",",
"width",
"=",
"600",
",",
"height",
"=",
"600",
",",
"antialiasing",
"=",
"0.01",
",",
"extra_opts",
"=",
"{",
"}",
")",
":",
"if",
"not",
"vapory_available",
":",
"raise",
"... | Render the scene with povray for publication.
:param dict scene: The scene to render
:param string filename: Output filename or 'ipython' to render in the notebook.
:param int width: Width in pixels.
:param int height: Height in pixels.
:param dict extra_opts: Dictionary to merge/override with the passed scene. | [
"Render",
"the",
"scene",
"with",
"povray",
"for",
"publication",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/render.py#L21-L93 | train | 43,825 |
gabrielelanaro/chemview | chemview/render.py | rmatrixquaternion | def rmatrixquaternion(q):
"""Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4.
"""
assert np.allclose(math.sqrt(np.dot(q,q)), 1.0)
x, y, z, w = q
xx = x*x
xy = x*y
xz = x*z
xw = x*w
yy = y*y
yz = y*z
yw = y*w
zz = z*z
zw = z*w
r00 = 1.0 - 2.0 * (yy + zz)
r01 = 2.0 * (xy - zw)
r02 = 2.0 * (xz + yw)
r10 = 2.0 * (xy + zw)
r11 = 1.0 - 2.0 * (xx + zz)
r12 = 2.0 * (yz - xw)
r20 = 2.0 * (xz - yw)
r21 = 2.0 * (yz + xw)
r22 = 1.0 - 2.0 * (xx + yy)
R = np.array([[r00, r01, r02],
[r10, r11, r12],
[r20, r21, r22]], float)
assert np.allclose(np.linalg.det(R), 1.0)
return R | python | def rmatrixquaternion(q):
"""Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4.
"""
assert np.allclose(math.sqrt(np.dot(q,q)), 1.0)
x, y, z, w = q
xx = x*x
xy = x*y
xz = x*z
xw = x*w
yy = y*y
yz = y*z
yw = y*w
zz = z*z
zw = z*w
r00 = 1.0 - 2.0 * (yy + zz)
r01 = 2.0 * (xy - zw)
r02 = 2.0 * (xz + yw)
r10 = 2.0 * (xy + zw)
r11 = 1.0 - 2.0 * (xx + zz)
r12 = 2.0 * (yz - xw)
r20 = 2.0 * (xz - yw)
r21 = 2.0 * (yz + xw)
r22 = 1.0 - 2.0 * (xx + yy)
R = np.array([[r00, r01, r02],
[r10, r11, r12],
[r20, r21, r22]], float)
assert np.allclose(np.linalg.det(R), 1.0)
return R | [
"def",
"rmatrixquaternion",
"(",
"q",
")",
":",
"assert",
"np",
".",
"allclose",
"(",
"math",
".",
"sqrt",
"(",
"np",
".",
"dot",
"(",
"q",
",",
"q",
")",
")",
",",
"1.0",
")",
"x",
",",
"y",
",",
"z",
",",
"w",
"=",
"q",
"xx",
"=",
"x",
... | Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4. | [
"Create",
"a",
"rotation",
"matrix",
"from",
"q",
"quaternion",
"rotation",
".",
"Quaternions",
"are",
"typed",
"as",
"Numeric",
"Python",
"numpy",
".",
"arrays",
"of",
"length",
"4",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/render.py#L181-L216 | train | 43,826 |
openvax/topiary | topiary/cli/rna.py | rna_transcript_expression_dict_from_args | def rna_transcript_expression_dict_from_args(args):
"""
Returns a dictionary mapping Ensembl transcript IDs to FPKM expression
values or None if neither Cufflinks tracking file nor StringTie GTF file
were specified.
"""
if args.rna_transcript_fpkm_tracking_file:
return load_cufflinks_fpkm_dict(args.rna_transcript_fpkm_tracking_file)
elif args.rna_transcript_fpkm_gtf_file:
return load_transcript_fpkm_dict_from_gtf(
args.rna_transcript_fpkm_gtf_file)
else:
return None | python | def rna_transcript_expression_dict_from_args(args):
"""
Returns a dictionary mapping Ensembl transcript IDs to FPKM expression
values or None if neither Cufflinks tracking file nor StringTie GTF file
were specified.
"""
if args.rna_transcript_fpkm_tracking_file:
return load_cufflinks_fpkm_dict(args.rna_transcript_fpkm_tracking_file)
elif args.rna_transcript_fpkm_gtf_file:
return load_transcript_fpkm_dict_from_gtf(
args.rna_transcript_fpkm_gtf_file)
else:
return None | [
"def",
"rna_transcript_expression_dict_from_args",
"(",
"args",
")",
":",
"if",
"args",
".",
"rna_transcript_fpkm_tracking_file",
":",
"return",
"load_cufflinks_fpkm_dict",
"(",
"args",
".",
"rna_transcript_fpkm_tracking_file",
")",
"elif",
"args",
".",
"rna_transcript_fpkm... | Returns a dictionary mapping Ensembl transcript IDs to FPKM expression
values or None if neither Cufflinks tracking file nor StringTie GTF file
were specified. | [
"Returns",
"a",
"dictionary",
"mapping",
"Ensembl",
"transcript",
"IDs",
"to",
"FPKM",
"expression",
"values",
"or",
"None",
"if",
"neither",
"Cufflinks",
"tracking",
"file",
"nor",
"StringTie",
"GTF",
"file",
"were",
"specified",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/cli/rna.py#L75-L87 | train | 43,827 |
trustar/trustar-python | trustar/models/page.py | Page.from_dict | def from_dict(page, content_type=None):
"""
Create a |Page| object from a dictionary. This method is intended for internal use, to construct a
|Page| object from the body of a response json from a paginated endpoint.
:param page: The dictionary.
:param content_type: The class that the contents should be deserialized into.
:return: The resulting |Page| object.
"""
result = Page(items=page.get('items'),
page_number=page.get('pageNumber'),
page_size=page.get('pageSize'),
total_elements=page.get('totalElements'),
has_next=page.get('hasNext'))
if content_type is not None:
if not issubclass(content_type, ModelBase):
raise ValueError("'content_type' must be a subclass of ModelBase.")
result.items = [content_type.from_dict(item) for item in result.items]
return result | python | def from_dict(page, content_type=None):
"""
Create a |Page| object from a dictionary. This method is intended for internal use, to construct a
|Page| object from the body of a response json from a paginated endpoint.
:param page: The dictionary.
:param content_type: The class that the contents should be deserialized into.
:return: The resulting |Page| object.
"""
result = Page(items=page.get('items'),
page_number=page.get('pageNumber'),
page_size=page.get('pageSize'),
total_elements=page.get('totalElements'),
has_next=page.get('hasNext'))
if content_type is not None:
if not issubclass(content_type, ModelBase):
raise ValueError("'content_type' must be a subclass of ModelBase.")
result.items = [content_type.from_dict(item) for item in result.items]
return result | [
"def",
"from_dict",
"(",
"page",
",",
"content_type",
"=",
"None",
")",
":",
"result",
"=",
"Page",
"(",
"items",
"=",
"page",
".",
"get",
"(",
"'items'",
")",
",",
"page_number",
"=",
"page",
".",
"get",
"(",
"'pageNumber'",
")",
",",
"page_size",
"... | Create a |Page| object from a dictionary. This method is intended for internal use, to construct a
|Page| object from the body of a response json from a paginated endpoint.
:param page: The dictionary.
:param content_type: The class that the contents should be deserialized into.
:return: The resulting |Page| object. | [
"Create",
"a",
"|Page|",
"object",
"from",
"a",
"dictionary",
".",
"This",
"method",
"is",
"intended",
"for",
"internal",
"use",
"to",
"construct",
"a",
"|Page|",
"object",
"from",
"the",
"body",
"of",
"a",
"response",
"json",
"from",
"a",
"paginated",
"en... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/page.py#L67-L89 | train | 43,828 |
trustar/trustar-python | trustar/models/page.py | Page.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the page.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the page.
"""
items = []
# attempt to replace each item with its dictionary representation if possible
for item in self.items:
if hasattr(item, 'to_dict'):
items.append(item.to_dict(remove_nones=remove_nones))
else:
items.append(item)
return {
'items': items,
'pageNumber': self.page_number,
'pageSize': self.page_size,
'totalElements': self.total_elements,
'hasNext': self.has_next
} | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the page.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the page.
"""
items = []
# attempt to replace each item with its dictionary representation if possible
for item in self.items:
if hasattr(item, 'to_dict'):
items.append(item.to_dict(remove_nones=remove_nones))
else:
items.append(item)
return {
'items': items,
'pageNumber': self.page_number,
'pageSize': self.page_size,
'totalElements': self.total_elements,
'hasNext': self.has_next
} | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"items",
"=",
"[",
"]",
"# attempt to replace each item with its dictionary representation if possible",
"for",
"item",
"in",
"self",
".",
"items",
":",
"if",
"hasattr",
"(",
"item",
",",
... | Creates a dictionary representation of the page.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the page. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/page.py#L91-L114 | train | 43,829 |
trustar/trustar-python | trustar/models/page.py | Page.get_page_generator | def get_page_generator(func, start_page=0, page_size=None):
"""
Constructs a generator for retrieving pages from a paginated endpoint. This method is intended for internal
use.
:param func: Should take parameters ``page_number`` and ``page_size`` and return the corresponding |Page| object.
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: A generator that generates each successive page.
"""
# initialize starting values
page_number = start_page
more_pages = True
# continuously request the next page as long as more pages exist
while more_pages:
# get next page
page = func(page_number=page_number, page_size=page_size)
yield page
# determine whether more pages exist
more_pages = page.has_more_pages()
page_number += 1 | python | def get_page_generator(func, start_page=0, page_size=None):
"""
Constructs a generator for retrieving pages from a paginated endpoint. This method is intended for internal
use.
:param func: Should take parameters ``page_number`` and ``page_size`` and return the corresponding |Page| object.
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: A generator that generates each successive page.
"""
# initialize starting values
page_number = start_page
more_pages = True
# continuously request the next page as long as more pages exist
while more_pages:
# get next page
page = func(page_number=page_number, page_size=page_size)
yield page
# determine whether more pages exist
more_pages = page.has_more_pages()
page_number += 1 | [
"def",
"get_page_generator",
"(",
"func",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"# initialize starting values",
"page_number",
"=",
"start_page",
"more_pages",
"=",
"True",
"# continuously request the next page as long as more pages exist",
... | Constructs a generator for retrieving pages from a paginated endpoint. This method is intended for internal
use.
:param func: Should take parameters ``page_number`` and ``page_size`` and return the corresponding |Page| object.
:param start_page: The page to start on.
:param page_size: The size of each page.
:return: A generator that generates each successive page. | [
"Constructs",
"a",
"generator",
"for",
"retrieving",
"pages",
"from",
"a",
"paginated",
"endpoint",
".",
"This",
"method",
"is",
"intended",
"for",
"internal",
"use",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/page.py#L117-L142 | train | 43,830 |
gabrielelanaro/chemview | chemview/export.py | serialize_to_dict | def serialize_to_dict(dictionary):
'''Make a json-serializable dictionary from input dictionary by converting
non-serializable data types such as numpy arrays.'''
retval = {}
for k, v in dictionary.items():
if isinstance(v, dict):
retval[k] = serialize_to_dict(v)
else:
# This is when custom serialization happens
if isinstance(v, np.ndarray):
if v.dtype == 'float64':
# We don't support float64 on js side
v = v.astype('float32')
retval[k] = encode_numpy(v)
else:
retval[k] = v
return retval | python | def serialize_to_dict(dictionary):
'''Make a json-serializable dictionary from input dictionary by converting
non-serializable data types such as numpy arrays.'''
retval = {}
for k, v in dictionary.items():
if isinstance(v, dict):
retval[k] = serialize_to_dict(v)
else:
# This is when custom serialization happens
if isinstance(v, np.ndarray):
if v.dtype == 'float64':
# We don't support float64 on js side
v = v.astype('float32')
retval[k] = encode_numpy(v)
else:
retval[k] = v
return retval | [
"def",
"serialize_to_dict",
"(",
"dictionary",
")",
":",
"retval",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"retval",
"[",
"k",
"]",
"=",
"serialize_t... | Make a json-serializable dictionary from input dictionary by converting
non-serializable data types such as numpy arrays. | [
"Make",
"a",
"json",
"-",
"serializable",
"dictionary",
"from",
"input",
"dictionary",
"by",
"converting",
"non",
"-",
"serializable",
"data",
"types",
"such",
"as",
"numpy",
"arrays",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/export.py#L27-L46 | train | 43,831 |
tdsmith/homebrew-pypi-poet | poet/poet.py | make_graph | def make_graph(pkg):
"""Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_package.
(No, it's not really a graph.)
"""
ignore = ['argparse', 'pip', 'setuptools', 'wsgiref']
pkg_deps = recursive_dependencies(pkg_resources.Requirement.parse(pkg))
dependencies = {key: {} for key in pkg_deps if key not in ignore}
installed_packages = pkg_resources.working_set
versions = {package.key: package.version for package in installed_packages}
for package in dependencies:
try:
dependencies[package]['version'] = versions[package]
except KeyError:
warnings.warn("{} is not installed so we cannot compute "
"resources for its dependencies.".format(package),
PackageNotInstalledWarning)
dependencies[package]['version'] = None
for package in dependencies:
package_data = research_package(package, dependencies[package]['version'])
dependencies[package].update(package_data)
return OrderedDict(
[(package, dependencies[package]) for package in sorted(dependencies.keys())]
) | python | def make_graph(pkg):
"""Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_package.
(No, it's not really a graph.)
"""
ignore = ['argparse', 'pip', 'setuptools', 'wsgiref']
pkg_deps = recursive_dependencies(pkg_resources.Requirement.parse(pkg))
dependencies = {key: {} for key in pkg_deps if key not in ignore}
installed_packages = pkg_resources.working_set
versions = {package.key: package.version for package in installed_packages}
for package in dependencies:
try:
dependencies[package]['version'] = versions[package]
except KeyError:
warnings.warn("{} is not installed so we cannot compute "
"resources for its dependencies.".format(package),
PackageNotInstalledWarning)
dependencies[package]['version'] = None
for package in dependencies:
package_data = research_package(package, dependencies[package]['version'])
dependencies[package].update(package_data)
return OrderedDict(
[(package, dependencies[package]) for package in sorted(dependencies.keys())]
) | [
"def",
"make_graph",
"(",
"pkg",
")",
":",
"ignore",
"=",
"[",
"'argparse'",
",",
"'pip'",
",",
"'setuptools'",
",",
"'wsgiref'",
"]",
"pkg_deps",
"=",
"recursive_dependencies",
"(",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"pkg",
")",
")",
... | Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_package.
(No, it's not really a graph.) | [
"Returns",
"a",
"dictionary",
"of",
"information",
"about",
"pkg",
"&",
"its",
"recursive",
"deps",
"."
] | fdafc615bcd28f29bcbe90789f07cc26f97c3bbc | https://github.com/tdsmith/homebrew-pypi-poet/blob/fdafc615bcd28f29bcbe90789f07cc26f97c3bbc/poet/poet.py#L123-L152 | train | 43,832 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_report_details | def get_report_details(self, report_id, id_type=None):
"""
Retrieves a report by its ID. Internal and external IDs are both allowed.
:param str report_id: The ID of the incident report.
:param str id_type: Indicates whether ID is internal or external.
:return: The retrieved |Report| object.
Example:
>>> report = ts.get_report_details("1a09f14b-ef8c-443f-b082-9643071c522a")
>>> print(report)
{
"id": "1a09f14b-ef8c-443f-b082-9643071c522a",
"created": 1515571633505,
"updated": 1515620420062,
"reportBody": "Employee reported suspect email. We had multiple reports of suspicious email overnight ...",
"title": "Phishing Incident",
"enclaveIds": [
"ac6a0d17-7350-4410-bc57-9699521db992"
],
"distributionType": "ENCLAVE",
"timeBegan": 1479941278000
}
"""
params = {'idType': id_type}
resp = self._client.get("reports/%s" % report_id, params=params)
return Report.from_dict(resp.json()) | python | def get_report_details(self, report_id, id_type=None):
"""
Retrieves a report by its ID. Internal and external IDs are both allowed.
:param str report_id: The ID of the incident report.
:param str id_type: Indicates whether ID is internal or external.
:return: The retrieved |Report| object.
Example:
>>> report = ts.get_report_details("1a09f14b-ef8c-443f-b082-9643071c522a")
>>> print(report)
{
"id": "1a09f14b-ef8c-443f-b082-9643071c522a",
"created": 1515571633505,
"updated": 1515620420062,
"reportBody": "Employee reported suspect email. We had multiple reports of suspicious email overnight ...",
"title": "Phishing Incident",
"enclaveIds": [
"ac6a0d17-7350-4410-bc57-9699521db992"
],
"distributionType": "ENCLAVE",
"timeBegan": 1479941278000
}
"""
params = {'idType': id_type}
resp = self._client.get("reports/%s" % report_id, params=params)
return Report.from_dict(resp.json()) | [
"def",
"get_report_details",
"(",
"self",
",",
"report_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/%s\"",
"%",
"report_id",
",",
"params... | Retrieves a report by its ID. Internal and external IDs are both allowed.
:param str report_id: The ID of the incident report.
:param str id_type: Indicates whether ID is internal or external.
:return: The retrieved |Report| object.
Example:
>>> report = ts.get_report_details("1a09f14b-ef8c-443f-b082-9643071c522a")
>>> print(report)
{
"id": "1a09f14b-ef8c-443f-b082-9643071c522a",
"created": 1515571633505,
"updated": 1515620420062,
"reportBody": "Employee reported suspect email. We had multiple reports of suspicious email overnight ...",
"title": "Phishing Incident",
"enclaveIds": [
"ac6a0d17-7350-4410-bc57-9699521db992"
],
"distributionType": "ENCLAVE",
"timeBegan": 1479941278000
} | [
"Retrieves",
"a",
"report",
"by",
"its",
"ID",
".",
"Internal",
"and",
"external",
"IDs",
"are",
"both",
"allowed",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L25-L55 | train | 43,833 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_reports_page | def get_reports_page(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Retrieves a page of reports, filtering by time window, distribution type, enclave association, and tag.
The results are sorted by updated time.
This method does not take ``page_number`` and ``page_size`` parameters. Instead, each successive page must be
found by adjusting the ``from_time`` and ``to_time`` parameters.
Note: This endpoint will only return reports from a time window of maximum size of 2 weeks. If you give a
time window larger than 2 weeks, it will pull reports starting at 2 weeks before the "to" date, through the
"to" date.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param list(str) tag: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned.
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A |Page| of |Report| objects.
"""
distribution_type = None
# explicitly compare to True and False to distinguish from None (which is treated as False in a conditional)
if is_enclave:
distribution_type = DistributionType.ENCLAVE
elif not is_enclave:
distribution_type = DistributionType.COMMUNITY
if enclave_ids is None:
enclave_ids = self.enclave_ids
params = {
'from': from_time,
'to': to_time,
'distributionType': distribution_type,
'enclaveIds': enclave_ids,
'tags': tag,
'excludedTags': excluded_tags
}
resp = self._client.get("reports", params=params)
result = Page.from_dict(resp.json(), content_type=Report)
# create a Page object from the dict
return result | python | def get_reports_page(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Retrieves a page of reports, filtering by time window, distribution type, enclave association, and tag.
The results are sorted by updated time.
This method does not take ``page_number`` and ``page_size`` parameters. Instead, each successive page must be
found by adjusting the ``from_time`` and ``to_time`` parameters.
Note: This endpoint will only return reports from a time window of maximum size of 2 weeks. If you give a
time window larger than 2 weeks, it will pull reports starting at 2 weeks before the "to" date, through the
"to" date.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param list(str) tag: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned.
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A |Page| of |Report| objects.
"""
distribution_type = None
# explicitly compare to True and False to distinguish from None (which is treated as False in a conditional)
if is_enclave:
distribution_type = DistributionType.ENCLAVE
elif not is_enclave:
distribution_type = DistributionType.COMMUNITY
if enclave_ids is None:
enclave_ids = self.enclave_ids
params = {
'from': from_time,
'to': to_time,
'distributionType': distribution_type,
'enclaveIds': enclave_ids,
'tags': tag,
'excludedTags': excluded_tags
}
resp = self._client.get("reports", params=params)
result = Page.from_dict(resp.json(), content_type=Report)
# create a Page object from the dict
return result | [
"def",
"get_reports_page",
"(",
"self",
",",
"is_enclave",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
")",
":",
"distribution_type",
... | Retrieves a page of reports, filtering by time window, distribution type, enclave association, and tag.
The results are sorted by updated time.
This method does not take ``page_number`` and ``page_size`` parameters. Instead, each successive page must be
found by adjusting the ``from_time`` and ``to_time`` parameters.
Note: This endpoint will only return reports from a time window of maximum size of 2 weeks. If you give a
time window larger than 2 weeks, it will pull reports starting at 2 weeks before the "to" date, through the
"to" date.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param list(str) tag: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned.
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A |Page| of |Report| objects. | [
"Retrieves",
"a",
"page",
"of",
"reports",
"filtering",
"by",
"time",
"window",
"distribution",
"type",
"enclave",
"association",
"and",
"tag",
".",
"The",
"results",
"are",
"sorted",
"by",
"updated",
"time",
".",
"This",
"method",
"does",
"not",
"take",
"pa... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L57-L106 | train | 43,834 |
trustar/trustar-python | trustar/report_client.py | ReportClient.submit_report | def submit_report(self, report):
"""
Submits a report.
* If ``report.is_enclave`` is ``True``, then the report will be submitted to the enclaves
identified by ``report.enclaves``; if that field is ``None``, then the enclave IDs registered with this
|TruStar| object will be used.
* If ``report.time_began`` is ``None``, then the current time will be used.
:param report: The |Report| object that was submitted, with the ``id`` field updated based
on values from the response.
Example:
>>> report = Report(title="Suspicious Activity",
>>> body="We have been receiving suspicious requests from 169.178.68.63.",
>>> enclave_ids=["602d4795-31cd-44f9-a85d-f33cb869145a"])
>>> report = ts.submit_report(report)
>>> print(report.id)
ac6a0d17-7350-4410-bc57-9699521db992
>>> print(report.title)
Suspicious Activity
"""
# make distribution type default to "enclave"
if report.is_enclave is None:
report.is_enclave = True
if report.enclave_ids is None:
# use configured enclave_ids by default if distribution type is ENCLAVE
if report.is_enclave:
report.enclave_ids = self.enclave_ids
# if distribution type is COMMUNITY, API still expects non-null list of enclaves
else:
report.enclave_ids = []
if report.is_enclave and len(report.enclave_ids) == 0:
raise Exception("Cannot submit a report of distribution type 'ENCLAVE' with an empty set of enclaves.")
# default time began is current time
if report.time_began is None:
report.set_time_began(datetime.now())
data = json.dumps(report.to_dict())
resp = self._client.post("reports", data=data, timeout=60)
# get report id from response body
report_id = resp.content
if isinstance(report_id, bytes):
report_id = report_id.decode('utf-8')
report.id = report_id
return report | python | def submit_report(self, report):
"""
Submits a report.
* If ``report.is_enclave`` is ``True``, then the report will be submitted to the enclaves
identified by ``report.enclaves``; if that field is ``None``, then the enclave IDs registered with this
|TruStar| object will be used.
* If ``report.time_began`` is ``None``, then the current time will be used.
:param report: The |Report| object that was submitted, with the ``id`` field updated based
on values from the response.
Example:
>>> report = Report(title="Suspicious Activity",
>>> body="We have been receiving suspicious requests from 169.178.68.63.",
>>> enclave_ids=["602d4795-31cd-44f9-a85d-f33cb869145a"])
>>> report = ts.submit_report(report)
>>> print(report.id)
ac6a0d17-7350-4410-bc57-9699521db992
>>> print(report.title)
Suspicious Activity
"""
# make distribution type default to "enclave"
if report.is_enclave is None:
report.is_enclave = True
if report.enclave_ids is None:
# use configured enclave_ids by default if distribution type is ENCLAVE
if report.is_enclave:
report.enclave_ids = self.enclave_ids
# if distribution type is COMMUNITY, API still expects non-null list of enclaves
else:
report.enclave_ids = []
if report.is_enclave and len(report.enclave_ids) == 0:
raise Exception("Cannot submit a report of distribution type 'ENCLAVE' with an empty set of enclaves.")
# default time began is current time
if report.time_began is None:
report.set_time_began(datetime.now())
data = json.dumps(report.to_dict())
resp = self._client.post("reports", data=data, timeout=60)
# get report id from response body
report_id = resp.content
if isinstance(report_id, bytes):
report_id = report_id.decode('utf-8')
report.id = report_id
return report | [
"def",
"submit_report",
"(",
"self",
",",
"report",
")",
":",
"# make distribution type default to \"enclave\"",
"if",
"report",
".",
"is_enclave",
"is",
"None",
":",
"report",
".",
"is_enclave",
"=",
"True",
"if",
"report",
".",
"enclave_ids",
"is",
"None",
":"... | Submits a report.
* If ``report.is_enclave`` is ``True``, then the report will be submitted to the enclaves
identified by ``report.enclaves``; if that field is ``None``, then the enclave IDs registered with this
|TruStar| object will be used.
* If ``report.time_began`` is ``None``, then the current time will be used.
:param report: The |Report| object that was submitted, with the ``id`` field updated based
on values from the response.
Example:
>>> report = Report(title="Suspicious Activity",
>>> body="We have been receiving suspicious requests from 169.178.68.63.",
>>> enclave_ids=["602d4795-31cd-44f9-a85d-f33cb869145a"])
>>> report = ts.submit_report(report)
>>> print(report.id)
ac6a0d17-7350-4410-bc57-9699521db992
>>> print(report.title)
Suspicious Activity | [
"Submits",
"a",
"report",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L108-L162 | train | 43,835 |
trustar/trustar-python | trustar/report_client.py | ReportClient.update_report | def update_report(self, report):
"""
Updates the report identified by the ``report.id`` field; if this field does not exist, then
``report.external_id`` will be used if it exists. Any other fields on ``report`` that are not ``None``
will overwrite values on the report in TruSTAR's system. Any fields that are ``None`` will simply be ignored;
their values will be unchanged.
:param report: A |Report| object with the updated values.
:return: The |Report| object.
Example:
>>> report = ts.get_report_details(report_id)
>>> print(report.title)
Old Title
>>> report.title = "Changed title"
>>> updated_report = ts.update_report(report)
>>> print(updated_report.title)
Changed Title
"""
# default to interal ID type if ID field is present
if report.id is not None:
id_type = IdType.INTERNAL
report_id = report.id
# if no ID field is present, but external ID field is, default to external ID type
elif report.external_id is not None:
id_type = IdType.EXTERNAL
report_id = report.external_id
# if no ID fields exist, raise exception
else:
raise Exception("Cannot update report without either an ID or an external ID.")
# not allowed to update value of 'reportId', so remove it
report_dict = {k: v for k, v in report.to_dict().items() if k != 'reportId'}
params = {'idType': id_type}
data = json.dumps(report.to_dict())
self._client.put("reports/%s" % report_id, data=data, params=params)
return report | python | def update_report(self, report):
"""
Updates the report identified by the ``report.id`` field; if this field does not exist, then
``report.external_id`` will be used if it exists. Any other fields on ``report`` that are not ``None``
will overwrite values on the report in TruSTAR's system. Any fields that are ``None`` will simply be ignored;
their values will be unchanged.
:param report: A |Report| object with the updated values.
:return: The |Report| object.
Example:
>>> report = ts.get_report_details(report_id)
>>> print(report.title)
Old Title
>>> report.title = "Changed title"
>>> updated_report = ts.update_report(report)
>>> print(updated_report.title)
Changed Title
"""
# default to interal ID type if ID field is present
if report.id is not None:
id_type = IdType.INTERNAL
report_id = report.id
# if no ID field is present, but external ID field is, default to external ID type
elif report.external_id is not None:
id_type = IdType.EXTERNAL
report_id = report.external_id
# if no ID fields exist, raise exception
else:
raise Exception("Cannot update report without either an ID or an external ID.")
# not allowed to update value of 'reportId', so remove it
report_dict = {k: v for k, v in report.to_dict().items() if k != 'reportId'}
params = {'idType': id_type}
data = json.dumps(report.to_dict())
self._client.put("reports/%s" % report_id, data=data, params=params)
return report | [
"def",
"update_report",
"(",
"self",
",",
"report",
")",
":",
"# default to interal ID type if ID field is present",
"if",
"report",
".",
"id",
"is",
"not",
"None",
":",
"id_type",
"=",
"IdType",
".",
"INTERNAL",
"report_id",
"=",
"report",
".",
"id",
"# if no I... | Updates the report identified by the ``report.id`` field; if this field does not exist, then
``report.external_id`` will be used if it exists. Any other fields on ``report`` that are not ``None``
will overwrite values on the report in TruSTAR's system. Any fields that are ``None`` will simply be ignored;
their values will be unchanged.
:param report: A |Report| object with the updated values.
:return: The |Report| object.
Example:
>>> report = ts.get_report_details(report_id)
>>> print(report.title)
Old Title
>>> report.title = "Changed title"
>>> updated_report = ts.update_report(report)
>>> print(updated_report.title)
Changed Title | [
"Updates",
"the",
"report",
"identified",
"by",
"the",
"report",
".",
"id",
"field",
";",
"if",
"this",
"field",
"does",
"not",
"exist",
"then",
"report",
".",
"external_id",
"will",
"be",
"used",
"if",
"it",
"exists",
".",
"Any",
"other",
"fields",
"on"... | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L164-L205 | train | 43,836 |
trustar/trustar-python | trustar/report_client.py | ReportClient.delete_report | def delete_report(self, report_id, id_type=None):
"""
Deletes the report with the given ID.
:param report_id: the ID of the report to delete
:param id_type: indicates whether the ID is internal or an external ID provided by the user
:return: the response object
Example:
>>> response = ts.delete_report("4d1fcaee-5009-4620-b239-2b22c3992b80")
"""
params = {'idType': id_type}
self._client.delete("reports/%s" % report_id, params=params) | python | def delete_report(self, report_id, id_type=None):
"""
Deletes the report with the given ID.
:param report_id: the ID of the report to delete
:param id_type: indicates whether the ID is internal or an external ID provided by the user
:return: the response object
Example:
>>> response = ts.delete_report("4d1fcaee-5009-4620-b239-2b22c3992b80")
"""
params = {'idType': id_type}
self._client.delete("reports/%s" % report_id, params=params) | [
"def",
"delete_report",
"(",
"self",
",",
"report_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"reports/%s\"",
"%",
"report_id",
",",
"params",
"=",
"params... | Deletes the report with the given ID.
:param report_id: the ID of the report to delete
:param id_type: indicates whether the ID is internal or an external ID provided by the user
:return: the response object
Example:
>>> response = ts.delete_report("4d1fcaee-5009-4620-b239-2b22c3992b80") | [
"Deletes",
"the",
"report",
"with",
"the",
"given",
"ID",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L207-L221 | train | 43,837 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_correlated_report_ids | def get_correlated_report_ids(self, indicators):
"""
DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that correlated.
Example:
>>> report_ids = ts.get_correlated_report_ids(["wannacry", "www.evil.com"])
>>> print(report_ids)
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"]
"""
params = {'indicators': indicators}
resp = self._client.get("reports/correlate", params=params)
return resp.json() | python | def get_correlated_report_ids(self, indicators):
"""
DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that correlated.
Example:
>>> report_ids = ts.get_correlated_report_ids(["wannacry", "www.evil.com"])
>>> print(report_ids)
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"]
"""
params = {'indicators': indicators}
resp = self._client.get("reports/correlate", params=params)
return resp.json() | [
"def",
"get_correlated_report_ids",
"(",
"self",
",",
"indicators",
")",
":",
"params",
"=",
"{",
"'indicators'",
":",
"indicators",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/correlate\"",
",",
"params",
"=",
"params",
")",
"retur... | DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that correlated.
Example:
>>> report_ids = ts.get_correlated_report_ids(["wannacry", "www.evil.com"])
>>> print(report_ids)
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"] | [
"DEPRECATED!",
"Retrieves",
"a",
"list",
"of",
"the",
"IDs",
"of",
"all",
"TruSTAR",
"reports",
"that",
"contain",
"the",
"searched",
"indicators",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L223-L240 | train | 43,838 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_correlated_reports_page | def get_correlated_reports_page(self, indicators, enclave_ids=None, is_enclave=True,
page_size=None, page_number=None):
"""
Retrieves a page of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: The list of IDs of reports that correlated.
Example:
>>> reports = ts.get_correlated_reports_page(["wannacry", "www.evil.com"]).items
>>> print([report.id for report in reports])
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"]
"""
if is_enclave:
distribution_type = DistributionType.ENCLAVE
else:
distribution_type = DistributionType.COMMUNITY
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'distributionType': distribution_type,
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("reports/correlated", params=params)
return Page.from_dict(resp.json(), content_type=Report) | python | def get_correlated_reports_page(self, indicators, enclave_ids=None, is_enclave=True,
page_size=None, page_number=None):
"""
Retrieves a page of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: The list of IDs of reports that correlated.
Example:
>>> reports = ts.get_correlated_reports_page(["wannacry", "www.evil.com"]).items
>>> print([report.id for report in reports])
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"]
"""
if is_enclave:
distribution_type = DistributionType.ENCLAVE
else:
distribution_type = DistributionType.COMMUNITY
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'distributionType': distribution_type,
'pageNumber': page_number,
'pageSize': page_size
}
resp = self._client.get("reports/correlated", params=params)
return Page.from_dict(resp.json(), content_type=Report) | [
"def",
"get_correlated_reports_page",
"(",
"self",
",",
"indicators",
",",
"enclave_ids",
"=",
"None",
",",
"is_enclave",
"=",
"True",
",",
"page_size",
"=",
"None",
",",
"page_number",
"=",
"None",
")",
":",
"if",
"is_enclave",
":",
"distribution_type",
"=",
... | Retrieves a page of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:param int page_number: the page number to get.
:param int page_size: the size of the page to be returned.
:return: The list of IDs of reports that correlated.
Example:
>>> reports = ts.get_correlated_reports_page(["wannacry", "www.evil.com"]).items
>>> print([report.id for report in reports])
["e3bc6921-e2c8-42eb-829e-eea8da2d3f36", "4d04804f-ff82-4a0b-8586-c42aef2f6f73"] | [
"Retrieves",
"a",
"page",
"of",
"all",
"TruSTAR",
"reports",
"that",
"contain",
"the",
"searched",
"indicators",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L242-L275 | train | 43,839 |
trustar/trustar-python | trustar/report_client.py | ReportClient.search_reports_page | def search_reports_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None,
page_size=None,
page_number=None):
"""
Search for reports containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get. (optional)
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Report| objects. *NOTE*: The bodies of these reports will be ``None``.
"""
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'tags': tags,
'excludedTags': excluded_tags,
'pageSize': page_size,
'pageNumber': page_number
}
resp = self._client.post("reports/search", params=params, data=json.dumps(body))
page = Page.from_dict(resp.json(), content_type=Report)
return page | python | def search_reports_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None,
page_size=None,
page_number=None):
"""
Search for reports containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get. (optional)
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Report| objects. *NOTE*: The bodies of these reports will be ``None``.
"""
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'tags': tags,
'excludedTags': excluded_tags,
'pageSize': page_size,
'pageNumber': page_number
}
resp = self._client.post("reports/search", params=params, data=json.dumps(body))
page = Page.from_dict(resp.json(), content_type=Report)
return page | [
"def",
"search_reports_page",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
",",
"page_size",
"=",
"... | Search for reports containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int page_number: the page number to get. (optional)
:param int page_size: the size of the page to be returned.
:return: a |Page| of |Report| objects. *NOTE*: The bodies of these reports will be ``None``. | [
"Search",
"for",
"reports",
"containing",
"a",
"search",
"term",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L277-L319 | train | 43,840 |
trustar/trustar-python | trustar/report_client.py | ReportClient._get_reports_page_generator | def _get_reports_page_generator(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Creates a generator from the |get_reports_page| method that returns each successive page.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param str tag: name of tag to filter reports by. if a tag with this name exists in more than one enclave
indicated in ``enclave_ids``, the request will fail. handle this by making separate requests for each
enclave ID if necessary.
:param int from_time: start of time window in milliseconds since epoch
:param int to_time: end of time window in milliseconds since epoch (optional, defaults to current time)
:return: The generator.
"""
get_page = functools.partial(self.get_reports_page, is_enclave, enclave_ids, tag, excluded_tags)
return get_time_based_page_generator(
get_page=get_page,
get_next_to_time=lambda x: x.items[-1].updated if len(x.items) > 0 else None,
from_time=from_time,
to_time=to_time
) | python | def _get_reports_page_generator(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Creates a generator from the |get_reports_page| method that returns each successive page.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param str tag: name of tag to filter reports by. if a tag with this name exists in more than one enclave
indicated in ``enclave_ids``, the request will fail. handle this by making separate requests for each
enclave ID if necessary.
:param int from_time: start of time window in milliseconds since epoch
:param int to_time: end of time window in milliseconds since epoch (optional, defaults to current time)
:return: The generator.
"""
get_page = functools.partial(self.get_reports_page, is_enclave, enclave_ids, tag, excluded_tags)
return get_time_based_page_generator(
get_page=get_page,
get_next_to_time=lambda x: x.items[-1].updated if len(x.items) > 0 else None,
from_time=from_time,
to_time=to_time
) | [
"def",
"_get_reports_page_generator",
"(",
"self",
",",
"is_enclave",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
")",
":",
"get_page"... | Creates a generator from the |get_reports_page| method that returns each successive page.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param str tag: name of tag to filter reports by. if a tag with this name exists in more than one enclave
indicated in ``enclave_ids``, the request will fail. handle this by making separate requests for each
enclave ID if necessary.
:param int from_time: start of time window in milliseconds since epoch
:param int to_time: end of time window in milliseconds since epoch (optional, defaults to current time)
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_reports_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L321-L344 | train | 43,841 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_reports | def get_reports(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None, from_time=None, to_time=None):
"""
Uses the |get_reports_page| method to create a generator that returns each successive report as a trustar
report object.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param list(str) tag: a list of tags; only reports containing ALL of these tags will be returned.
If a tag with this name exists in more than one enclave in the list passed as the ``enclave_ids``
argument, the request will fail. Handle this by making separate requests for each
enclave ID if necessary.
:param list(str) excluded_tags: a list of tags; reports containing ANY of these tags will not be returned.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A generator of Report objects.
Note: If a report contains all of the tags in the list passed as argument to the 'tag' parameter and also
contains any (1 or more) of the tags in the list passed as argument to the 'excluded_tags' parameter, that
report will not be returned by this function.
Example:
>>> page = ts.get_reports(is_enclave=True, tag="malicious", from_time=1425695711000, to_time=1514185311000)
>>> for report in reports: print(report.id)
'661583cb-a6a7-4cbd-8a90-01578fa4da89'
'da131660-2708-4c8a-926e-f91fb5dbbc62'
'2e3400d6-fa37-4a8c-bc2f-155aaa02ae5a'
'38064828-d3db-4fff-8ab8-e0e3b304ff44'
'dbf26104-cee5-4ca4-bdbf-a01d0178c007'
"""
return Page.get_generator(page_generator=self._get_reports_page_generator(is_enclave, enclave_ids, tag,
excluded_tags, from_time, to_time)) | python | def get_reports(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None, from_time=None, to_time=None):
"""
Uses the |get_reports_page| method to create a generator that returns each successive report as a trustar
report object.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param list(str) tag: a list of tags; only reports containing ALL of these tags will be returned.
If a tag with this name exists in more than one enclave in the list passed as the ``enclave_ids``
argument, the request will fail. Handle this by making separate requests for each
enclave ID if necessary.
:param list(str) excluded_tags: a list of tags; reports containing ANY of these tags will not be returned.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A generator of Report objects.
Note: If a report contains all of the tags in the list passed as argument to the 'tag' parameter and also
contains any (1 or more) of the tags in the list passed as argument to the 'excluded_tags' parameter, that
report will not be returned by this function.
Example:
>>> page = ts.get_reports(is_enclave=True, tag="malicious", from_time=1425695711000, to_time=1514185311000)
>>> for report in reports: print(report.id)
'661583cb-a6a7-4cbd-8a90-01578fa4da89'
'da131660-2708-4c8a-926e-f91fb5dbbc62'
'2e3400d6-fa37-4a8c-bc2f-155aaa02ae5a'
'38064828-d3db-4fff-8ab8-e0e3b304ff44'
'dbf26104-cee5-4ca4-bdbf-a01d0178c007'
"""
return Page.get_generator(page_generator=self._get_reports_page_generator(is_enclave, enclave_ids, tag,
excluded_tags, from_time, to_time)) | [
"def",
"get_reports",
"(",
"self",
",",
"is_enclave",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
")",
":",
"return",
"Page",
".",... | Uses the |get_reports_page| method to create a generator that returns each successive report as a trustar
report object.
:param boolean is_enclave: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific
enclaves (optional - by default reports from all enclaves are returned)
:param list(str) tag: a list of tags; only reports containing ALL of these tags will be returned.
If a tag with this name exists in more than one enclave in the list passed as the ``enclave_ids``
argument, the request will fail. Handle this by making separate requests for each
enclave ID if necessary.
:param list(str) excluded_tags: a list of tags; reports containing ANY of these tags will not be returned.
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:return: A generator of Report objects.
Note: If a report contains all of the tags in the list passed as argument to the 'tag' parameter and also
contains any (1 or more) of the tags in the list passed as argument to the 'excluded_tags' parameter, that
report will not be returned by this function.
Example:
>>> page = ts.get_reports(is_enclave=True, tag="malicious", from_time=1425695711000, to_time=1514185311000)
>>> for report in reports: print(report.id)
'661583cb-a6a7-4cbd-8a90-01578fa4da89'
'da131660-2708-4c8a-926e-f91fb5dbbc62'
'2e3400d6-fa37-4a8c-bc2f-155aaa02ae5a'
'38064828-d3db-4fff-8ab8-e0e3b304ff44'
'dbf26104-cee5-4ca4-bdbf-a01d0178c007' | [
"Uses",
"the",
"|get_reports_page|",
"method",
"to",
"create",
"a",
"generator",
"that",
"returns",
"each",
"successive",
"report",
"as",
"a",
"trustar",
"report",
"object",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L346-L381 | train | 43,842 |
trustar/trustar-python | trustar/report_client.py | ReportClient._get_correlated_reports_page_generator | def _get_correlated_reports_page_generator(self, indicators, enclave_ids=None, is_enclave=True,
start_page=0, page_size=None):
"""
Creates a generator from the |get_correlated_reports_page| method that returns each
successive page.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids:
:param is_enclave:
:return: The generator.
"""
get_page = functools.partial(self.get_correlated_reports_page, indicators, enclave_ids, is_enclave)
return Page.get_page_generator(get_page, start_page, page_size) | python | def _get_correlated_reports_page_generator(self, indicators, enclave_ids=None, is_enclave=True,
start_page=0, page_size=None):
"""
Creates a generator from the |get_correlated_reports_page| method that returns each
successive page.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids:
:param is_enclave:
:return: The generator.
"""
get_page = functools.partial(self.get_correlated_reports_page, indicators, enclave_ids, is_enclave)
return Page.get_page_generator(get_page, start_page, page_size) | [
"def",
"_get_correlated_reports_page_generator",
"(",
"self",
",",
"indicators",
",",
"enclave_ids",
"=",
"None",
",",
"is_enclave",
"=",
"True",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"get_page",
"=",
"functools",
".",
"partial"... | Creates a generator from the |get_correlated_reports_page| method that returns each
successive page.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids:
:param is_enclave:
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|get_correlated_reports_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L383-L396 | train | 43,843 |
trustar/trustar-python | trustar/report_client.py | ReportClient.get_correlated_reports | def get_correlated_reports(self, indicators, enclave_ids=None, is_enclave=True):
"""
Uses the |get_correlated_reports_page| method to create a generator that returns each successive report.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:return: The generator.
"""
return Page.get_generator(page_generator=self._get_correlated_reports_page_generator(indicators,
enclave_ids,
is_enclave)) | python | def get_correlated_reports(self, indicators, enclave_ids=None, is_enclave=True):
"""
Uses the |get_correlated_reports_page| method to create a generator that returns each successive report.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:return: The generator.
"""
return Page.get_generator(page_generator=self._get_correlated_reports_page_generator(indicators,
enclave_ids,
is_enclave)) | [
"def",
"get_correlated_reports",
"(",
"self",
",",
"indicators",
",",
"enclave_ids",
"=",
"None",
",",
"is_enclave",
"=",
"True",
")",
":",
"return",
"Page",
".",
"get_generator",
"(",
"page_generator",
"=",
"self",
".",
"_get_correlated_reports_page_generator",
"... | Uses the |get_correlated_reports_page| method to create a generator that returns each successive report.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:return: The generator. | [
"Uses",
"the",
"|get_correlated_reports_page|",
"method",
"to",
"create",
"a",
"generator",
"that",
"returns",
"each",
"successive",
"report",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L398-L410 | train | 43,844 |
trustar/trustar-python | trustar/report_client.py | ReportClient._search_reports_page_generator | def _search_reports_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None,
start_page=0,
page_size=None):
"""
Creates a generator from the |search_reports_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.search_reports_page, search_term, enclave_ids, from_time, to_time, tags,
excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | python | def _search_reports_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None,
start_page=0,
page_size=None):
"""
Creates a generator from the |search_reports_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator.
"""
get_page = functools.partial(self.search_reports_page, search_term, enclave_ids, from_time, to_time, tags,
excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | [
"def",
"_search_reports_page_generator",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
",",
"start_page"... | Creates a generator from the |search_reports_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:param int start_page: The page to start on.
:param page_size: The size of each page.
:return: The generator. | [
"Creates",
"a",
"generator",
"from",
"the",
"|search_reports_page|",
"method",
"that",
"returns",
"each",
"successive",
"page",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L412-L439 | train | 43,845 |
trustar/trustar-python | trustar/report_client.py | ReportClient.search_reports | def search_reports(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_reports_page| method to create a generator that returns each successive report.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:return: The generator of Report objects. Note that the body attributes of these reports will be ``None``.
"""
return Page.get_generator(page_generator=self._search_reports_page_generator(search_term, enclave_ids,
from_time, to_time, tags,
excluded_tags)) | python | def search_reports(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_reports_page| method to create a generator that returns each successive report.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:return: The generator of Report objects. Note that the body attributes of these reports will be ``None``.
"""
return Page.get_generator(page_generator=self._search_reports_page_generator(search_term, enclave_ids,
from_time, to_time, tags,
excluded_tags)) | [
"def",
"search_reports",
"(",
"self",
",",
"search_term",
"=",
"None",
",",
"enclave_ids",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"excluded_tags",
"=",
"None",
")",
":",
"return",
"Page",
... | Uses the |search_reports_page| method to create a generator that returns each successive report.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
default reports from all of user's enclaves are returned)
:param int from_time: start of time window in milliseconds since epoch (optional)
:param int to_time: end of time window in milliseconds since epoch (optional)
:param list(str) tags: Name (or list of names) of tag(s) to filter reports by. Only reports containing
ALL of these tags will be returned. (optional)
:param list(str) excluded_tags: Reports containing ANY of these tags will be excluded from the results.
:return: The generator of Report objects. Note that the body attributes of these reports will be ``None``. | [
"Uses",
"the",
"|search_reports_page|",
"method",
"to",
"create",
"a",
"generator",
"that",
"returns",
"each",
"successive",
"report",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/report_client.py#L441-L464 | train | 43,846 |
trustar/trustar-python | trustar/utils.py | parse_boolean | def parse_boolean(value):
"""
Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean
"""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_types):
value = value.lower()
if value == 'false':
return False
if value == 'true':
return True
raise ValueError("Could not convert value to boolean: {}".format(value)) | python | def parse_boolean(value):
"""
Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean
"""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_types):
value = value.lower()
if value == 'false':
return False
if value == 'true':
return True
raise ValueError("Could not convert value to boolean: {}".format(value)) | [
"def",
"parse_boolean",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=... | Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean | [
"Coerce",
"a",
"value",
"to",
"boolean",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/utils.py#L117-L138 | train | 43,847 |
trustar/trustar-python | trustar/trustar.py | TruStar.config_from_file | def config_from_file(config_file_path, config_role):
"""
Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The section within the file to use.
:return: The configuration dictionary.
"""
# read config file depending on filetype, parse into dictionary
ext = os.path.splitext(config_file_path)[-1]
if ext in ['.conf', '.ini']:
config_parser = configparser.RawConfigParser()
config_parser.read(config_file_path)
roles = dict(config_parser)
elif ext in ['.json', '.yml', '.yaml']:
with open(config_file_path, 'r') as f:
roles = yaml.safe_load(f)
else:
raise IOError("Unrecognized filetype for config file '%s'" % config_file_path)
# ensure that config file has indicated role
if config_role in roles:
config = dict(roles[config_role])
else:
raise KeyError("Could not find role %s" % config_role)
# parse enclave ids
if 'enclave_ids' in config:
# if id has all numeric characters, will be parsed as an int, so convert to string
if isinstance(config['enclave_ids'], int):
config['enclave_ids'] = str(config['enclave_ids'])
# split comma separated list if necessary
if isinstance(config['enclave_ids'], string_types):
config['enclave_ids'] = config['enclave_ids'].split(',')
elif not isinstance(config['enclave_ids'], list):
raise Exception("'enclave_ids' must be a list or a comma-separated list")
# strip out whitespace
config['enclave_ids'] = [str(x).strip() for x in config['enclave_ids'] if x is not None]
else:
# default to empty list
config['enclave_ids'] = []
return config | python | def config_from_file(config_file_path, config_role):
"""
Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The section within the file to use.
:return: The configuration dictionary.
"""
# read config file depending on filetype, parse into dictionary
ext = os.path.splitext(config_file_path)[-1]
if ext in ['.conf', '.ini']:
config_parser = configparser.RawConfigParser()
config_parser.read(config_file_path)
roles = dict(config_parser)
elif ext in ['.json', '.yml', '.yaml']:
with open(config_file_path, 'r') as f:
roles = yaml.safe_load(f)
else:
raise IOError("Unrecognized filetype for config file '%s'" % config_file_path)
# ensure that config file has indicated role
if config_role in roles:
config = dict(roles[config_role])
else:
raise KeyError("Could not find role %s" % config_role)
# parse enclave ids
if 'enclave_ids' in config:
# if id has all numeric characters, will be parsed as an int, so convert to string
if isinstance(config['enclave_ids'], int):
config['enclave_ids'] = str(config['enclave_ids'])
# split comma separated list if necessary
if isinstance(config['enclave_ids'], string_types):
config['enclave_ids'] = config['enclave_ids'].split(',')
elif not isinstance(config['enclave_ids'], list):
raise Exception("'enclave_ids' must be a list or a comma-separated list")
# strip out whitespace
config['enclave_ids'] = [str(x).strip() for x in config['enclave_ids'] if x is not None]
else:
# default to empty list
config['enclave_ids'] = []
return config | [
"def",
"config_from_file",
"(",
"config_file_path",
",",
"config_role",
")",
":",
"# read config file depending on filetype, parse into dictionary",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"config_file_path",
")",
"[",
"-",
"1",
"]",
"if",
"ext",
"in",
... | Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The section within the file to use.
:return: The configuration dictionary. | [
"Create",
"a",
"configuration",
"dictionary",
"from",
"a",
"config",
"file",
"section",
".",
"This",
"dictionary",
"is",
"what",
"the",
"TruStar",
"class",
"constructor",
"ultimately",
"requires",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L213-L257 | train | 43,848 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_version | def get_version(self):
"""
Get the version number of the API.
Example:
>>> ts.get_version()
1.3
"""
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n') | python | def get_version(self):
"""
Get the version number of the API.
Example:
>>> ts.get_version()
1.3
"""
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n') | [
"def",
"get_version",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"version\"",
")",
".",
"content",
"if",
"isinstance",
"(",
"result",
",",
"bytes",
")",
":",
"result",
"=",
"result",
".",
"decode",
"(",
"'utf-8'",
... | Get the version number of the API.
Example:
>>> ts.get_version()
1.3 | [
"Get",
"the",
"version",
"number",
"of",
"the",
"API",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L284-L299 | train | 43,849 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_user_enclaves | def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.get("enclaves")
return [EnclavePermissions.from_dict(enclave) for enclave in resp.json()] | python | def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.get("enclaves")
return [EnclavePermissions.from_dict(enclave) for enclave in resp.json()] | [
"def",
"get_user_enclaves",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"enclaves\"",
")",
"return",
"[",
"EnclavePermissions",
".",
"from_dict",
"(",
"enclave",
")",
"for",
"enclave",
"in",
"resp",
".",
"json",
"(",
")... | Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it. | [
"Gets",
"the",
"list",
"of",
"enclaves",
"that",
"the",
"user",
"has",
"access",
"to",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L301-L310 | train | 43,850 |
trustar/trustar-python | trustar/trustar.py | TruStar.get_request_quotas | def get_request_quotas(self):
"""
Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects.
"""
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | python | def get_request_quotas(self):
"""
Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects.
"""
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | [
"def",
"get_request_quotas",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"request-quotas\"",
")",
"return",
"[",
"RequestQuota",
".",
"from_dict",
"(",
"quota",
")",
"for",
"quota",
"in",
"resp",
".",
"json",
"(",
")",
... | Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects. | [
"Gets",
"the",
"request",
"quotas",
"for",
"the",
"user",
"s",
"company",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/trustar.py#L312-L320 | train | 43,851 |
trustar/trustar-python | trustar/logger.py | configure_logging | def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
# construct error logger
error_logger = logging.getLogger("error")
# log all uncaught exceptions
def log_exception(exc_type, exc_value, exc_traceback):
error_logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
# register logging function as exception hook
sys.excepthook = log_exception | python | def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
# construct error logger
error_logger = logging.getLogger("error")
# log all uncaught exceptions
def log_exception(exc_type, exc_value, exc_traceback):
error_logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
# register logging function as exception hook
sys.excepthook = log_exception | [
"def",
"configure_logging",
"(",
")",
":",
"if",
"not",
"parse_boolean",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DISABLE_TRUSTAR_LOGGING'",
")",
")",
":",
"# configure",
"dictConfig",
"(",
"DEFAULT_LOGGING_CONFIG",
")",
"# construct error logger",
"error_logge... | Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored. | [
"Initialize",
"logging",
"configuration",
"to",
"defaults",
".",
"If",
"the",
"environment",
"variable",
"DISABLE_TRUSTAR_LOGGING",
"is",
"set",
"to",
"true",
"this",
"will",
"be",
"ignored",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/logger.py#L73-L92 | train | 43,852 |
trustar/trustar-python | trustar/models/enclave.py | EnclavePermissions.from_enclave | def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,
type=enclave.type) | python | def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,
type=enclave.type) | [
"def",
"from_enclave",
"(",
"cls",
",",
"enclave",
")",
":",
"return",
"EnclavePermissions",
"(",
"id",
"=",
"enclave",
".",
"id",
",",
"name",
"=",
"enclave",
".",
"name",
",",
"type",
"=",
"enclave",
".",
"type",
")"
] | Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object | [
"Create",
"an",
"|EnclavePermissions|",
"object",
"from",
"an",
"|Enclave|",
"object",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enclave.py#L123-L133 | train | 43,853 |
trustar/trustar-python | trustar/tag_client.py | TagClient.get_enclave_tags | def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
"""
params = {'idType': id_type}
resp = self._client.get("reports/%s/tags" % report_id, params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | python | def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
"""
params = {'idType': id_type}
resp = self._client.get("reports/%s/tags" % report_id, params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | [
"def",
"get_enclave_tags",
"(",
"self",
",",
"report_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/%s/tags\"",
"%",
"report_id",
",",
"par... | Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects. | [
"Retrieves",
"all",
"enclave",
"tags",
"present",
"in",
"a",
"specific",
"report",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L20-L31 | train | 43,854 |
trustar/trustar-python | trustar/tag_client.py | TagClient.add_enclave_tag | def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: The ID of the tag that was created.
"""
params = {
'idType': id_type,
'name': name,
'enclaveId': enclave_id
}
resp = self._client.post("reports/%s/tags" % report_id, params=params)
return str(resp.content) | python | def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: The ID of the tag that was created.
"""
params = {
'idType': id_type,
'name': name,
'enclaveId': enclave_id
}
resp = self._client.post("reports/%s/tags" % report_id, params=params)
return str(resp.content) | [
"def",
"add_enclave_tag",
"(",
"self",
",",
"report_id",
",",
"name",
",",
"enclave_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
",",
"'name'",
":",
"name",
",",
"'enclaveId'",
":",
"enclave_id",
"}",
"resp"... | Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: The ID of the tag that was created. | [
"Adds",
"a",
"tag",
"to",
"a",
"specific",
"report",
"for",
"a",
"specific",
"enclave",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L33-L50 | train | 43,855 |
trustar/trustar-python | trustar/tag_client.py | TagClient.delete_enclave_tag | def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or an external ID provided by the user
:return: The response body.
"""
params = {
'idType': id_type
}
self._client.delete("reports/%s/tags/%s" % (report_id, tag_id), params=params) | python | def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or an external ID provided by the user
:return: The response body.
"""
params = {
'idType': id_type
}
self._client.delete("reports/%s/tags/%s" % (report_id, tag_id), params=params) | [
"def",
"delete_enclave_tag",
"(",
"self",
",",
"report_id",
",",
"tag_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"reports/%s/tags/%s\"",
"%",
"(",
"report_i... | Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or an external ID provided by the user
:return: The response body. | [
"Deletes",
"a",
"tag",
"from",
"a",
"specific",
"report",
"in",
"a",
"specific",
"enclave",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L52-L65 | train | 43,856 |
trustar/trustar-python | trustar/tag_client.py | TagClient.get_all_enclave_tags | def get_all_enclave_tags(self, enclave_ids=None):
"""
Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The list of |Tag| objects.
"""
params = {'enclaveIds': enclave_ids}
resp = self._client.get("reports/tags", params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | python | def get_all_enclave_tags(self, enclave_ids=None):
"""
Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The list of |Tag| objects.
"""
params = {'enclaveIds': enclave_ids}
resp = self._client.get("reports/tags", params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | [
"def",
"get_all_enclave_tags",
"(",
"self",
",",
"enclave_ids",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'enclaveIds'",
":",
"enclave_ids",
"}",
"resp",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"reports/tags\"",
",",
"params",
"=",
"params",
")",... | Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The list of |Tag| objects. | [
"Retrieves",
"all",
"tags",
"present",
"in",
"the",
"given",
"enclaves",
".",
"If",
"the",
"enclave",
"list",
"is",
"empty",
"the",
"tags",
"returned",
"include",
"all",
"tags",
"for",
"all",
"enclaves",
"the",
"user",
"has",
"access",
"to",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L67-L78 | train | 43,857 |
trustar/trustar-python | trustar/tag_client.py | TagClient.add_indicator_tag | def add_indicator_tag(self, indicator_value, name, enclave_id):
"""
Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:return: A |Tag| object representing the tag that was created.
"""
data = {
'value': indicator_value,
'tag': {
'name': name,
'enclaveId': enclave_id
}
}
resp = self._client.post("indicators/tags", data=json.dumps(data))
return Tag.from_dict(resp.json()) | python | def add_indicator_tag(self, indicator_value, name, enclave_id):
"""
Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:return: A |Tag| object representing the tag that was created.
"""
data = {
'value': indicator_value,
'tag': {
'name': name,
'enclaveId': enclave_id
}
}
resp = self._client.post("indicators/tags", data=json.dumps(data))
return Tag.from_dict(resp.json()) | [
"def",
"add_indicator_tag",
"(",
"self",
",",
"indicator_value",
",",
"name",
",",
"enclave_id",
")",
":",
"data",
"=",
"{",
"'value'",
":",
"indicator_value",
",",
"'tag'",
":",
"{",
"'name'",
":",
"name",
",",
"'enclaveId'",
":",
"enclave_id",
"}",
"}",
... | Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added
:return: A |Tag| object representing the tag that was created. | [
"Adds",
"a",
"tag",
"to",
"a",
"specific",
"indicator",
"for",
"a",
"specific",
"enclave",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L95-L114 | train | 43,858 |
trustar/trustar-python | trustar/tag_client.py | TagClient.delete_indicator_tag | def delete_indicator_tag(self, indicator_value, tag_id):
"""
Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete
"""
params = {
'value': indicator_value
}
self._client.delete("indicators/tags/%s" % tag_id, params=params) | python | def delete_indicator_tag(self, indicator_value, tag_id):
"""
Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete
"""
params = {
'value': indicator_value
}
self._client.delete("indicators/tags/%s" % tag_id, params=params) | [
"def",
"delete_indicator_tag",
"(",
"self",
",",
"indicator_value",
",",
"tag_id",
")",
":",
"params",
"=",
"{",
"'value'",
":",
"indicator_value",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"indicators/tags/%s\"",
"%",
"tag_id",
",",
"params",
"=",
... | Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete | [
"Deletes",
"a",
"tag",
"from",
"a",
"specific",
"indicator",
"in",
"a",
"specific",
"enclave",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L116-L128 | train | 43,859 |
trustar/trustar-python | trustar/models/tag.py | Tag.to_dict | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag.
"""
if remove_nones:
d = super().to_dict(remove_nones=True)
else:
d = {
'name': self.name,
'id': self.id,
'enclaveId': self.enclave_id
}
return d | python | def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag.
"""
if remove_nones:
d = super().to_dict(remove_nones=True)
else:
d = {
'name': self.name,
'id': self.id,
'enclaveId': self.enclave_id
}
return d | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"if",
"remove_nones",
":",
"d",
"=",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"True",
")",
"else",
":",
"d",
"=",
"{",
"'name'",
":",
"self",
".",
"name... | Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag. | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"tag",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/tag.py#L48-L65 | train | 43,860 |
openvax/topiary | topiary/rna/common.py | check_required_columns | def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
raise ValueError("FPKM tracking file %s missing column '%s'" % (
filename,
column_name)) | python | def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
raise ValueError("FPKM tracking file %s missing column '%s'" % (
filename,
column_name)) | [
"def",
"check_required_columns",
"(",
"df",
",",
"filename",
",",
"required_columns",
")",
":",
"available_columns",
"=",
"set",
"(",
"df",
".",
"columns",
")",
"for",
"column_name",
"in",
"required_columns",
":",
"if",
"column_name",
"not",
"in",
"available_col... | Ensure that all required columns are present in the given dataframe,
otherwise raise an exception. | [
"Ensure",
"that",
"all",
"required",
"columns",
"are",
"present",
"in",
"the",
"given",
"dataframe",
"otherwise",
"raise",
"an",
"exception",
"."
] | 04f0077bc4bf1ad350a0e78c26fa48c55fe7813b | https://github.com/openvax/topiary/blob/04f0077bc4bf1ad350a0e78c26fa48c55fe7813b/topiary/rna/common.py#L49-L59 | train | 43,861 |
gabrielelanaro/chemview | chemview/contrib.py | topology_mdtraj | def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import mdtraj as md
top = {}
top['atom_types'] = [a.element.symbol for a in traj.topology.atoms]
top['atom_names'] = [a.name for a in traj.topology.atoms]
top['bonds'] = [(a.index, b.index) for a, b in traj.topology.bonds]
top['secondary_structure'] = md.compute_dssp(traj[0])[0]
top['residue_types'] = [r.name for r in traj.topology.residues ]
top['residue_indices'] = [ [a.index for a in r.atoms] for r in traj.topology.residues ]
return top | python | def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import mdtraj as md
top = {}
top['atom_types'] = [a.element.symbol for a in traj.topology.atoms]
top['atom_names'] = [a.name for a in traj.topology.atoms]
top['bonds'] = [(a.index, b.index) for a, b in traj.topology.bonds]
top['secondary_structure'] = md.compute_dssp(traj[0])[0]
top['residue_types'] = [r.name for r in traj.topology.residues ]
top['residue_indices'] = [ [a.index for a in r.atoms] for r in traj.topology.residues ]
return top | [
"def",
"topology_mdtraj",
"(",
"traj",
")",
":",
"import",
"mdtraj",
"as",
"md",
"top",
"=",
"{",
"}",
"top",
"[",
"'atom_types'",
"]",
"=",
"[",
"a",
".",
"element",
".",
"symbol",
"for",
"a",
"in",
"traj",
".",
"topology",
".",
"atoms",
"]",
"top... | Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj. | [
"Generate",
"topology",
"spec",
"for",
"the",
"MolecularViewer",
"from",
"mdtraj",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/contrib.py#L3-L20 | train | 43,862 |
gabrielelanaro/chemview | chemview/utils.py | encode_numpy | def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.b64encode(array.data).decode('utf8'),
'type' : array.dtype.name,
'shape': array.shape} | python | def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.b64encode(array.data).decode('utf8'),
'type' : array.dtype.name,
'shape': array.shape} | [
"def",
"encode_numpy",
"(",
"array",
")",
":",
"return",
"{",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"array",
".",
"data",
")",
".",
"decode",
"(",
"'utf8'",
")",
",",
"'type'",
":",
"array",
".",
"dtype",
".",
"name",
",",
"'shape'",
":",
... | Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape | [
"Encode",
"a",
"numpy",
"array",
"as",
"a",
"base64",
"encoded",
"string",
"to",
"be",
"JSON",
"serialized",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/utils.py#L7-L18 | train | 43,863 |
gabrielelanaro/chemview | chemview/install.py | enable_notebook | def enable_notebook(verbose=0):
"""Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets.
"""
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.js', 'three.min.js', 'jquery-ui.min.js',
'context.standalone.css', 'chemview_widget.js',
'trajectory_controls_widget.js', "layout_widget.js",
"components/jquery-fullscreen/jquery.fullscreen.js",
'scales.js']
fns = [resource_filename('chemview', os.path.join('static', f)) for f in libs]
[install_nbextension(fn, verbose=verbose, overwrite=True, user=True) for fn in fns] | python | def enable_notebook(verbose=0):
"""Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets.
"""
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.js', 'three.min.js', 'jquery-ui.min.js',
'context.standalone.css', 'chemview_widget.js',
'trajectory_controls_widget.js', "layout_widget.js",
"components/jquery-fullscreen/jquery.fullscreen.js",
'scales.js']
fns = [resource_filename('chemview', os.path.join('static', f)) for f in libs]
[install_nbextension(fn, verbose=verbose, overwrite=True, user=True) for fn in fns] | [
"def",
"enable_notebook",
"(",
"verbose",
"=",
"0",
")",
":",
"libs",
"=",
"[",
"'objexporter.js'",
",",
"'ArcballControls.js'",
",",
"'filesaver.js'",
",",
"'base64-arraybuffer.js'",
",",
"'context.js'",
",",
"'chemview.js'",
",",
"'three.min.js'",
",",
"'jquery-ui... | Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets. | [
"Enable",
"IPython",
"notebook",
"widgets",
"to",
"be",
"displayed",
"."
] | 2c9768dd23db99e59e27adff2a953bb8ee795fa3 | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/install.py#L14-L29 | train | 43,864 |
trustar/trustar-python | trustar/models/enum.py | Enum.from_string | def from_string(cls, string):
"""
Simply logs a warning if the desired enum value is not found.
:param string:
:return:
"""
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return value
# if not found, log warning and return the value passed in
logger.warning("{} is not a valid enum value for {}.".format(string, cls.__name__))
return string | python | def from_string(cls, string):
"""
Simply logs a warning if the desired enum value is not found.
:param string:
:return:
"""
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return value
# if not found, log warning and return the value passed in
logger.warning("{} is not a valid enum value for {}.".format(string, cls.__name__))
return string | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"# find enum value",
"for",
"attr",
"in",
"dir",
"(",
"cls",
")",
":",
"value",
"=",
"getattr",
"(",
"cls",
",",
"attr",
")",
"if",
"value",
"==",
"string",
":",
"return",
"value",
"# if not fo... | Simply logs a warning if the desired enum value is not found.
:param string:
:return: | [
"Simply",
"logs",
"a",
"warning",
"if",
"the",
"desired",
"enum",
"value",
"is",
"not",
"found",
"."
] | 707d51adc58d68aed7de12a4ca37949cb75cf122 | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/models/enum.py#L16-L32 | train | 43,865 |
valohai/valohai-yaml | valohai_yaml/objs/parameter.py | Parameter.format_cli | def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return None
pass_as_bits = text_type(self.pass_as or self.default_pass_as).split()
env = dict(name=self.name, value=value, v=value)
return [bit.format(**env) for bit in pass_as_bits] | python | def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return None
pass_as_bits = text_type(self.pass_as or self.default_pass_as).split()
env = dict(name=self.name, value=value, v=value)
return [bit.format(**env) for bit in pass_as_bits] | [
"def",
"format_cli",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"(",
"self",
".",
"type",
"==",
"'flag'",
"and",
"not",
"value",
")",
":",
"return",
"None",
"pass_as_bits",
"=",
"text_type",
"(",
"self",
".",
"pass_as",
"... | Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None | [
"Build",
"a",
"single",
"parameter",
"argument",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/parameter.py#L85-L96 | train | 43,866 |
valohai/valohai-yaml | valohai_yaml/validation.py | validate | def validate(yaml, raise_exc=True):
"""
Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered errors after validation.
:type raise_exc: bool
:return: A list of errors encountered.
:rtype: list[jsonschema.exceptions.ValidationError]
"""
data = read_yaml(yaml)
validator = get_validator()
# Nb: this uses a list instead of being a generator function in order to be
# easier to call correctly. (Were it a generator function, a plain
# `validate(..., raise_exc=True)` would not do anything.
errors = list(validator.iter_errors(data))
if errors and raise_exc:
raise ValidationErrors(errors)
return errors | python | def validate(yaml, raise_exc=True):
"""
Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered errors after validation.
:type raise_exc: bool
:return: A list of errors encountered.
:rtype: list[jsonschema.exceptions.ValidationError]
"""
data = read_yaml(yaml)
validator = get_validator()
# Nb: this uses a list instead of being a generator function in order to be
# easier to call correctly. (Were it a generator function, a plain
# `validate(..., raise_exc=True)` would not do anything.
errors = list(validator.iter_errors(data))
if errors and raise_exc:
raise ValidationErrors(errors)
return errors | [
"def",
"validate",
"(",
"yaml",
",",
"raise_exc",
"=",
"True",
")",
":",
"data",
"=",
"read_yaml",
"(",
"yaml",
")",
"validator",
"=",
"get_validator",
"(",
")",
"# Nb: this uses a list instead of being a generator function in order to be",
"# easier to call correctly. (W... | Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered errors after validation.
:type raise_exc: bool
:return: A list of errors encountered.
:rtype: list[jsonschema.exceptions.ValidationError] | [
"Validate",
"the",
"given",
"YAML",
"document",
"and",
"return",
"a",
"list",
"of",
"errors",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/validation.py#L66-L85 | train | 43,867 |
valohai/valohai-yaml | valohai_yaml/objs/parameter_map.py | ParameterMap.build_parameters | def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) or [])
return param_bits | python | def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) or [])
return param_bits | [
"def",
"build_parameters",
"(",
"self",
")",
":",
"param_bits",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"parameters",
":",
"param_bits",
".",
"extend",
"(",
"self",
".",
"build_parameter_by_name",
"(",
"name",
")",
"or",
"[",
"]",
")",
"return",... | Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str] | [
"Build",
"the",
"CLI",
"command",
"line",
"from",
"the",
"parameter",
"values",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/parameter_map.py#L6-L16 | train | 43,868 |
valohai/valohai-yaml | valohai_yaml/objs/config.py | Config.get_step_by | def get_step_by(self, **kwargs):
"""
Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(name="greeting", command='echo HELLO MORDOR')
:param kwargs:
:return: Step object or None
:rtype: valohai_yaml.objs.Step|None
"""
if not kwargs:
return None
for index, step in enumerate(self.steps.values()):
extended_step = dict(step.serialize(), index=index)
# check if kwargs is a subset of extended_step
if all(item in extended_step.items() for item in kwargs.items()):
return step
return None | python | def get_step_by(self, **kwargs):
"""
Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(name="greeting", command='echo HELLO MORDOR')
:param kwargs:
:return: Step object or None
:rtype: valohai_yaml.objs.Step|None
"""
if not kwargs:
return None
for index, step in enumerate(self.steps.values()):
extended_step = dict(step.serialize(), index=index)
# check if kwargs is a subset of extended_step
if all(item in extended_step.items() for item in kwargs.items()):
return step
return None | [
"def",
"get_step_by",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
":",
"return",
"None",
"for",
"index",
",",
"step",
"in",
"enumerate",
"(",
"self",
".",
"steps",
".",
"values",
"(",
")",
")",
":",
"extended_step",
"=",
... | Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(name="greeting", command='echo HELLO MORDOR')
:param kwargs:
:return: Step object or None
:rtype: valohai_yaml.objs.Step|None | [
"Get",
"the",
"first",
"step",
"that",
"matches",
"all",
"the",
"passed",
"named",
"arguments",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/config.py#L65-L87 | train | 43,869 |
valohai/valohai-yaml | valohai_yaml/parsing.py | parse | def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:return: Config object
:rtype: valohai_yaml.objs.Config
"""
data = read_yaml(yaml)
if validate: # pragma: no branch
from .validation import validate
validate(data, raise_exc=True)
return Config.parse(data) | python | def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:return: Config object
:rtype: valohai_yaml.objs.Config
"""
data = read_yaml(yaml)
if validate: # pragma: no branch
from .validation import validate
validate(data, raise_exc=True)
return Config.parse(data) | [
"def",
"parse",
"(",
"yaml",
",",
"validate",
"=",
"True",
")",
":",
"data",
"=",
"read_yaml",
"(",
"yaml",
")",
"if",
"validate",
":",
"# pragma: no branch",
"from",
".",
"validation",
"import",
"validate",
"validate",
"(",
"data",
",",
"raise_exc",
"=",
... | Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:return: Config object
:rtype: valohai_yaml.objs.Config | [
"Parse",
"the",
"given",
"YAML",
"data",
"into",
"a",
"Config",
"object",
"optionally",
"validating",
"it",
"first",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/parsing.py#L6-L21 | train | 43,870 |
valohai/valohai-yaml | valohai_yaml/objs/step.py | Step.build_command | def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to concatenate them, likely using the semicolon or
double ampersands.
It is also possible to override the `command`.
:param parameter_values: Parameter values to augment any parameter defaults.
:type parameter_values: dict[str, object]
:param command: Overriding command; leave falsy to not override.
:type command: str|list[str]|None
:return: list of commands
:rtype: list[str]
"""
command = (command or self.command)
# merge defaults with passed values
# ignore flag default values as they are special
# undefined flag will remain undefined regardless of default value
values = dict(self.get_parameter_defaults(include_flags=False), **parameter_values)
parameter_map = ParameterMap(parameters=self.parameters, values=values)
return build_command(command, parameter_map) | python | def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to concatenate them, likely using the semicolon or
double ampersands.
It is also possible to override the `command`.
:param parameter_values: Parameter values to augment any parameter defaults.
:type parameter_values: dict[str, object]
:param command: Overriding command; leave falsy to not override.
:type command: str|list[str]|None
:return: list of commands
:rtype: list[str]
"""
command = (command or self.command)
# merge defaults with passed values
# ignore flag default values as they are special
# undefined flag will remain undefined regardless of default value
values = dict(self.get_parameter_defaults(include_flags=False), **parameter_values)
parameter_map = ParameterMap(parameters=self.parameters, values=values)
return build_command(command, parameter_map) | [
"def",
"build_command",
"(",
"self",
",",
"parameter_values",
",",
"command",
"=",
"None",
")",
":",
"command",
"=",
"(",
"command",
"or",
"self",
".",
"command",
")",
"# merge defaults with passed values",
"# ignore flag default values as they are special",
"# undefine... | Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to concatenate them, likely using the semicolon or
double ampersands.
It is also possible to override the `command`.
:param parameter_values: Parameter values to augment any parameter defaults.
:type parameter_values: dict[str, object]
:param command: Overriding command; leave falsy to not override.
:type command: str|list[str]|None
:return: list of commands
:rtype: list[str] | [
"Build",
"the",
"command",
"for",
"this",
"step",
"using",
"the",
"given",
"parameter",
"values",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/objs/step.py#L92-L118 | train | 43,871 |
valohai/valohai-yaml | valohai_yaml/lint.py | lint_file | def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr = LintResult()
lr.add_error('could not parse YAML: %s' % e, exception=e)
return lr | python | def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr = LintResult()
lr.add_error('could not parse YAML: %s' % e, exception=e)
return lr | [
"def",
"lint_file",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"yaml",
":",
"try",
":",
"return",
"lint",
"(",
"yaml",
")",
"except",
"Exception",
"as",
"e",
":",
"lr",
"=",
"LintResult",
"(",
")",
"lr",
".... | Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object | [
"Validate",
"&",
"lint",
"file_path",
"and",
"return",
"a",
"LintResult",
"."
] | 3d2e92381633d84cdba039f6905df34c9633a2e1 | https://github.com/valohai/valohai-yaml/blob/3d2e92381633d84cdba039f6905df34c9633a2e1/valohai_yaml/lint.py#L35-L50 | train | 43,872 |
metglobal/django-exchange | exchange/adapters/__init__.py | BaseAdapter.update | def update(self):
"""Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models
"""
currencies = self.get_currencies()
currency_objects = {}
for code, name in currencies:
currency_objects[code], created = Currency.objects.get_or_create(
code=code, defaults={'name': name})
if created:
logger.info('currency: %s created', code)
existing = ExchangeRate.objects.values('source__code',
'target__code',
'id')
existing = {(d['source__code'], d['target__code']): d['id']
for d in existing}
usd_exchange_rates = dict(self.get_exchangerates('USD'))
updates = []
inserts = []
for source in currencies:
for target in currencies:
rate = self._get_rate_through_usd(source.code,
target.code,
usd_exchange_rates)
exchange_rate = ExchangeRate(source=currency_objects[source.code],
target=currency_objects[target.code],
rate=rate)
if (source.code, target.code) in existing:
exchange_rate.id = existing[(source.code, target.code)]
updates.append(exchange_rate)
logger.debug('exchange rate updated %s/%s=%s'
% (source, target, rate))
else:
inserts.append(exchange_rate)
logger.debug('exchange rate created %s/%s=%s'
% (source, target, rate))
logger.info('exchange rates updated for %s' % source.code)
logger.info("Updating %s rows" % len(updates))
update_many(updates)
logger.info("Inserting %s rows" % len(inserts))
insert_many(inserts)
logger.info('saved rates to db') | python | def update(self):
"""Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models
"""
currencies = self.get_currencies()
currency_objects = {}
for code, name in currencies:
currency_objects[code], created = Currency.objects.get_or_create(
code=code, defaults={'name': name})
if created:
logger.info('currency: %s created', code)
existing = ExchangeRate.objects.values('source__code',
'target__code',
'id')
existing = {(d['source__code'], d['target__code']): d['id']
for d in existing}
usd_exchange_rates = dict(self.get_exchangerates('USD'))
updates = []
inserts = []
for source in currencies:
for target in currencies:
rate = self._get_rate_through_usd(source.code,
target.code,
usd_exchange_rates)
exchange_rate = ExchangeRate(source=currency_objects[source.code],
target=currency_objects[target.code],
rate=rate)
if (source.code, target.code) in existing:
exchange_rate.id = existing[(source.code, target.code)]
updates.append(exchange_rate)
logger.debug('exchange rate updated %s/%s=%s'
% (source, target, rate))
else:
inserts.append(exchange_rate)
logger.debug('exchange rate created %s/%s=%s'
% (source, target, rate))
logger.info('exchange rates updated for %s' % source.code)
logger.info("Updating %s rows" % len(updates))
update_many(updates)
logger.info("Inserting %s rows" % len(inserts))
insert_many(inserts)
logger.info('saved rates to db') | [
"def",
"update",
"(",
"self",
")",
":",
"currencies",
"=",
"self",
".",
"get_currencies",
"(",
")",
"currency_objects",
"=",
"{",
"}",
"for",
"code",
",",
"name",
"in",
"currencies",
":",
"currency_objects",
"[",
"code",
"]",
",",
"created",
"=",
"Curren... | Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models | [
"Actual",
"update",
"process",
"goes",
"here",
"using",
"auxialary",
"get_currencies",
"and",
"get_exchangerates",
"methods",
".",
"This",
"method",
"creates",
"or",
"updates",
"corresponding",
"Currency",
"and",
"ExchangeRate",
"models"
] | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/adapters/__init__.py#L17-L63 | train | 43,873 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | redirect | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
res.set_header('Location', urljoin(request.url, url))
raise res | python | def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
res.set_header('Location', urljoin(request.url, url))
raise res | [
"def",
"redirect",
"(",
"url",
",",
"code",
"=",
"None",
")",
":",
"if",
"not",
"code",
":",
"code",
"=",
"303",
"if",
"request",
".",
"get",
"(",
"'SERVER_PROTOCOL'",
")",
"==",
"\"HTTP/1.1\"",
"else",
"302",
"res",
"=",
"response",
".",
"copy",
"("... | Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. | [
"Aborts",
"execution",
"and",
"causes",
"a",
"303",
"or",
"302",
"redirect",
"depending",
"on",
"the",
"HTTP",
"protocol",
"version",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2413-L2422 | train | 43,874 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | _file_iter_range | def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part | python | def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part | [
"def",
"_file_iter_range",
"(",
"fp",
",",
"offset",
",",
"bytes",
",",
"maxread",
"=",
"1024",
"*",
"1024",
")",
":",
"fp",
".",
"seek",
"(",
"offset",
")",
"while",
"bytes",
">",
"0",
":",
"part",
"=",
"fp",
".",
"read",
"(",
"min",
"(",
"bytes... | Yield chunks from a range in a file. No chunk is bigger than maxread. | [
"Yield",
"chunks",
"from",
"a",
"range",
"in",
"a",
"file",
".",
"No",
"chunk",
"is",
"bigger",
"than",
"maxread",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2425-L2432 | train | 43,875 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | debug | def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | python | def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | [
"def",
"debug",
"(",
"mode",
"=",
"True",
")",
":",
"global",
"DEBUG",
"if",
"mode",
":",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"DEBUG",
"=",
"bool",
"(",
"mode",
")"
] | Change the debug level.
There is only one debug level supported at the moment. | [
"Change",
"the",
"debug",
"level",
".",
"There",
"is",
"only",
"one",
"debug",
"level",
"supported",
"at",
"the",
"moment",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2516-L2521 | train | 43,876 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | Router.build | def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except KeyError:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0]) | python | def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except KeyError:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0]) | [
"def",
"build",
"(",
"self",
",",
"_name",
",",
"*",
"anons",
",",
"*",
"*",
"query",
")",
":",
"builder",
"=",
"self",
".",
"builder",
".",
"get",
"(",
"_name",
")",
"if",
"not",
"builder",
":",
"raise",
"RouteBuildError",
"(",
"\"No route with that n... | Build an URL by filling the wildcards in a rule. | [
"Build",
"an",
"URL",
"by",
"filling",
"the",
"wildcards",
"in",
"a",
"rule",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L400-L409 | train | 43,877 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | FormsDict.getunicode | def getunicode(self, name, default=None, encoding=None):
''' Return the value as a unicode string, or the default. '''
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | python | def getunicode(self, name, default=None, encoding=None):
''' Return the value as a unicode string, or the default. '''
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | [
"def",
"getunicode",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_fix",
"(",
"self",
"[",
"name",
"]",
",",
"encoding",
")",
"except",
"(",
"UnicodeError",
",",
... | Return the value as a unicode string, or the default. | [
"Return",
"the",
"value",
"as",
"a",
"unicode",
"string",
"or",
"the",
"default",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L1911-L1916 | train | 43,878 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.load_dict | def load_dict(self, source, namespace='', make_namespaces=False):
''' Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'}
'''
stack = [(namespace, source)]
while stack:
prefix, source = stack.pop()
if not isinstance(source, dict):
raise TypeError('Source is not a dict (r)' % type(key))
for key, value in source.items():
if not isinstance(key, str):
raise TypeError('Key is not a string (%r)' % type(key))
full_key = prefix + '.' + key if prefix else key
if isinstance(value, dict):
stack.append((full_key, value))
if make_namespaces:
self[full_key] = self.Namespace(self, full_key)
else:
self[full_key] = value
return self | python | def load_dict(self, source, namespace='', make_namespaces=False):
''' Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'}
'''
stack = [(namespace, source)]
while stack:
prefix, source = stack.pop()
if not isinstance(source, dict):
raise TypeError('Source is not a dict (r)' % type(key))
for key, value in source.items():
if not isinstance(key, str):
raise TypeError('Key is not a string (%r)' % type(key))
full_key = prefix + '.' + key if prefix else key
if isinstance(value, dict):
stack.append((full_key, value))
if make_namespaces:
self[full_key] = self.Namespace(self, full_key)
else:
self[full_key] = value
return self | [
"def",
"load_dict",
"(",
"self",
",",
"source",
",",
"namespace",
"=",
"''",
",",
"make_namespaces",
"=",
"False",
")",
":",
"stack",
"=",
"[",
"(",
"namespace",
",",
"source",
")",
"]",
"while",
"stack",
":",
"prefix",
",",
"source",
"=",
"stack",
"... | Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
{'name.space.key': 'value'} | [
"Import",
"values",
"from",
"a",
"dictionary",
"structure",
".",
"Nesting",
"can",
"be",
"used",
"to",
"represent",
"namespaces",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2097-L2119 | train | 43,879 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.meta_get | def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) | python | def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) | [
"def",
"meta_get",
"(",
"self",
",",
"key",
",",
"metafield",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_meta",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
".",
"get",
"(",
"metafield",
",",
"default",
")"
] | Return the value of a meta field for a key. | [
"Return",
"the",
"value",
"of",
"a",
"meta",
"field",
"for",
"a",
"key",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2154-L2156 | train | 43,880 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ConfigDict.meta_set | def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
self[key] = self[key] | python | def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
self[key] = self[key] | [
"def",
"meta_set",
"(",
"self",
",",
"key",
",",
"metafield",
",",
"value",
")",
":",
"self",
".",
"_meta",
".",
"setdefault",
"(",
"key",
",",
"{",
"}",
")",
"[",
"metafield",
"]",
"=",
"value",
"if",
"key",
"in",
"self",
":",
"self",
"[",
"key"... | Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. | [
"Set",
"the",
"meta",
"field",
"for",
"a",
"key",
"to",
"a",
"new",
"value",
".",
"This",
"triggers",
"the",
"on",
"-",
"change",
"handler",
"for",
"existing",
"keys",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2158-L2163 | train | 43,881 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ResourceManager.lookup | def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. '''
if name not in self.cache or DEBUG:
for path in self.path:
fpath = os.path.join(path, name)
if os.path.isfile(fpath):
if self.cachemode in ('all', 'found'):
self.cache[name] = fpath
return fpath
if self.cachemode == 'all':
self.cache[name] = None
return self.cache[name] | python | def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. '''
if name not in self.cache or DEBUG:
for path in self.path:
fpath = os.path.join(path, name)
if os.path.isfile(fpath):
if self.cachemode in ('all', 'found'):
self.cache[name] = fpath
return fpath
if self.cachemode == 'all':
self.cache[name] = None
return self.cache[name] | [
"def",
"lookup",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"cache",
"or",
"DEBUG",
":",
"for",
"path",
"in",
"self",
".",
"path",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")"... | Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
future lookups. | [
"Search",
"for",
"a",
"resource",
"and",
"return",
"an",
"absolute",
"file",
"path",
"or",
"None",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2312-L2327 | train | 43,882 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | ResourceManager.open | def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(fname, mode=mode, *args, **kwargs) | python | def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(fname, mode=mode, *args, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"mode",
"=",
"'r'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fname",
"=",
"self",
".",
"lookup",
"(",
"name",
")",
"if",
"not",
"fname",
":",
"raise",
"IOError",
"(",
"\"Resource %r not fou... | Find a resource and return a file object, or raise IOError. | [
"Find",
"a",
"resource",
"and",
"return",
"a",
"file",
"object",
"or",
"raise",
"IOError",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2329-L2333 | train | 43,883 |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | SimpleTemplate.render | def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | python | def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"env",
"=",
"{",
"}",
"stdout",
"=",
"[",
"]",
"for",
"dictarg",
"in",
"args",
":",
"env",
".",
"update",
"(",
"dictarg",
")",
"env",
".",
"update",
"(",
"kwargs... | Render the template using keyword arguments as local variables. | [
"Render",
"the",
"template",
"using",
"keyword",
"arguments",
"as",
"local",
"variables",
"."
] | 9eacbfd40a1d35011c2dcea15c303da9636c6b9e | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L3394-L3400 | train | 43,884 |
metglobal/django-exchange | exchange/conversion.py | convert_values | def convert_values(args_list):
"""convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values
"""
rate_map = get_rates(map(itemgetter(1, 2), args_list))
value_map = {}
for value, source, target in args_list:
args = (value, source, target)
if source == target:
value_map[args] = value
else:
value_map[args] = value * rate_map[(source, target)]
return value_map | python | def convert_values(args_list):
"""convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values
"""
rate_map = get_rates(map(itemgetter(1, 2), args_list))
value_map = {}
for value, source, target in args_list:
args = (value, source, target)
if source == target:
value_map[args] = value
else:
value_map[args] = value * rate_map[(source, target)]
return value_map | [
"def",
"convert_values",
"(",
"args_list",
")",
":",
"rate_map",
"=",
"get_rates",
"(",
"map",
"(",
"itemgetter",
"(",
"1",
",",
"2",
")",
",",
"args_list",
")",
")",
"value_map",
"=",
"{",
"}",
"for",
"value",
",",
"source",
",",
"target",
"in",
"ar... | convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values | [
"convert_value",
"in",
"bulk",
"."
] | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L36-L52 | train | 43,885 |
metglobal/django-exchange | exchange/conversion.py | convert_value | def convert_value(value, source_currency, target_currency):
"""Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price``
"""
# If price currency and target currency is same
# return given currency as is
if source_currency == target_currency:
return value
rate = get_rate(source_currency, target_currency)
return value * rate | python | def convert_value(value, source_currency, target_currency):
"""Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price``
"""
# If price currency and target currency is same
# return given currency as is
if source_currency == target_currency:
return value
rate = get_rate(source_currency, target_currency)
return value * rate | [
"def",
"convert_value",
"(",
"value",
",",
"source_currency",
",",
"target_currency",
")",
":",
"# If price currency and target currency is same",
"# return given currency as is",
"if",
"source_currency",
"==",
"target_currency",
":",
"return",
"value",
"rate",
"=",
"get_ra... | Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price`` | [
"Converts",
"the",
"price",
"of",
"a",
"currency",
"to",
"another",
"one",
"using",
"exchange",
"rates"
] | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L100-L123 | train | 43,886 |
metglobal/django-exchange | exchange/conversion.py | convert | def convert(price, currency):
"""Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price``
"""
# If price currency and target currency is same
# return given currency as is
value = convert_value(price.value, price.currency, currency)
return Price(value, currency) | python | def convert(price, currency):
"""Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price``
"""
# If price currency and target currency is same
# return given currency as is
value = convert_value(price.value, price.currency, currency)
return Price(value, currency) | [
"def",
"convert",
"(",
"price",
",",
"currency",
")",
":",
"# If price currency and target currency is same",
"# return given currency as is",
"value",
"=",
"convert_value",
"(",
"price",
".",
"value",
",",
"price",
".",
"currency",
",",
"currency",
")",
"return",
"... | Shorthand function converts a price object instance of a source
currency to target currency
:param price: the price value
:param type: decimal
:param currency: target ISO-4217 currency code
:param type: str
:returns: converted price instance
:rtype: ``Price`` | [
"Shorthand",
"function",
"converts",
"a",
"price",
"object",
"instance",
"of",
"a",
"source",
"currency",
"to",
"target",
"currency"
] | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L126-L143 | train | 43,887 |
metglobal/django-exchange | exchange/utils.py | import_class | def import_class(class_path):
"""imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict'
"""
try:
from django.utils.importlib import import_module
module_name = '.'.join(class_path.split(".")[:-1])
mod = import_module(module_name)
return getattr(mod, class_path.split(".")[-1])
except Exception, detail:
raise ImportError(detail) | python | def import_class(class_path):
"""imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict'
"""
try:
from django.utils.importlib import import_module
module_name = '.'.join(class_path.split(".")[:-1])
mod = import_module(module_name)
return getattr(mod, class_path.split(".")[-1])
except Exception, detail:
raise ImportError(detail) | [
"def",
"import_class",
"(",
"class_path",
")",
":",
"try",
":",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"class_path",
".",
"split",
"(",
"\".\"",
")",
"[",
":",
"-",
"1",
... | imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict' | [
"imports",
"and",
"returns",
"given",
"class",
"string",
"."
] | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L5-L25 | train | 43,888 |
metglobal/django-exchange | exchange/utils.py | insert_many | def insert_many(objects, using="default"):
"""Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py
"""
if not objects:
return
import django.db.models
from django.db import connections
from django.db import transaction
con = connections[using]
model = objects[0].__class__
fields = [f for f in model._meta.fields
if not isinstance(f, django.db.models.AutoField)]
parameters = []
for o in objects:
params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
for f in fields)
parameters.append(params)
table = model._meta.db_table
column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
placeholders = ",".join(("%s",) * len(fields))
con.cursor().executemany("insert into %s (%s) values (%s)"
% (table, column_names, placeholders), parameters)
transaction.commit_unless_managed(using=using) | python | def insert_many(objects, using="default"):
"""Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py
"""
if not objects:
return
import django.db.models
from django.db import connections
from django.db import transaction
con = connections[using]
model = objects[0].__class__
fields = [f for f in model._meta.fields
if not isinstance(f, django.db.models.AutoField)]
parameters = []
for o in objects:
params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
for f in fields)
parameters.append(params)
table = model._meta.db_table
column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
placeholders = ",".join(("%s",) * len(fields))
con.cursor().executemany("insert into %s (%s) values (%s)"
% (table, column_names, placeholders), parameters)
transaction.commit_unless_managed(using=using) | [
"def",
"insert_many",
"(",
"objects",
",",
"using",
"=",
"\"default\"",
")",
":",
"if",
"not",
"objects",
":",
"return",
"import",
"django",
".",
"db",
".",
"models",
"from",
"django",
".",
"db",
"import",
"connections",
"from",
"django",
".",
"db",
"imp... | Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py | [
"Insert",
"list",
"of",
"Django",
"objects",
"in",
"one",
"SQL",
"query",
".",
"Objects",
"must",
"be",
"of",
"the",
"same",
"Django",
"model",
".",
"Note",
"that",
"save",
"is",
"not",
"called",
"and",
"signals",
"on",
"the",
"model",
"are",
"not",
"r... | 2133593885e02f42a4ed2ed4be2763c4777a1245 | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/utils.py#L28-L57 | train | 43,889 |
liip/taxi | taxi/timesheet/timesheet.py | TimesheetCollection._timesheets_callback | def _timesheets_callback(self, callback):
"""
Call a method on all the timesheets, aggregate the return values in a
list and return it.
"""
def call(*args, **kwargs):
return_values = []
for timesheet in self:
attr = getattr(timesheet, callback)
if callable(attr):
result = attr(*args, **kwargs)
else:
result = attr
return_values.append(result)
return return_values
return call | python | def _timesheets_callback(self, callback):
"""
Call a method on all the timesheets, aggregate the return values in a
list and return it.
"""
def call(*args, **kwargs):
return_values = []
for timesheet in self:
attr = getattr(timesheet, callback)
if callable(attr):
result = attr(*args, **kwargs)
else:
result = attr
return_values.append(result)
return return_values
return call | [
"def",
"_timesheets_callback",
"(",
"self",
",",
"callback",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return_values",
"=",
"[",
"]",
"for",
"timesheet",
"in",
"self",
":",
"attr",
"=",
"getattr",
"(",
"timesheet",
... | Call a method on all the timesheets, aggregate the return values in a
list and return it. | [
"Call",
"a",
"method",
"on",
"all",
"the",
"timesheets",
"aggregate",
"the",
"return",
"values",
"in",
"a",
"list",
"and",
"return",
"it",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L202-L222 | train | 43,890 |
liip/taxi | taxi/timesheet/timesheet.py | TimesheetCollection.get_new_timesheets_contents | def get_new_timesheets_contents(self):
"""
Return the initial text to be inserted in new timesheets.
"""
popular_aliases = self.get_popular_aliases()
template = ['# Recently used aliases:']
if popular_aliases:
contents = '\n'.join(template + ['# ' + entry for entry, usage in popular_aliases])
else:
contents = ''
return contents | python | def get_new_timesheets_contents(self):
"""
Return the initial text to be inserted in new timesheets.
"""
popular_aliases = self.get_popular_aliases()
template = ['# Recently used aliases:']
if popular_aliases:
contents = '\n'.join(template + ['# ' + entry for entry, usage in popular_aliases])
else:
contents = ''
return contents | [
"def",
"get_new_timesheets_contents",
"(",
"self",
")",
":",
"popular_aliases",
"=",
"self",
".",
"get_popular_aliases",
"(",
")",
"template",
"=",
"[",
"'# Recently used aliases:'",
"]",
"if",
"popular_aliases",
":",
"contents",
"=",
"'\\n'",
".",
"join",
"(",
... | Return the initial text to be inserted in new timesheets. | [
"Return",
"the",
"initial",
"text",
"to",
"be",
"inserted",
"in",
"new",
"timesheets",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/timesheet.py#L299-L311 | train | 43,891 |
liip/taxi | taxi/commands/status.py | status | def status(ctx, date, f, pushed):
"""
Shows the summary of what's going to be committed to the server.
"""
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
except ParseError as e:
ctx.obj['view'].err(e)
else:
ctx.obj['view'].show_status(
timesheet_collection.entries.filter(
date, regroup=ctx.obj['settings']['regroup_entries'],
pushed=False if not pushed else None
)
) | python | def status(ctx, date, f, pushed):
"""
Shows the summary of what's going to be committed to the server.
"""
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
except ParseError as e:
ctx.obj['view'].err(e)
else:
ctx.obj['view'].show_status(
timesheet_collection.entries.filter(
date, regroup=ctx.obj['settings']['regroup_entries'],
pushed=False if not pushed else None
)
) | [
"def",
"status",
"(",
"ctx",
",",
"date",
",",
"f",
",",
"pushed",
")",
":",
"try",
":",
"timesheet_collection",
"=",
"get_timesheet_collection_for_context",
"(",
"ctx",
",",
"f",
")",
"except",
"ParseError",
"as",
"e",
":",
"ctx",
".",
"obj",
"[",
"'vie... | Shows the summary of what's going to be committed to the server. | [
"Shows",
"the",
"summary",
"of",
"what",
"s",
"going",
"to",
"be",
"committed",
"to",
"the",
"server",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/status.py#L15-L29 | train | 43,892 |
liip/taxi | taxi/commands/edit.py | edit | def edit(ctx, file_to_edit, previous_file):
"""
Opens your timesheet file in your favourite editor.
The PREVIOUS_FILE argument can be used to specify which nth previous file
to edit. A value of 1 will edit the previous file, 2 will edit the
second-previous file, etc.
"""
timesheet_collection = None
autofill = not bool(file_to_edit) and previous_file == 0
if not file_to_edit:
file_to_edit = ctx.obj['settings'].get_entries_file_path(False)
# If the file was not specified and if it's the current file, autofill it
if autofill:
try:
timesheet_collection = get_timesheet_collection_for_context(
ctx, file_to_edit
)
except ParseError:
pass
else:
t = timesheet_collection.latest()
if ctx.obj['settings']['auto_add'] != Settings.AUTO_ADD_OPTIONS['NO']:
auto_fill_days = ctx.obj['settings']['auto_fill_days']
if auto_fill_days:
t.prefill(auto_fill_days, limit=None)
t.save()
# Get the path to the file we should open in the editor
timesheet_files = list(reversed(TimesheetCollection.get_files(file_to_edit, previous_file)))
if previous_file >= len(timesheet_files):
ctx.fail("Couldn't find the requested previous file for `%s`." % file_to_edit)
expanded_file_to_edit = list(timesheet_files)[previous_file]
editor = ctx.obj['settings']['editor']
edit_kwargs = {
'filename': expanded_file_to_edit,
'extension': '.tks'
}
if editor:
edit_kwargs['editor'] = editor
click.edit(**edit_kwargs)
try:
# Show the status only for the given file if it was specified with the
# --file option, or for the files specified in the settings otherwise
timesheet_collection = get_timesheet_collection_for_context(
ctx, file_to_edit
)
except ParseError as e:
ctx.obj['view'].err(e)
else:
ctx.obj['view'].show_status(
timesheet_collection.entries.filter(regroup=True, pushed=False)
) | python | def edit(ctx, file_to_edit, previous_file):
"""
Opens your timesheet file in your favourite editor.
The PREVIOUS_FILE argument can be used to specify which nth previous file
to edit. A value of 1 will edit the previous file, 2 will edit the
second-previous file, etc.
"""
timesheet_collection = None
autofill = not bool(file_to_edit) and previous_file == 0
if not file_to_edit:
file_to_edit = ctx.obj['settings'].get_entries_file_path(False)
# If the file was not specified and if it's the current file, autofill it
if autofill:
try:
timesheet_collection = get_timesheet_collection_for_context(
ctx, file_to_edit
)
except ParseError:
pass
else:
t = timesheet_collection.latest()
if ctx.obj['settings']['auto_add'] != Settings.AUTO_ADD_OPTIONS['NO']:
auto_fill_days = ctx.obj['settings']['auto_fill_days']
if auto_fill_days:
t.prefill(auto_fill_days, limit=None)
t.save()
# Get the path to the file we should open in the editor
timesheet_files = list(reversed(TimesheetCollection.get_files(file_to_edit, previous_file)))
if previous_file >= len(timesheet_files):
ctx.fail("Couldn't find the requested previous file for `%s`." % file_to_edit)
expanded_file_to_edit = list(timesheet_files)[previous_file]
editor = ctx.obj['settings']['editor']
edit_kwargs = {
'filename': expanded_file_to_edit,
'extension': '.tks'
}
if editor:
edit_kwargs['editor'] = editor
click.edit(**edit_kwargs)
try:
# Show the status only for the given file if it was specified with the
# --file option, or for the files specified in the settings otherwise
timesheet_collection = get_timesheet_collection_for_context(
ctx, file_to_edit
)
except ParseError as e:
ctx.obj['view'].err(e)
else:
ctx.obj['view'].show_status(
timesheet_collection.entries.filter(regroup=True, pushed=False)
) | [
"def",
"edit",
"(",
"ctx",
",",
"file_to_edit",
",",
"previous_file",
")",
":",
"timesheet_collection",
"=",
"None",
"autofill",
"=",
"not",
"bool",
"(",
"file_to_edit",
")",
"and",
"previous_file",
"==",
"0",
"if",
"not",
"file_to_edit",
":",
"file_to_edit",
... | Opens your timesheet file in your favourite editor.
The PREVIOUS_FILE argument can be used to specify which nth previous file
to edit. A value of 1 will edit the previous file, 2 will edit the
second-previous file, etc. | [
"Opens",
"your",
"timesheet",
"file",
"in",
"your",
"favourite",
"editor",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/edit.py#L16-L75 | train | 43,893 |
liip/taxi | taxi/aliases.py | AliasesDatabase.filter_from_alias | def filter_from_alias(self, alias, backend=None):
"""
Return aliases that start with the given `alias`, optionally filtered
by backend.
"""
def alias_filter(key_item):
key, item = key_item
return ((alias is None or alias in key) and
(backend is None or item.backend == backend))
items = six.moves.filter(alias_filter, six.iteritems(self))
aliases = collections.OrderedDict(sorted(items, key=lambda a: a[0].lower()))
return aliases | python | def filter_from_alias(self, alias, backend=None):
"""
Return aliases that start with the given `alias`, optionally filtered
by backend.
"""
def alias_filter(key_item):
key, item = key_item
return ((alias is None or alias in key) and
(backend is None or item.backend == backend))
items = six.moves.filter(alias_filter, six.iteritems(self))
aliases = collections.OrderedDict(sorted(items, key=lambda a: a[0].lower()))
return aliases | [
"def",
"filter_from_alias",
"(",
"self",
",",
"alias",
",",
"backend",
"=",
"None",
")",
":",
"def",
"alias_filter",
"(",
"key_item",
")",
":",
"key",
",",
"item",
"=",
"key_item",
"return",
"(",
"(",
"alias",
"is",
"None",
"or",
"alias",
"in",
"key",
... | Return aliases that start with the given `alias`, optionally filtered
by backend. | [
"Return",
"aliases",
"that",
"start",
"with",
"the",
"given",
"alias",
"optionally",
"filtered",
"by",
"backend",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/aliases.py#L119-L134 | train | 43,894 |
liip/taxi | taxi/commands/clean_aliases.py | clean_aliases | def clean_aliases(ctx, force_yes):
"""
Removes aliases from your config file that point to inactive projects.
"""
inactive_aliases = []
for (alias, mapping) in six.iteritems(aliases_database):
# Ignore local aliases
if mapping.mapping is None:
continue
project = ctx.obj['projects_db'].get(mapping.mapping[0],
mapping.backend)
if (project is None or not project.is_active() or
(mapping.mapping[1] is not None
and project.get_activity(mapping.mapping[1]) is None)):
inactive_aliases.append(((alias, mapping), project))
if not inactive_aliases:
ctx.obj['view'].msg("No inactive aliases found.")
return
if not force_yes:
confirm = ctx.obj['view'].clean_inactive_aliases(inactive_aliases)
if force_yes or confirm:
ctx.obj['settings'].remove_aliases(
[item[0] for item in inactive_aliases]
)
ctx.obj['settings'].write_config()
ctx.obj['view'].msg("%d inactive aliases have been successfully"
" cleaned." % len(inactive_aliases)) | python | def clean_aliases(ctx, force_yes):
"""
Removes aliases from your config file that point to inactive projects.
"""
inactive_aliases = []
for (alias, mapping) in six.iteritems(aliases_database):
# Ignore local aliases
if mapping.mapping is None:
continue
project = ctx.obj['projects_db'].get(mapping.mapping[0],
mapping.backend)
if (project is None or not project.is_active() or
(mapping.mapping[1] is not None
and project.get_activity(mapping.mapping[1]) is None)):
inactive_aliases.append(((alias, mapping), project))
if not inactive_aliases:
ctx.obj['view'].msg("No inactive aliases found.")
return
if not force_yes:
confirm = ctx.obj['view'].clean_inactive_aliases(inactive_aliases)
if force_yes or confirm:
ctx.obj['settings'].remove_aliases(
[item[0] for item in inactive_aliases]
)
ctx.obj['settings'].write_config()
ctx.obj['view'].msg("%d inactive aliases have been successfully"
" cleaned." % len(inactive_aliases)) | [
"def",
"clean_aliases",
"(",
"ctx",
",",
"force_yes",
")",
":",
"inactive_aliases",
"=",
"[",
"]",
"for",
"(",
"alias",
",",
"mapping",
")",
"in",
"six",
".",
"iteritems",
"(",
"aliases_database",
")",
":",
"# Ignore local aliases",
"if",
"mapping",
".",
"... | Removes aliases from your config file that point to inactive projects. | [
"Removes",
"aliases",
"from",
"your",
"config",
"file",
"that",
"point",
"to",
"inactive",
"projects",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/clean_aliases.py#L16-L48 | train | 43,895 |
liip/taxi | taxi/commands/plugin.py | list_ | def list_(ctx):
"""
Lists installed plugins.
"""
plugins = plugins_registry.get_plugins()
click.echo("\n".join(
["%s (%s)" % p for p in plugins.items()]
)) | python | def list_(ctx):
"""
Lists installed plugins.
"""
plugins = plugins_registry.get_plugins()
click.echo("\n".join(
["%s (%s)" % p for p in plugins.items()]
)) | [
"def",
"list_",
"(",
"ctx",
")",
":",
"plugins",
"=",
"plugins_registry",
".",
"get_plugins",
"(",
")",
"click",
".",
"echo",
"(",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"%s (%s)\"",
"%",
"p",
"for",
"p",
"in",
"plugins",
".",
"items",
"(",
")",
"]",
... | Lists installed plugins. | [
"Lists",
"installed",
"plugins",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/plugin.py#L97-L105 | train | 43,896 |
liip/taxi | taxi/commands/plugin.py | install | def install(ctx, plugin):
"""
Install the given plugin.
"""
ensure_inside_venv(ctx)
plugin_name = get_plugin_name(plugin)
try:
info = get_plugin_info(plugin_name)
except NameError:
echo_error("Plugin {} could not be found.".format(plugin))
sys.exit(1)
except ValueError as e:
echo_error("Unable to retrieve plugin info. "
"Error was:\n\n {}".format(e))
sys.exit(1)
try:
installed_version = pkg_resources.get_distribution(plugin_name).version
except pkg_resources.DistributionNotFound:
installed_version = None
if installed_version is not None and info['version'] == installed_version:
click.echo("You already have the latest version of {} ({}).".format(
plugin, info['version']
))
return
pinned_plugin = '{0}=={1}'.format(plugin_name, info['version'])
try:
run_command([sys.executable, '-m', 'pip', 'install', pinned_plugin])
except subprocess.CalledProcessError as e:
echo_error("Error when trying to install plugin {}. "
"Error was:\n\n {}".format(plugin, e))
sys.exit(1)
echo_success("Plugin {} {} installed successfully.".format(
plugin, info['version']
)) | python | def install(ctx, plugin):
"""
Install the given plugin.
"""
ensure_inside_venv(ctx)
plugin_name = get_plugin_name(plugin)
try:
info = get_plugin_info(plugin_name)
except NameError:
echo_error("Plugin {} could not be found.".format(plugin))
sys.exit(1)
except ValueError as e:
echo_error("Unable to retrieve plugin info. "
"Error was:\n\n {}".format(e))
sys.exit(1)
try:
installed_version = pkg_resources.get_distribution(plugin_name).version
except pkg_resources.DistributionNotFound:
installed_version = None
if installed_version is not None and info['version'] == installed_version:
click.echo("You already have the latest version of {} ({}).".format(
plugin, info['version']
))
return
pinned_plugin = '{0}=={1}'.format(plugin_name, info['version'])
try:
run_command([sys.executable, '-m', 'pip', 'install', pinned_plugin])
except subprocess.CalledProcessError as e:
echo_error("Error when trying to install plugin {}. "
"Error was:\n\n {}".format(plugin, e))
sys.exit(1)
echo_success("Plugin {} {} installed successfully.".format(
plugin, info['version']
)) | [
"def",
"install",
"(",
"ctx",
",",
"plugin",
")",
":",
"ensure_inside_venv",
"(",
"ctx",
")",
"plugin_name",
"=",
"get_plugin_name",
"(",
"plugin",
")",
"try",
":",
"info",
"=",
"get_plugin_info",
"(",
"plugin_name",
")",
"except",
"NameError",
":",
"echo_er... | Install the given plugin. | [
"Install",
"the",
"given",
"plugin",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/plugin.py#L111-L149 | train | 43,897 |
liip/taxi | taxi/commands/plugin.py | uninstall | def uninstall(ctx, plugin):
"""
Uninstall the given plugin.
"""
ensure_inside_venv(ctx)
if plugin not in get_installed_plugins():
echo_error("Plugin {} does not seem to be installed.".format(plugin))
sys.exit(1)
plugin_name = get_plugin_name(plugin)
try:
run_command([sys.executable, '-m', 'pip', 'uninstall', '-y',
plugin_name])
except subprocess.CalledProcessError as e:
echo_error(
"Error when trying to uninstall plugin {}. Error message "
"was:\n\n{}".format(plugin, e.output.decode())
)
sys.exit(1)
else:
echo_success("Plugin {} uninstalled successfully.".format(plugin)) | python | def uninstall(ctx, plugin):
"""
Uninstall the given plugin.
"""
ensure_inside_venv(ctx)
if plugin not in get_installed_plugins():
echo_error("Plugin {} does not seem to be installed.".format(plugin))
sys.exit(1)
plugin_name = get_plugin_name(plugin)
try:
run_command([sys.executable, '-m', 'pip', 'uninstall', '-y',
plugin_name])
except subprocess.CalledProcessError as e:
echo_error(
"Error when trying to uninstall plugin {}. Error message "
"was:\n\n{}".format(plugin, e.output.decode())
)
sys.exit(1)
else:
echo_success("Plugin {} uninstalled successfully.".format(plugin)) | [
"def",
"uninstall",
"(",
"ctx",
",",
"plugin",
")",
":",
"ensure_inside_venv",
"(",
"ctx",
")",
"if",
"plugin",
"not",
"in",
"get_installed_plugins",
"(",
")",
":",
"echo_error",
"(",
"\"Plugin {} does not seem to be installed.\"",
".",
"format",
"(",
"plugin",
... | Uninstall the given plugin. | [
"Uninstall",
"the",
"given",
"plugin",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/plugin.py#L155-L176 | train | 43,898 |
liip/taxi | taxi/timesheet/entry.py | Entry.hours | def hours(self):
"""
Return the number of hours this entry has lasted. If the duration is a tuple with a start and an end time,
the difference between the two times will be calculated. If the duration is a number, it will be returned
as-is.
"""
if not isinstance(self.duration, tuple):
return self.duration
if self.duration[1] is None:
return 0
time_start = self.get_start_time()
# This can happen if the previous entry has a non-tuple duration
# and the current entry has a tuple duration without a start time
if time_start is None:
return 0
now = datetime.datetime.now()
time_start = now.replace(
hour=time_start.hour,
minute=time_start.minute, second=0
)
time_end = now.replace(
hour=self.duration[1].hour,
minute=self.duration[1].minute, second=0
)
total_time = time_end - time_start
total_hours = total_time.seconds / 3600.0
return total_hours | python | def hours(self):
"""
Return the number of hours this entry has lasted. If the duration is a tuple with a start and an end time,
the difference between the two times will be calculated. If the duration is a number, it will be returned
as-is.
"""
if not isinstance(self.duration, tuple):
return self.duration
if self.duration[1] is None:
return 0
time_start = self.get_start_time()
# This can happen if the previous entry has a non-tuple duration
# and the current entry has a tuple duration without a start time
if time_start is None:
return 0
now = datetime.datetime.now()
time_start = now.replace(
hour=time_start.hour,
minute=time_start.minute, second=0
)
time_end = now.replace(
hour=self.duration[1].hour,
minute=self.duration[1].minute, second=0
)
total_time = time_end - time_start
total_hours = total_time.seconds / 3600.0
return total_hours | [
"def",
"hours",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"duration",
",",
"tuple",
")",
":",
"return",
"self",
".",
"duration",
"if",
"self",
".",
"duration",
"[",
"1",
"]",
"is",
"None",
":",
"return",
"0",
"time_start",
... | Return the number of hours this entry has lasted. If the duration is a tuple with a start and an end time,
the difference between the two times will be calculated. If the duration is a number, it will be returned
as-is. | [
"Return",
"the",
"number",
"of",
"hours",
"this",
"entry",
"has",
"lasted",
".",
"If",
"the",
"duration",
"is",
"a",
"tuple",
"with",
"a",
"start",
"and",
"an",
"end",
"time",
"the",
"difference",
"between",
"the",
"two",
"times",
"will",
"be",
"calculat... | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L84-L115 | train | 43,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.