repo
stringlengths 7
54
| path
stringlengths 4
192
| url
stringlengths 87
284
| code
stringlengths 78
104k
| code_tokens
list | docstring
stringlengths 1
46.9k
| docstring_tokens
list | language
stringclasses 1
value | partition
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|
BerkeleyAutomation/perception | perception/image.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L1306-L1346 | def segment_kmeans(self, rgb_weight, num_clusters, hue_weight=0.0):
"""
Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
weighting of RGB distance relative to spatial and hue distance
num_clusters : int
number of clusters to use
hue_weight : float
weighting of hue from hsv relative to spatial and RGB distance
Returns
-------
:obj:`SegmentationImage`
image containing the segment labels
"""
# form features array
label_offset = 1
nonzero_px = np.where(self.data != 0.0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
# get hsv data if specified
color_vals = rgb_weight * \
self._data[nonzero_px[:, 0], nonzero_px[:, 1], :]
if hue_weight > 0.0:
hsv_data = cv2.cvtColor(self.data, cv2.COLOR_BGR2HSV)
color_vals = np.c_[color_vals, hue_weight *
hsv_data[nonzero_px[:, 0], nonzero_px[:, 1], :1]]
features = np.c_[nonzero_px, color_vals.astype(np.float32)]
# perform KMeans clustering
kmeans = sc.KMeans(n_clusters=num_clusters)
labels = kmeans.fit_predict(features)
# create output label array
label_im = np.zeros([self.height, self.width]).astype(np.uint8)
label_im[nonzero_px[:, 0], nonzero_px[:, 1]] = labels + label_offset
return SegmentationImage(label_im, frame=self.frame) | [
"def",
"segment_kmeans",
"(",
"self",
",",
"rgb_weight",
",",
"num_clusters",
",",
"hue_weight",
"=",
"0.0",
")",
":",
"# form features array",
"label_offset",
"=",
"1",
"nonzero_px",
"=",
"np",
".",
"where",
"(",
"self",
".",
"data",
"!=",
"0.0",
")",
"nonzero_px",
"=",
"np",
".",
"c_",
"[",
"nonzero_px",
"[",
"0",
"]",
",",
"nonzero_px",
"[",
"1",
"]",
"]",
"# get hsv data if specified",
"color_vals",
"=",
"rgb_weight",
"*",
"self",
".",
"_data",
"[",
"nonzero_px",
"[",
":",
",",
"0",
"]",
",",
"nonzero_px",
"[",
":",
",",
"1",
"]",
",",
":",
"]",
"if",
"hue_weight",
">",
"0.0",
":",
"hsv_data",
"=",
"cv2",
".",
"cvtColor",
"(",
"self",
".",
"data",
",",
"cv2",
".",
"COLOR_BGR2HSV",
")",
"color_vals",
"=",
"np",
".",
"c_",
"[",
"color_vals",
",",
"hue_weight",
"*",
"hsv_data",
"[",
"nonzero_px",
"[",
":",
",",
"0",
"]",
",",
"nonzero_px",
"[",
":",
",",
"1",
"]",
",",
":",
"1",
"]",
"]",
"features",
"=",
"np",
".",
"c_",
"[",
"nonzero_px",
",",
"color_vals",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"]",
"# perform KMeans clustering",
"kmeans",
"=",
"sc",
".",
"KMeans",
"(",
"n_clusters",
"=",
"num_clusters",
")",
"labels",
"=",
"kmeans",
".",
"fit_predict",
"(",
"features",
")",
"# create output label array",
"label_im",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"height",
",",
"self",
".",
"width",
"]",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"label_im",
"[",
"nonzero_px",
"[",
":",
",",
"0",
"]",
",",
"nonzero_px",
"[",
":",
",",
"1",
"]",
"]",
"=",
"labels",
"+",
"label_offset",
"return",
"SegmentationImage",
"(",
"label_im",
",",
"frame",
"=",
"self",
".",
"frame",
")"
] | Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
weighting of RGB distance relative to spatial and hue distance
num_clusters : int
number of clusters to use
hue_weight : float
weighting of hue from hsv relative to spatial and RGB distance
Returns
-------
:obj:`SegmentationImage`
image containing the segment labels | [
"Segment",
"a",
"color",
"image",
"using",
"KMeans",
"based",
"on",
"spatial",
"and",
"color",
"distances",
".",
"Black",
"pixels",
"will",
"automatically",
"be",
"assigned",
"to",
"their",
"own",
"background",
"cluster",
"."
] | python | train |
expfactory/expfactory | expfactory/variables.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/variables.py#L263-L294 | def validate_header(header, required_fields=None):
'''validate_header ensures that the first row contains the exp_id,
var_name, var_value, and token. Capitalization isn't important, but
ordering is. This criteria is very strict, but it's reasonable
to require.
Parameters
==========
header: the header row, as a list
required_fields: a list of required fields. We derive the required
length from this list.
Does not return, instead exits if malformed. Runs silently if OK.
'''
if required_fields is None:
required_fields = ['exp_id', 'var_name', 'var_value', 'token']
# The required length of the header based on required fields
length = len(required_fields)
# This is very strict, but no reason not to be
header = _validate_row(header, required_length=length)
header = [x.lower() for x in header]
for idx in range(length):
field = header[idx].lower().strip()
if required_fields[idx] != field:
bot.error('Malformed header field %s, exiting.' %field)
sys.exit(1) | [
"def",
"validate_header",
"(",
"header",
",",
"required_fields",
"=",
"None",
")",
":",
"if",
"required_fields",
"is",
"None",
":",
"required_fields",
"=",
"[",
"'exp_id'",
",",
"'var_name'",
",",
"'var_value'",
",",
"'token'",
"]",
"# The required length of the header based on required fields",
"length",
"=",
"len",
"(",
"required_fields",
")",
"# This is very strict, but no reason not to be",
"header",
"=",
"_validate_row",
"(",
"header",
",",
"required_length",
"=",
"length",
")",
"header",
"=",
"[",
"x",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"header",
"]",
"for",
"idx",
"in",
"range",
"(",
"length",
")",
":",
"field",
"=",
"header",
"[",
"idx",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"required_fields",
"[",
"idx",
"]",
"!=",
"field",
":",
"bot",
".",
"error",
"(",
"'Malformed header field %s, exiting.'",
"%",
"field",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | validate_header ensures that the first row contains the exp_id,
var_name, var_value, and token. Capitalization isn't important, but
ordering is. This criteria is very strict, but it's reasonable
to require.
Parameters
==========
header: the header row, as a list
required_fields: a list of required fields. We derive the required
length from this list.
Does not return, instead exits if malformed. Runs silently if OK. | [
"validate_header",
"ensures",
"that",
"the",
"first",
"row",
"contains",
"the",
"exp_id",
"var_name",
"var_value",
"and",
"token",
".",
"Capitalization",
"isn",
"t",
"important",
"but",
"ordering",
"is",
".",
"This",
"criteria",
"is",
"very",
"strict",
"but",
"it",
"s",
"reasonable",
"to",
"require",
".",
"Parameters",
"==========",
"header",
":",
"the",
"header",
"row",
"as",
"a",
"list",
"required_fields",
":",
"a",
"list",
"of",
"required",
"fields",
".",
"We",
"derive",
"the",
"required",
"length",
"from",
"this",
"list",
"."
] | python | train |
Azure/azure-multiapi-storage-python | azure/multiapi/storage/v2015_04_05/table/_request.py | https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/table/_request.py#L49-L62 | def _insert_entity(entity):
'''
Constructs an insert entity request.
'''
_validate_entity(entity)
request = HTTPRequest()
request.method = 'POST'
request.headers = [_DEFAULT_CONTENT_TYPE_HEADER,
_DEFAULT_PREFER_HEADER,
_DEFAULT_ACCEPT_HEADER]
request.body = _get_request_body(_convert_entity_to_json(entity))
return request | [
"def",
"_insert_entity",
"(",
"entity",
")",
":",
"_validate_entity",
"(",
"entity",
")",
"request",
"=",
"HTTPRequest",
"(",
")",
"request",
".",
"method",
"=",
"'POST'",
"request",
".",
"headers",
"=",
"[",
"_DEFAULT_CONTENT_TYPE_HEADER",
",",
"_DEFAULT_PREFER_HEADER",
",",
"_DEFAULT_ACCEPT_HEADER",
"]",
"request",
".",
"body",
"=",
"_get_request_body",
"(",
"_convert_entity_to_json",
"(",
"entity",
")",
")",
"return",
"request"
] | Constructs an insert entity request. | [
"Constructs",
"an",
"insert",
"entity",
"request",
"."
] | python | train |
pywavefront/PyWavefront | pywavefront/visualization.py | https://github.com/pywavefront/PyWavefront/blob/39ee5186cb37750d4654d19ebe43f723ecd01e2f/pywavefront/visualization.py#L134-L138 | def load_image(name):
"""Load an image"""
image = pyglet.image.load(name).texture
verify_dimensions(image)
return image | [
"def",
"load_image",
"(",
"name",
")",
":",
"image",
"=",
"pyglet",
".",
"image",
".",
"load",
"(",
"name",
")",
".",
"texture",
"verify_dimensions",
"(",
"image",
")",
"return",
"image"
] | Load an image | [
"Load",
"an",
"image"
] | python | train |
pallets/werkzeug | examples/simplewiki/actions.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/simplewiki/actions.py#L96-L139 | def on_diff(request, page_name):
"""Show the diff between two revisions."""
old = request.args.get("old", type=int)
new = request.args.get("new", type=int)
error = ""
diff = page = old_rev = new_rev = None
if not (old and new):
error = "No revisions specified."
else:
revisions = dict(
(x.revision_id, x)
for x in Revision.query.filter(
(Revision.revision_id.in_((old, new)))
& (Revision.page_id == Page.page_id)
& (Page.name == page_name)
)
)
if len(revisions) != 2:
error = "At least one of the revisions requested does not exist."
else:
new_rev = revisions[new]
old_rev = revisions[old]
page = old_rev.page
diff = unified_diff(
(old_rev.text + "\n").splitlines(True),
(new_rev.text + "\n").splitlines(True),
page.name,
page.name,
format_datetime(old_rev.timestamp),
format_datetime(new_rev.timestamp),
3,
)
return Response(
generate_template(
"action_diff.html",
error=error,
old_revision=old_rev,
new_revision=new_rev,
page=page,
diff=diff,
)
) | [
"def",
"on_diff",
"(",
"request",
",",
"page_name",
")",
":",
"old",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"old\"",
",",
"type",
"=",
"int",
")",
"new",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"new\"",
",",
"type",
"=",
"int",
")",
"error",
"=",
"\"\"",
"diff",
"=",
"page",
"=",
"old_rev",
"=",
"new_rev",
"=",
"None",
"if",
"not",
"(",
"old",
"and",
"new",
")",
":",
"error",
"=",
"\"No revisions specified.\"",
"else",
":",
"revisions",
"=",
"dict",
"(",
"(",
"x",
".",
"revision_id",
",",
"x",
")",
"for",
"x",
"in",
"Revision",
".",
"query",
".",
"filter",
"(",
"(",
"Revision",
".",
"revision_id",
".",
"in_",
"(",
"(",
"old",
",",
"new",
")",
")",
")",
"&",
"(",
"Revision",
".",
"page_id",
"==",
"Page",
".",
"page_id",
")",
"&",
"(",
"Page",
".",
"name",
"==",
"page_name",
")",
")",
")",
"if",
"len",
"(",
"revisions",
")",
"!=",
"2",
":",
"error",
"=",
"\"At least one of the revisions requested does not exist.\"",
"else",
":",
"new_rev",
"=",
"revisions",
"[",
"new",
"]",
"old_rev",
"=",
"revisions",
"[",
"old",
"]",
"page",
"=",
"old_rev",
".",
"page",
"diff",
"=",
"unified_diff",
"(",
"(",
"old_rev",
".",
"text",
"+",
"\"\\n\"",
")",
".",
"splitlines",
"(",
"True",
")",
",",
"(",
"new_rev",
".",
"text",
"+",
"\"\\n\"",
")",
".",
"splitlines",
"(",
"True",
")",
",",
"page",
".",
"name",
",",
"page",
".",
"name",
",",
"format_datetime",
"(",
"old_rev",
".",
"timestamp",
")",
",",
"format_datetime",
"(",
"new_rev",
".",
"timestamp",
")",
",",
"3",
",",
")",
"return",
"Response",
"(",
"generate_template",
"(",
"\"action_diff.html\"",
",",
"error",
"=",
"error",
",",
"old_revision",
"=",
"old_rev",
",",
"new_revision",
"=",
"new_rev",
",",
"page",
"=",
"page",
",",
"diff",
"=",
"diff",
",",
")",
")"
] | Show the diff between two revisions. | [
"Show",
"the",
"diff",
"between",
"two",
"revisions",
"."
] | python | train |
rackerlabs/simpl | simpl/config.py | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/config.py#L685-L703 | def load_options(self, argv=None, keyring_namespace=None):
"""Find settings from all sources.
Only performs data type validation. Does not perform validation on
required, extra/unknown, or mutually exclusive options. To perform that
call `validate_config`.
"""
defaults = self.get_defaults()
args = self.cli_values(argv=argv)
env = self.parse_env()
secrets = self.parse_keyring(keyring_namespace)
ini = self.parse_ini()
results = defaults
results.update(ini)
results.update(secrets)
results.update(env)
results.update(args)
return results | [
"def",
"load_options",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"keyring_namespace",
"=",
"None",
")",
":",
"defaults",
"=",
"self",
".",
"get_defaults",
"(",
")",
"args",
"=",
"self",
".",
"cli_values",
"(",
"argv",
"=",
"argv",
")",
"env",
"=",
"self",
".",
"parse_env",
"(",
")",
"secrets",
"=",
"self",
".",
"parse_keyring",
"(",
"keyring_namespace",
")",
"ini",
"=",
"self",
".",
"parse_ini",
"(",
")",
"results",
"=",
"defaults",
"results",
".",
"update",
"(",
"ini",
")",
"results",
".",
"update",
"(",
"secrets",
")",
"results",
".",
"update",
"(",
"env",
")",
"results",
".",
"update",
"(",
"args",
")",
"return",
"results"
] | Find settings from all sources.
Only performs data type validation. Does not perform validation on
required, extra/unknown, or mutually exclusive options. To perform that
call `validate_config`. | [
"Find",
"settings",
"from",
"all",
"sources",
"."
] | python | train |
coderholic/pyradio | pyradio/radio.py | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/radio.py#L442-L468 | def _goto_playing_station(self, changing_playlist=False):
""" make sure playing station is visible """
if (self.player.isPlaying() or self.operation_mode == PLAYLIST_MODE) and \
(self.selection != self.playing or changing_playlist):
if changing_playlist:
self.startPos = 0
max_lines = self.bodyMaxY - 2
if logger.isEnabledFor(logging.INFO):
logger.info('max_lines = {0}, self.playing = {1}'.format(max_lines, self.playing))
if self.number_of_items < max_lines:
self.startPos = 0
elif self.playing < self.startPos or \
self.playing >= self.startPos + max_lines:
if logger.isEnabledFor(logging.INFO):
logger.info('=== _goto:adjusting startPos')
if self.playing < max_lines:
self.startPos = 0
if self.playing - int(max_lines/2) > 0:
self.startPos = self.playing - int(max_lines/2)
elif self.playing > self.number_of_items - max_lines:
self.startPos = self.number_of_items - max_lines
else:
self.startPos = int(self.playing+1/max_lines) - int(max_lines/2)
if logger.isEnabledFor(logging.INFO):
logger.info('===== _goto:startPos = {0}, changing_playlist = {1}'.format(self.startPos, changing_playlist))
self.selection = self.playing
self.refreshBody() | [
"def",
"_goto_playing_station",
"(",
"self",
",",
"changing_playlist",
"=",
"False",
")",
":",
"if",
"(",
"self",
".",
"player",
".",
"isPlaying",
"(",
")",
"or",
"self",
".",
"operation_mode",
"==",
"PLAYLIST_MODE",
")",
"and",
"(",
"self",
".",
"selection",
"!=",
"self",
".",
"playing",
"or",
"changing_playlist",
")",
":",
"if",
"changing_playlist",
":",
"self",
".",
"startPos",
"=",
"0",
"max_lines",
"=",
"self",
".",
"bodyMaxY",
"-",
"2",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"'max_lines = {0}, self.playing = {1}'",
".",
"format",
"(",
"max_lines",
",",
"self",
".",
"playing",
")",
")",
"if",
"self",
".",
"number_of_items",
"<",
"max_lines",
":",
"self",
".",
"startPos",
"=",
"0",
"elif",
"self",
".",
"playing",
"<",
"self",
".",
"startPos",
"or",
"self",
".",
"playing",
">=",
"self",
".",
"startPos",
"+",
"max_lines",
":",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"'=== _goto:adjusting startPos'",
")",
"if",
"self",
".",
"playing",
"<",
"max_lines",
":",
"self",
".",
"startPos",
"=",
"0",
"if",
"self",
".",
"playing",
"-",
"int",
"(",
"max_lines",
"/",
"2",
")",
">",
"0",
":",
"self",
".",
"startPos",
"=",
"self",
".",
"playing",
"-",
"int",
"(",
"max_lines",
"/",
"2",
")",
"elif",
"self",
".",
"playing",
">",
"self",
".",
"number_of_items",
"-",
"max_lines",
":",
"self",
".",
"startPos",
"=",
"self",
".",
"number_of_items",
"-",
"max_lines",
"else",
":",
"self",
".",
"startPos",
"=",
"int",
"(",
"self",
".",
"playing",
"+",
"1",
"/",
"max_lines",
")",
"-",
"int",
"(",
"max_lines",
"/",
"2",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"'===== _goto:startPos = {0}, changing_playlist = {1}'",
".",
"format",
"(",
"self",
".",
"startPos",
",",
"changing_playlist",
")",
")",
"self",
".",
"selection",
"=",
"self",
".",
"playing",
"self",
".",
"refreshBody",
"(",
")"
] | make sure playing station is visible | [
"make",
"sure",
"playing",
"station",
"is",
"visible"
] | python | train |
wmayner/pyphi | pyphi/validate.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L74-L90 | def conditionally_independent(tpm):
"""Validate that the TPM is conditionally independent."""
if not config.VALIDATE_CONDITIONAL_INDEPENDENCE:
return True
tpm = np.array(tpm)
if is_state_by_state(tpm):
there_and_back_again = convert.state_by_node2state_by_state(
convert.state_by_state2state_by_node(tpm))
else:
there_and_back_again = convert.state_by_state2state_by_node(
convert.state_by_node2state_by_state(tpm))
if np.any((tpm - there_and_back_again) >= EPSILON):
raise exceptions.ConditionallyDependentError(
'TPM is not conditionally independent.\n'
'See the conditional independence example in the documentation '
'for more info.')
return True | [
"def",
"conditionally_independent",
"(",
"tpm",
")",
":",
"if",
"not",
"config",
".",
"VALIDATE_CONDITIONAL_INDEPENDENCE",
":",
"return",
"True",
"tpm",
"=",
"np",
".",
"array",
"(",
"tpm",
")",
"if",
"is_state_by_state",
"(",
"tpm",
")",
":",
"there_and_back_again",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"convert",
".",
"state_by_state2state_by_node",
"(",
"tpm",
")",
")",
"else",
":",
"there_and_back_again",
"=",
"convert",
".",
"state_by_state2state_by_node",
"(",
"convert",
".",
"state_by_node2state_by_state",
"(",
"tpm",
")",
")",
"if",
"np",
".",
"any",
"(",
"(",
"tpm",
"-",
"there_and_back_again",
")",
">=",
"EPSILON",
")",
":",
"raise",
"exceptions",
".",
"ConditionallyDependentError",
"(",
"'TPM is not conditionally independent.\\n'",
"'See the conditional independence example in the documentation '",
"'for more info.'",
")",
"return",
"True"
] | Validate that the TPM is conditionally independent. | [
"Validate",
"that",
"the",
"TPM",
"is",
"conditionally",
"independent",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L350-L399 | def convert_ages(Recs, data_model=3):
"""
converts ages to Ma
Parameters
_________
Recs : list of dictionaries in data model by data_model
data_model : MagIC data model (default is 3)
"""
if data_model == 3:
site_key = 'site'
agekey = "age"
keybase = ""
else:
site_key = 'er_site_names'
agekey = find('age', list(rec.keys()))
if agekey != "":
keybase = agekey.split('_')[0] + '_'
New = []
for rec in Recs:
age = ''
if rec[keybase + 'age'] != "":
age = float(rec[keybase + "age"])
elif rec[keybase + 'age_low'] != "" and rec[keybase + 'age_high'] != '':
age = np.mean([rec[keybase + 'age_high'],
rec[keybase + "age_low"]])
# age = float(rec[keybase + 'age_low']) + old_div(
# (float(rec[keybase + 'age_high']) - float(rec[keybase + 'age_low'])), 2.)
if age != '':
rec[keybase + 'age_unit']
if rec[keybase + 'age_unit'] == 'Ma':
rec[keybase + 'age'] = '%10.4e' % (age)
elif rec[keybase + 'age_unit'] == 'ka' or rec[keybase + 'age_unit'] == 'Ka':
rec[keybase + 'age'] = '%10.4e' % (age * .001)
elif rec[keybase + 'age_unit'] == 'Years AD (+/-)':
rec[keybase + 'age'] = '%10.4e' % ((2011 - age) * 1e-6)
elif rec[keybase + 'age_unit'] == 'Years BP':
rec[keybase + 'age'] = '%10.4e' % ((age) * 1e-6)
rec[keybase + 'age_unit'] = 'Ma'
New.append(rec)
else:
if 'site_key' in list(rec.keys()):
print('problem in convert_ages:', rec['site_key'])
elif 'er_site_name' in list(rec.keys()):
print('problem in convert_ages:', rec['site_key'])
else:
print('problem in convert_ages:', rec)
if len(New) == 0:
print('no age key:', rec)
return New | [
"def",
"convert_ages",
"(",
"Recs",
",",
"data_model",
"=",
"3",
")",
":",
"if",
"data_model",
"==",
"3",
":",
"site_key",
"=",
"'site'",
"agekey",
"=",
"\"age\"",
"keybase",
"=",
"\"\"",
"else",
":",
"site_key",
"=",
"'er_site_names'",
"agekey",
"=",
"find",
"(",
"'age'",
",",
"list",
"(",
"rec",
".",
"keys",
"(",
")",
")",
")",
"if",
"agekey",
"!=",
"\"\"",
":",
"keybase",
"=",
"agekey",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"+",
"'_'",
"New",
"=",
"[",
"]",
"for",
"rec",
"in",
"Recs",
":",
"age",
"=",
"''",
"if",
"rec",
"[",
"keybase",
"+",
"'age'",
"]",
"!=",
"\"\"",
":",
"age",
"=",
"float",
"(",
"rec",
"[",
"keybase",
"+",
"\"age\"",
"]",
")",
"elif",
"rec",
"[",
"keybase",
"+",
"'age_low'",
"]",
"!=",
"\"\"",
"and",
"rec",
"[",
"keybase",
"+",
"'age_high'",
"]",
"!=",
"''",
":",
"age",
"=",
"np",
".",
"mean",
"(",
"[",
"rec",
"[",
"keybase",
"+",
"'age_high'",
"]",
",",
"rec",
"[",
"keybase",
"+",
"\"age_low\"",
"]",
"]",
")",
"# age = float(rec[keybase + 'age_low']) + old_div(",
"# (float(rec[keybase + 'age_high']) - float(rec[keybase + 'age_low'])), 2.)",
"if",
"age",
"!=",
"''",
":",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"if",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"==",
"'Ma'",
":",
"rec",
"[",
"keybase",
"+",
"'age'",
"]",
"=",
"'%10.4e'",
"%",
"(",
"age",
")",
"elif",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"==",
"'ka'",
"or",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"==",
"'Ka'",
":",
"rec",
"[",
"keybase",
"+",
"'age'",
"]",
"=",
"'%10.4e'",
"%",
"(",
"age",
"*",
".001",
")",
"elif",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"==",
"'Years AD (+/-)'",
":",
"rec",
"[",
"keybase",
"+",
"'age'",
"]",
"=",
"'%10.4e'",
"%",
"(",
"(",
"2011",
"-",
"age",
")",
"*",
"1e-6",
")",
"elif",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"==",
"'Years BP'",
":",
"rec",
"[",
"keybase",
"+",
"'age'",
"]",
"=",
"'%10.4e'",
"%",
"(",
"(",
"age",
")",
"*",
"1e-6",
")",
"rec",
"[",
"keybase",
"+",
"'age_unit'",
"]",
"=",
"'Ma'",
"New",
".",
"append",
"(",
"rec",
")",
"else",
":",
"if",
"'site_key'",
"in",
"list",
"(",
"rec",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"'problem in convert_ages:'",
",",
"rec",
"[",
"'site_key'",
"]",
")",
"elif",
"'er_site_name'",
"in",
"list",
"(",
"rec",
".",
"keys",
"(",
")",
")",
":",
"print",
"(",
"'problem in convert_ages:'",
",",
"rec",
"[",
"'site_key'",
"]",
")",
"else",
":",
"print",
"(",
"'problem in convert_ages:'",
",",
"rec",
")",
"if",
"len",
"(",
"New",
")",
"==",
"0",
":",
"print",
"(",
"'no age key:'",
",",
"rec",
")",
"return",
"New"
] | converts ages to Ma
Parameters
_________
Recs : list of dictionaries in data model by data_model
data_model : MagIC data model (default is 3) | [
"converts",
"ages",
"to",
"Ma",
"Parameters",
"_________",
"Recs",
":",
"list",
"of",
"dictionaries",
"in",
"data",
"model",
"by",
"data_model",
"data_model",
":",
"MagIC",
"data",
"model",
"(",
"default",
"is",
"3",
")"
] | python | train |
ev3dev/ev3dev-lang-python | ev3dev2/motor.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2434-L2584 | def angle_to_speed_percentage(angle):
"""
The following graphic illustrates the **motor power outputs** for the
left and right motors based on where the joystick is pointing, of the
form ``(left power, right power)``::
(1, 1)
. . . . . . .
. | .
. | .
(0, 1) . | . (1, 0)
. | .
. | .
. | .
. | .
. | .
. | x-axis .
(-1, 1) .---------------------------------------. (1, -1)
. | .
. | .
. | .
. | y-axis .
. | .
(0, -1) . | . (-1, 0)
. | .
. | .
. . . . . . .
(-1, -1)
The joystick is a circle within a circle where the (x, y) coordinates
of the joystick form an angle with the x-axis. Our job is to translate
this angle into the percentage of power that should be sent to each motor.
For instance if the joystick is moved all the way to the top of the circle
we want both motors to move forward with 100% power...that is represented
above by (1, 1). If the joystick is moved all the way to the right side of
the circle we want to rotate clockwise so we move the left motor forward 100%
and the right motor backwards 100%...so (1, -1). If the joystick is at
45 degrees then we move apply (1, 0) to move the left motor forward 100% and
the right motor stays still.
The 8 points shown above are pretty easy. For the points in between those 8
we do some math to figure out what the percentages should be. Take 11.25 degrees
for example. We look at how the motors transition from 0 degrees to 45 degrees:
- the left motor is 1 so that is easy
- the right motor moves from -1 to 0
We determine how far we are between 0 and 45 degrees (11.25 is 25% of 45) so we
know that the right motor should be 25% of the way from -1 to 0...so -0.75 is the
percentage for the right motor at 11.25 degrees.
"""
if 0 <= angle <= 45:
# left motor stays at 1
left_speed_percentage = 1
# right motor transitions from -1 to 0
right_speed_percentage = -1 + (angle/45.0)
elif 45 < angle <= 90:
# left motor stays at 1
left_speed_percentage = 1
# right motor transitions from 0 to 1
percentage_from_45_to_90 = (angle - 45) / 45.0
right_speed_percentage = percentage_from_45_to_90
elif 90 < angle <= 135:
# left motor transitions from 1 to 0
percentage_from_90_to_135 = (angle - 90) / 45.0
left_speed_percentage = 1 - percentage_from_90_to_135
# right motor stays at 1
right_speed_percentage = 1
elif 135 < angle <= 180:
# left motor transitions from 0 to -1
percentage_from_135_to_180 = (angle - 135) / 45.0
left_speed_percentage = -1 * percentage_from_135_to_180
# right motor stays at 1
right_speed_percentage = 1
elif 180 < angle <= 225:
# left motor transitions from -1 to 0
percentage_from_180_to_225 = (angle - 180) / 45.0
left_speed_percentage = -1 + percentage_from_180_to_225
# right motor transitions from 1 to -1
# right motor transitions from 1 to 0 between 180 and 202.5
if angle < 202.5:
percentage_from_180_to_202 = (angle - 180) / 22.5
right_speed_percentage = 1 - percentage_from_180_to_202
# right motor is 0 at 202.5
elif angle == 202.5:
right_speed_percentage = 0
# right motor transitions from 0 to -1 between 202.5 and 225
else:
percentage_from_202_to_225 = (angle - 202.5) / 22.5
right_speed_percentage = -1 * percentage_from_202_to_225
elif 225 < angle <= 270:
# left motor transitions from 0 to -1
percentage_from_225_to_270 = (angle - 225) / 45.0
left_speed_percentage = -1 * percentage_from_225_to_270
# right motor stays at -1
right_speed_percentage = -1
elif 270 < angle <= 315:
# left motor stays at -1
left_speed_percentage = -1
# right motor transitions from -1 to 0
percentage_from_270_to_315 = (angle - 270) / 45.0
right_speed_percentage = -1 + percentage_from_270_to_315
elif 315 < angle <= 360:
# left motor transitions from -1 to 1
# left motor transitions from -1 to 0 between 315 and 337.5
if angle < 337.5:
percentage_from_315_to_337 = (angle - 315) / 22.5
left_speed_percentage = (1 - percentage_from_315_to_337) * -1
# left motor is 0 at 337.5
elif angle == 337.5:
left_speed_percentage = 0
# left motor transitions from 0 to 1 between 337.5 and 360
elif angle > 337.5:
percentage_from_337_to_360 = (angle - 337.5) / 22.5
left_speed_percentage = percentage_from_337_to_360
# right motor transitions from 0 to -1
percentage_from_315_to_360 = (angle - 315) / 45.0
right_speed_percentage = -1 * percentage_from_315_to_360
else:
raise Exception('You created a circle with more than 360 degrees ({})...that is quite the trick'.format(angle))
return (left_speed_percentage * 100, right_speed_percentage * 100) | [
"def",
"angle_to_speed_percentage",
"(",
"angle",
")",
":",
"if",
"0",
"<=",
"angle",
"<=",
"45",
":",
"# left motor stays at 1",
"left_speed_percentage",
"=",
"1",
"# right motor transitions from -1 to 0",
"right_speed_percentage",
"=",
"-",
"1",
"+",
"(",
"angle",
"/",
"45.0",
")",
"elif",
"45",
"<",
"angle",
"<=",
"90",
":",
"# left motor stays at 1",
"left_speed_percentage",
"=",
"1",
"# right motor transitions from 0 to 1",
"percentage_from_45_to_90",
"=",
"(",
"angle",
"-",
"45",
")",
"/",
"45.0",
"right_speed_percentage",
"=",
"percentage_from_45_to_90",
"elif",
"90",
"<",
"angle",
"<=",
"135",
":",
"# left motor transitions from 1 to 0",
"percentage_from_90_to_135",
"=",
"(",
"angle",
"-",
"90",
")",
"/",
"45.0",
"left_speed_percentage",
"=",
"1",
"-",
"percentage_from_90_to_135",
"# right motor stays at 1",
"right_speed_percentage",
"=",
"1",
"elif",
"135",
"<",
"angle",
"<=",
"180",
":",
"# left motor transitions from 0 to -1",
"percentage_from_135_to_180",
"=",
"(",
"angle",
"-",
"135",
")",
"/",
"45.0",
"left_speed_percentage",
"=",
"-",
"1",
"*",
"percentage_from_135_to_180",
"# right motor stays at 1",
"right_speed_percentage",
"=",
"1",
"elif",
"180",
"<",
"angle",
"<=",
"225",
":",
"# left motor transitions from -1 to 0",
"percentage_from_180_to_225",
"=",
"(",
"angle",
"-",
"180",
")",
"/",
"45.0",
"left_speed_percentage",
"=",
"-",
"1",
"+",
"percentage_from_180_to_225",
"# right motor transitions from 1 to -1",
"# right motor transitions from 1 to 0 between 180 and 202.5",
"if",
"angle",
"<",
"202.5",
":",
"percentage_from_180_to_202",
"=",
"(",
"angle",
"-",
"180",
")",
"/",
"22.5",
"right_speed_percentage",
"=",
"1",
"-",
"percentage_from_180_to_202",
"# right motor is 0 at 202.5",
"elif",
"angle",
"==",
"202.5",
":",
"right_speed_percentage",
"=",
"0",
"# right motor transitions from 0 to -1 between 202.5 and 225",
"else",
":",
"percentage_from_202_to_225",
"=",
"(",
"angle",
"-",
"202.5",
")",
"/",
"22.5",
"right_speed_percentage",
"=",
"-",
"1",
"*",
"percentage_from_202_to_225",
"elif",
"225",
"<",
"angle",
"<=",
"270",
":",
"# left motor transitions from 0 to -1",
"percentage_from_225_to_270",
"=",
"(",
"angle",
"-",
"225",
")",
"/",
"45.0",
"left_speed_percentage",
"=",
"-",
"1",
"*",
"percentage_from_225_to_270",
"# right motor stays at -1",
"right_speed_percentage",
"=",
"-",
"1",
"elif",
"270",
"<",
"angle",
"<=",
"315",
":",
"# left motor stays at -1",
"left_speed_percentage",
"=",
"-",
"1",
"# right motor transitions from -1 to 0",
"percentage_from_270_to_315",
"=",
"(",
"angle",
"-",
"270",
")",
"/",
"45.0",
"right_speed_percentage",
"=",
"-",
"1",
"+",
"percentage_from_270_to_315",
"elif",
"315",
"<",
"angle",
"<=",
"360",
":",
"# left motor transitions from -1 to 1",
"# left motor transitions from -1 to 0 between 315 and 337.5",
"if",
"angle",
"<",
"337.5",
":",
"percentage_from_315_to_337",
"=",
"(",
"angle",
"-",
"315",
")",
"/",
"22.5",
"left_speed_percentage",
"=",
"(",
"1",
"-",
"percentage_from_315_to_337",
")",
"*",
"-",
"1",
"# left motor is 0 at 337.5",
"elif",
"angle",
"==",
"337.5",
":",
"left_speed_percentage",
"=",
"0",
"# left motor transitions from 0 to 1 between 337.5 and 360",
"elif",
"angle",
">",
"337.5",
":",
"percentage_from_337_to_360",
"=",
"(",
"angle",
"-",
"337.5",
")",
"/",
"22.5",
"left_speed_percentage",
"=",
"percentage_from_337_to_360",
"# right motor transitions from 0 to -1",
"percentage_from_315_to_360",
"=",
"(",
"angle",
"-",
"315",
")",
"/",
"45.0",
"right_speed_percentage",
"=",
"-",
"1",
"*",
"percentage_from_315_to_360",
"else",
":",
"raise",
"Exception",
"(",
"'You created a circle with more than 360 degrees ({})...that is quite the trick'",
".",
"format",
"(",
"angle",
")",
")",
"return",
"(",
"left_speed_percentage",
"*",
"100",
",",
"right_speed_percentage",
"*",
"100",
")"
] | The following graphic illustrates the **motor power outputs** for the
left and right motors based on where the joystick is pointing, of the
form ``(left power, right power)``::
(1, 1)
. . . . . . .
. | .
. | .
(0, 1) . | . (1, 0)
. | .
. | .
. | .
. | .
. | .
. | x-axis .
(-1, 1) .---------------------------------------. (1, -1)
. | .
. | .
. | .
. | y-axis .
. | .
(0, -1) . | . (-1, 0)
. | .
. | .
. . . . . . .
(-1, -1)
The joystick is a circle within a circle where the (x, y) coordinates
of the joystick form an angle with the x-axis. Our job is to translate
this angle into the percentage of power that should be sent to each motor.
For instance if the joystick is moved all the way to the top of the circle
we want both motors to move forward with 100% power...that is represented
above by (1, 1). If the joystick is moved all the way to the right side of
the circle we want to rotate clockwise so we move the left motor forward 100%
and the right motor backwards 100%...so (1, -1). If the joystick is at
45 degrees then we move apply (1, 0) to move the left motor forward 100% and
the right motor stays still.
The 8 points shown above are pretty easy. For the points in between those 8
we do some math to figure out what the percentages should be. Take 11.25 degrees
for example. We look at how the motors transition from 0 degrees to 45 degrees:
- the left motor is 1 so that is easy
- the right motor moves from -1 to 0
We determine how far we are between 0 and 45 degrees (11.25 is 25% of 45) so we
know that the right motor should be 25% of the way from -1 to 0...so -0.75 is the
percentage for the right motor at 11.25 degrees. | [
"The",
"following",
"graphic",
"illustrates",
"the",
"**",
"motor",
"power",
"outputs",
"**",
"for",
"the",
"left",
"and",
"right",
"motors",
"based",
"on",
"where",
"the",
"joystick",
"is",
"pointing",
"of",
"the",
"form",
"(",
"left",
"power",
"right",
"power",
")",
"::"
] | python | train |
saltstack/salt | salt/states/pip_state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pip_state.py#L184-L273 | def _check_if_installed(prefix,
state_pkg_name,
version_spec,
ignore_installed,
force_reinstall,
upgrade,
user,
cwd,
bin_env,
env_vars,
index_url,
extra_index_url,
pip_list=False,
**kwargs):
'''
Takes a package name and version specification (if any) and checks it is
installed
Keyword arguments include:
pip_list: optional dict of installed pip packages, and their versions,
to search through to check if the package is installed. If not
provided, one will be generated in this function by querying the
system.
Returns:
result: None means the command failed to run
result: True means the package is installed
result: False means the package is not installed
'''
ret = {'result': False, 'comment': None}
# If we are not passed a pip list, get one:
pip_list = salt.utils.data.CaseInsensitiveDict(
pip_list or __salt__['pip.list'](prefix, bin_env=bin_env,
user=user, cwd=cwd,
env_vars=env_vars, **kwargs)
)
# If the package was already installed, check
# the ignore_installed and force_reinstall flags
if ignore_installed is False and prefix in pip_list:
if force_reinstall is False and not upgrade:
# Check desired version (if any) against currently-installed
if (
any(version_spec) and
_fulfills_version_spec(pip_list[prefix], version_spec)
) or (not any(version_spec)):
ret['result'] = True
ret['comment'] = ('Python package {0} was already '
'installed'.format(state_pkg_name))
return ret
if force_reinstall is False and upgrade:
# Check desired version (if any) against currently-installed
include_alpha = False
include_beta = False
include_rc = False
if any(version_spec):
for spec in version_spec:
if 'a' in spec[1]:
include_alpha = True
if 'b' in spec[1]:
include_beta = True
if 'rc' in spec[1]:
include_rc = True
available_versions = __salt__['pip.list_all_versions'](
prefix, bin_env=bin_env, include_alpha=include_alpha,
include_beta=include_beta, include_rc=include_rc, user=user,
cwd=cwd, index_url=index_url, extra_index_url=extra_index_url)
desired_version = ''
if any(version_spec):
for version in reversed(available_versions):
if _fulfills_version_spec(version, version_spec):
desired_version = version
break
else:
desired_version = available_versions[-1]
if not desired_version:
ret['result'] = True
ret['comment'] = ('Python package {0} was already '
'installed and\nthe available upgrade '
'doesn\'t fulfills the version '
'requirements'.format(prefix))
return ret
if _pep440_version_cmp(pip_list[prefix], desired_version) == 0:
ret['result'] = True
ret['comment'] = ('Python package {0} was already '
'installed'.format(state_pkg_name))
return ret
return ret | [
"def",
"_check_if_installed",
"(",
"prefix",
",",
"state_pkg_name",
",",
"version_spec",
",",
"ignore_installed",
",",
"force_reinstall",
",",
"upgrade",
",",
"user",
",",
"cwd",
",",
"bin_env",
",",
"env_vars",
",",
"index_url",
",",
"extra_index_url",
",",
"pip_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"False",
",",
"'comment'",
":",
"None",
"}",
"# If we are not passed a pip list, get one:",
"pip_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"CaseInsensitiveDict",
"(",
"pip_list",
"or",
"__salt__",
"[",
"'pip.list'",
"]",
"(",
"prefix",
",",
"bin_env",
"=",
"bin_env",
",",
"user",
"=",
"user",
",",
"cwd",
"=",
"cwd",
",",
"env_vars",
"=",
"env_vars",
",",
"*",
"*",
"kwargs",
")",
")",
"# If the package was already installed, check",
"# the ignore_installed and force_reinstall flags",
"if",
"ignore_installed",
"is",
"False",
"and",
"prefix",
"in",
"pip_list",
":",
"if",
"force_reinstall",
"is",
"False",
"and",
"not",
"upgrade",
":",
"# Check desired version (if any) against currently-installed",
"if",
"(",
"any",
"(",
"version_spec",
")",
"and",
"_fulfills_version_spec",
"(",
"pip_list",
"[",
"prefix",
"]",
",",
"version_spec",
")",
")",
"or",
"(",
"not",
"any",
"(",
"version_spec",
")",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"(",
"'Python package {0} was already '",
"'installed'",
".",
"format",
"(",
"state_pkg_name",
")",
")",
"return",
"ret",
"if",
"force_reinstall",
"is",
"False",
"and",
"upgrade",
":",
"# Check desired version (if any) against currently-installed",
"include_alpha",
"=",
"False",
"include_beta",
"=",
"False",
"include_rc",
"=",
"False",
"if",
"any",
"(",
"version_spec",
")",
":",
"for",
"spec",
"in",
"version_spec",
":",
"if",
"'a'",
"in",
"spec",
"[",
"1",
"]",
":",
"include_alpha",
"=",
"True",
"if",
"'b'",
"in",
"spec",
"[",
"1",
"]",
":",
"include_beta",
"=",
"True",
"if",
"'rc'",
"in",
"spec",
"[",
"1",
"]",
":",
"include_rc",
"=",
"True",
"available_versions",
"=",
"__salt__",
"[",
"'pip.list_all_versions'",
"]",
"(",
"prefix",
",",
"bin_env",
"=",
"bin_env",
",",
"include_alpha",
"=",
"include_alpha",
",",
"include_beta",
"=",
"include_beta",
",",
"include_rc",
"=",
"include_rc",
",",
"user",
"=",
"user",
",",
"cwd",
"=",
"cwd",
",",
"index_url",
"=",
"index_url",
",",
"extra_index_url",
"=",
"extra_index_url",
")",
"desired_version",
"=",
"''",
"if",
"any",
"(",
"version_spec",
")",
":",
"for",
"version",
"in",
"reversed",
"(",
"available_versions",
")",
":",
"if",
"_fulfills_version_spec",
"(",
"version",
",",
"version_spec",
")",
":",
"desired_version",
"=",
"version",
"break",
"else",
":",
"desired_version",
"=",
"available_versions",
"[",
"-",
"1",
"]",
"if",
"not",
"desired_version",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"(",
"'Python package {0} was already '",
"'installed and\\nthe available upgrade '",
"'doesn\\'t fulfills the version '",
"'requirements'",
".",
"format",
"(",
"prefix",
")",
")",
"return",
"ret",
"if",
"_pep440_version_cmp",
"(",
"pip_list",
"[",
"prefix",
"]",
",",
"desired_version",
")",
"==",
"0",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"(",
"'Python package {0} was already '",
"'installed'",
".",
"format",
"(",
"state_pkg_name",
")",
")",
"return",
"ret",
"return",
"ret"
] | Takes a package name and version specification (if any) and checks it is
installed
Keyword arguments include:
pip_list: optional dict of installed pip packages, and their versions,
to search through to check if the package is installed. If not
provided, one will be generated in this function by querying the
system.
Returns:
result: None means the command failed to run
result: True means the package is installed
result: False means the package is not installed | [
"Takes",
"a",
"package",
"name",
"and",
"version",
"specification",
"(",
"if",
"any",
")",
"and",
"checks",
"it",
"is",
"installed"
] | python | train |
mar10/pyftpsync | ftpsync/targets.py | https://github.com/mar10/pyftpsync/blob/bbdc94186975cdc1cc4f678474bdce08bce7bb76/ftpsync/targets.py#L62-L73 | def _get_encoding_opt(synchronizer, extra_opts, default):
"""Helper to figure out encoding setting inside constructors."""
encoding = default
# if synchronizer and "encoding" in synchronizer.options:
# encoding = synchronizer.options.get("encoding")
if extra_opts and "encoding" in extra_opts:
encoding = extra_opts.get("encoding")
if encoding:
# Normalize name (e.g. 'UTF8' => 'utf-8')
encoding = codecs.lookup(encoding).name
# print("_get_encoding_opt", encoding)
return encoding or None | [
"def",
"_get_encoding_opt",
"(",
"synchronizer",
",",
"extra_opts",
",",
"default",
")",
":",
"encoding",
"=",
"default",
"# if synchronizer and \"encoding\" in synchronizer.options:",
"# encoding = synchronizer.options.get(\"encoding\")",
"if",
"extra_opts",
"and",
"\"encoding\"",
"in",
"extra_opts",
":",
"encoding",
"=",
"extra_opts",
".",
"get",
"(",
"\"encoding\"",
")",
"if",
"encoding",
":",
"# Normalize name (e.g. 'UTF8' => 'utf-8')",
"encoding",
"=",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
".",
"name",
"# print(\"_get_encoding_opt\", encoding)",
"return",
"encoding",
"or",
"None"
] | Helper to figure out encoding setting inside constructors. | [
"Helper",
"to",
"figure",
"out",
"encoding",
"setting",
"inside",
"constructors",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_sketch.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_sketch.py#L55-L62 | def transformer_sketch():
"""Basic transformer_sketch hparams."""
hparams = transformer.transformer_small()
hparams.num_compress_steps = 4
hparams.batch_size = 32
hparams.clip_grad_norm = 2.
hparams.sampling_method = "random"
return hparams | [
"def",
"transformer_sketch",
"(",
")",
":",
"hparams",
"=",
"transformer",
".",
"transformer_small",
"(",
")",
"hparams",
".",
"num_compress_steps",
"=",
"4",
"hparams",
".",
"batch_size",
"=",
"32",
"hparams",
".",
"clip_grad_norm",
"=",
"2.",
"hparams",
".",
"sampling_method",
"=",
"\"random\"",
"return",
"hparams"
] | Basic transformer_sketch hparams. | [
"Basic",
"transformer_sketch",
"hparams",
"."
] | python | train |
donovan-duplessis/pwnurl | pwnurl/models/base.py | https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L38-L44 | def get_by_id(cls, id):
""" Get model by identifier """
if any((isinstance(id, basestring) and id.isdigit(), isinstance(id,
(int, float)))):
return cls.query.get(int(id))
return None | [
"def",
"get_by_id",
"(",
"cls",
",",
"id",
")",
":",
"if",
"any",
"(",
"(",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"and",
"id",
".",
"isdigit",
"(",
")",
",",
"isinstance",
"(",
"id",
",",
"(",
"int",
",",
"float",
")",
")",
")",
")",
":",
"return",
"cls",
".",
"query",
".",
"get",
"(",
"int",
"(",
"id",
")",
")",
"return",
"None"
] | Get model by identifier | [
"Get",
"model",
"by",
"identifier"
] | python | train |
madzak/python-json-logger | src/pythonjsonlogger/jsonlogger.py | https://github.com/madzak/python-json-logger/blob/687cc52260876fd2189cbb7c5856e3fbaff65279/src/pythonjsonlogger/jsonlogger.py#L25-L39 | def merge_record_extra(record, target, reserved):
"""
Merges extra attributes from LogRecord object into target dictionary
:param record: logging.LogRecord
:param target: dict to update
:param reserved: dict or list with reserved keys to skip
"""
for key, value in record.__dict__.items():
# this allows to have numeric keys
if (key not in reserved
and not (hasattr(key, "startswith")
and key.startswith('_'))):
target[key] = value
return target | [
"def",
"merge_record_extra",
"(",
"record",
",",
"target",
",",
"reserved",
")",
":",
"for",
"key",
",",
"value",
"in",
"record",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# this allows to have numeric keys",
"if",
"(",
"key",
"not",
"in",
"reserved",
"and",
"not",
"(",
"hasattr",
"(",
"key",
",",
"\"startswith\"",
")",
"and",
"key",
".",
"startswith",
"(",
"'_'",
")",
")",
")",
":",
"target",
"[",
"key",
"]",
"=",
"value",
"return",
"target"
] | Merges extra attributes from LogRecord object into target dictionary
:param record: logging.LogRecord
:param target: dict to update
:param reserved: dict or list with reserved keys to skip | [
"Merges",
"extra",
"attributes",
"from",
"LogRecord",
"object",
"into",
"target",
"dictionary"
] | python | train |
SatelliteQE/nailgun | nailgun/entity_fields.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entity_fields.py#L156-L161 | def gen_value(self):
"""Return a value suitable for a :class:`StringField`."""
return gen_string(
gen_choice(self.str_type),
gen_integer(self.min_len, self.max_len)
) | [
"def",
"gen_value",
"(",
"self",
")",
":",
"return",
"gen_string",
"(",
"gen_choice",
"(",
"self",
".",
"str_type",
")",
",",
"gen_integer",
"(",
"self",
".",
"min_len",
",",
"self",
".",
"max_len",
")",
")"
] | Return a value suitable for a :class:`StringField`. | [
"Return",
"a",
"value",
"suitable",
"for",
"a",
":",
"class",
":",
"StringField",
"."
] | python | train |
witchard/grole | grole.py | https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L77-L86 | async def _buffer_body(self, reader):
"""
Buffers the body of the request
"""
remaining = int(self.headers.get('Content-Length', 0))
if remaining > 0:
try:
self.data = await reader.readexactly(remaining)
except asyncio.IncompleteReadError:
raise EOFError() | [
"async",
"def",
"_buffer_body",
"(",
"self",
",",
"reader",
")",
":",
"remaining",
"=",
"int",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'Content-Length'",
",",
"0",
")",
")",
"if",
"remaining",
">",
"0",
":",
"try",
":",
"self",
".",
"data",
"=",
"await",
"reader",
".",
"readexactly",
"(",
"remaining",
")",
"except",
"asyncio",
".",
"IncompleteReadError",
":",
"raise",
"EOFError",
"(",
")"
] | Buffers the body of the request | [
"Buffers",
"the",
"body",
"of",
"the",
"request"
] | python | train |
drewsonne/aws-autodiscovery-templater | awsautodiscoverytemplater/command.py | https://github.com/drewsonne/aws-autodiscovery-templater/blob/9ef2edd6a373aeb5d343b841550c210966efe079/awsautodiscoverytemplater/command.py#L128-L146 | def generate_file_template_load(path):
"""
Generate calleable to return the content of the template on disk
:param path:
:return:
"""
path = os.path.expanduser(os.path.abspath(
path
))
def read_file():
"""
Read file from path and return file contents
:return:
"""
with open(path) as template:
return template.read()
return read_file | [
"def",
"generate_file_template_load",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"def",
"read_file",
"(",
")",
":",
"\"\"\"\n Read file from path and return file contents\n :return:\n \"\"\"",
"with",
"open",
"(",
"path",
")",
"as",
"template",
":",
"return",
"template",
".",
"read",
"(",
")",
"return",
"read_file"
] | Generate calleable to return the content of the template on disk
:param path:
:return: | [
"Generate",
"calleable",
"to",
"return",
"the",
"content",
"of",
"the",
"template",
"on",
"disk",
":",
"param",
"path",
":",
":",
"return",
":"
] | python | train |
alex-kostirin/pyatomac | atomac/ldtpd/text.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/text.py#L429-L456 | def pastetext(self, window_name, object_name, position=0):
"""
paste text from start position to end position
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: string
@param position: Position to paste the text, default 0
@type object_name: integer
@return: 1 on success.
@rtype: integer
"""
object_handle = self._get_object_handle(window_name, object_name)
if not object_handle.AXEnabled:
raise LdtpServerException(u"Object %s state disabled" % object_name)
size = object_handle.AXNumberOfCharacters
if position > size:
position = size
if position < 0:
position = 0
clipboard = Clipboard.paste()
data = object_handle.AXValue
object_handle.AXValue = data[:position] + clipboard + data[position:]
return 1 | [
"def",
"pastetext",
"(",
"self",
",",
"window_name",
",",
"object_name",
",",
"position",
"=",
"0",
")",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"if",
"not",
"object_handle",
".",
"AXEnabled",
":",
"raise",
"LdtpServerException",
"(",
"u\"Object %s state disabled\"",
"%",
"object_name",
")",
"size",
"=",
"object_handle",
".",
"AXNumberOfCharacters",
"if",
"position",
">",
"size",
":",
"position",
"=",
"size",
"if",
"position",
"<",
"0",
":",
"position",
"=",
"0",
"clipboard",
"=",
"Clipboard",
".",
"paste",
"(",
")",
"data",
"=",
"object_handle",
".",
"AXValue",
"object_handle",
".",
"AXValue",
"=",
"data",
"[",
":",
"position",
"]",
"+",
"clipboard",
"+",
"data",
"[",
"position",
":",
"]",
"return",
"1"
] | paste text from start position to end position
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: string
@param position: Position to paste the text, default 0
@type object_name: integer
@return: 1 on success.
@rtype: integer | [
"paste",
"text",
"from",
"start",
"position",
"to",
"end",
"position",
"@param",
"window_name",
":",
"Window",
"name",
"to",
"type",
"in",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"window_name",
":",
"string",
"@param",
"object_name",
":",
"Object",
"name",
"to",
"type",
"in",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"object_name",
":",
"string",
"@param",
"position",
":",
"Position",
"to",
"paste",
"the",
"text",
"default",
"0",
"@type",
"object_name",
":",
"integer"
] | python | valid |
CivicSpleen/ambry | ambry/bundle/bundle.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L763-L772 | def warn(self, message):
"""Log an error messsage.
:param message: Log message.
"""
if message not in self._warnings:
self._warnings.append(message)
self.logger.warn(message) | [
"def",
"warn",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
"not",
"in",
"self",
".",
"_warnings",
":",
"self",
".",
"_warnings",
".",
"append",
"(",
"message",
")",
"self",
".",
"logger",
".",
"warn",
"(",
"message",
")"
] | Log an error messsage.
:param message: Log message. | [
"Log",
"an",
"error",
"messsage",
"."
] | python | train |
ssato/python-anyconfig | src/anyconfig/backend/ini.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L103-L121 | def _make_parser(**kwargs):
"""
:return: (keyword args to be used, parser object)
"""
# Optional arguements for configparser.SafeConfigParser{,readfp}
kwargs_0 = filter_options(("defaults", "dict_type", "allow_no_value"),
kwargs)
kwargs_1 = filter_options(("filename", ), kwargs)
try:
parser = configparser.SafeConfigParser(**kwargs_0)
except TypeError:
# .. note::
# It seems ConfigParser.*ConfigParser in python 2.6 does not support
# 'allow_no_value' option parameter, and TypeError will be thrown.
kwargs_0 = filter_options(("defaults", "dict_type"), kwargs)
parser = configparser.SafeConfigParser(**kwargs_0)
return (kwargs_1, parser) | [
"def",
"_make_parser",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Optional arguements for configparser.SafeConfigParser{,readfp}",
"kwargs_0",
"=",
"filter_options",
"(",
"(",
"\"defaults\"",
",",
"\"dict_type\"",
",",
"\"allow_no_value\"",
")",
",",
"kwargs",
")",
"kwargs_1",
"=",
"filter_options",
"(",
"(",
"\"filename\"",
",",
")",
",",
"kwargs",
")",
"try",
":",
"parser",
"=",
"configparser",
".",
"SafeConfigParser",
"(",
"*",
"*",
"kwargs_0",
")",
"except",
"TypeError",
":",
"# .. note::",
"# It seems ConfigParser.*ConfigParser in python 2.6 does not support",
"# 'allow_no_value' option parameter, and TypeError will be thrown.",
"kwargs_0",
"=",
"filter_options",
"(",
"(",
"\"defaults\"",
",",
"\"dict_type\"",
")",
",",
"kwargs",
")",
"parser",
"=",
"configparser",
".",
"SafeConfigParser",
"(",
"*",
"*",
"kwargs_0",
")",
"return",
"(",
"kwargs_1",
",",
"parser",
")"
] | :return: (keyword args to be used, parser object) | [
":",
"return",
":",
"(",
"keyword",
"args",
"to",
"be",
"used",
"parser",
"object",
")"
] | python | train |
praekeltfoundation/seed-message-sender | message_sender/serializers.py | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/serializers.py#L97-L104 | def to_internal_value(self, data):
"""
Adds extra data to the helper_metadata field.
"""
if "session_event" in data:
data["helper_metadata"]["session_event"] = data["session_event"]
return super(InboundSerializer, self).to_internal_value(data) | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"\"session_event\"",
"in",
"data",
":",
"data",
"[",
"\"helper_metadata\"",
"]",
"[",
"\"session_event\"",
"]",
"=",
"data",
"[",
"\"session_event\"",
"]",
"return",
"super",
"(",
"InboundSerializer",
",",
"self",
")",
".",
"to_internal_value",
"(",
"data",
")"
] | Adds extra data to the helper_metadata field. | [
"Adds",
"extra",
"data",
"to",
"the",
"helper_metadata",
"field",
"."
] | python | train |
VingtCinq/python-mailchimp | mailchimp3/entities/storeorders.py | https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/storeorders.py#L50-L109 | def create(self, store_id, data):
"""
Add a new order to a store.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"customer": object*
{
"'id": string*
},
"curency_code": string*,
"order_total": number*,
"lines": array*
[
{
"id": string*,
"product_id": string*,
"product_variant_id": string*,
"quantity": integer*,
"price": number*
}
]
}
"""
self.store_id = store_id
if 'id' not in data:
raise KeyError('The order must have an id')
if 'customer' not in data:
raise KeyError('The order must have a customer')
if 'id' not in data['customer']:
raise KeyError('The order customer must have an id')
if 'currency_code' not in data:
raise KeyError('The order must have a currency_code')
if not re.match(r"^[A-Z]{3}$", data['currency_code']):
raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')
if 'order_total' not in data:
raise KeyError('The order must have an order_total')
if 'lines' not in data:
raise KeyError('The order must have at least one order line')
for line in data['lines']:
if 'id' not in line:
raise KeyError('Each order line must have an id')
if 'product_id' not in line:
raise KeyError('Each order line must have a product_id')
if 'product_variant_id' not in line:
raise KeyError('Each order line must have a product_variant_id')
if 'quantity' not in line:
raise KeyError('Each order line must have a quantity')
if 'price' not in line:
raise KeyError('Each order line must have a price')
response = self._mc_client._post(url=self._build_path(store_id, 'orders'), data=data)
if response is not None:
self.order_id = response['id']
else:
self.order_id = None
return response | [
"def",
"create",
"(",
"self",
",",
"store_id",
",",
"data",
")",
":",
"self",
".",
"store_id",
"=",
"store_id",
"if",
"'id'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The order must have an id'",
")",
"if",
"'customer'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The order must have a customer'",
")",
"if",
"'id'",
"not",
"in",
"data",
"[",
"'customer'",
"]",
":",
"raise",
"KeyError",
"(",
"'The order customer must have an id'",
")",
"if",
"'currency_code'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The order must have a currency_code'",
")",
"if",
"not",
"re",
".",
"match",
"(",
"r\"^[A-Z]{3}$\"",
",",
"data",
"[",
"'currency_code'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'The currency_code must be a valid 3-letter ISO 4217 currency code'",
")",
"if",
"'order_total'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The order must have an order_total'",
")",
"if",
"'lines'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The order must have at least one order line'",
")",
"for",
"line",
"in",
"data",
"[",
"'lines'",
"]",
":",
"if",
"'id'",
"not",
"in",
"line",
":",
"raise",
"KeyError",
"(",
"'Each order line must have an id'",
")",
"if",
"'product_id'",
"not",
"in",
"line",
":",
"raise",
"KeyError",
"(",
"'Each order line must have a product_id'",
")",
"if",
"'product_variant_id'",
"not",
"in",
"line",
":",
"raise",
"KeyError",
"(",
"'Each order line must have a product_variant_id'",
")",
"if",
"'quantity'",
"not",
"in",
"line",
":",
"raise",
"KeyError",
"(",
"'Each order line must have a quantity'",
")",
"if",
"'price'",
"not",
"in",
"line",
":",
"raise",
"KeyError",
"(",
"'Each order line must have a price'",
")",
"response",
"=",
"self",
".",
"_mc_client",
".",
"_post",
"(",
"url",
"=",
"self",
".",
"_build_path",
"(",
"store_id",
",",
"'orders'",
")",
",",
"data",
"=",
"data",
")",
"if",
"response",
"is",
"not",
"None",
":",
"self",
".",
"order_id",
"=",
"response",
"[",
"'id'",
"]",
"else",
":",
"self",
".",
"order_id",
"=",
"None",
"return",
"response"
] | Add a new order to a store.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"customer": object*
{
"'id": string*
},
"curency_code": string*,
"order_total": number*,
"lines": array*
[
{
"id": string*,
"product_id": string*,
"product_variant_id": string*,
"quantity": integer*,
"price": number*
}
]
} | [
"Add",
"a",
"new",
"order",
"to",
"a",
"store",
"."
] | python | valid |
pgmpy/pgmpy | pgmpy/readwrite/PomdpX.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/PomdpX.py#L86-L152 | def get_variables(self):
"""
Returns list of variables of the network
Example
-------
>>> reader = PomdpXReader("pomdpx.xml")
>>> reader.get_variables()
{'StateVar': [
{'vnamePrev': 'rover_0',
'vnameCurr': 'rover_1',
'ValueEnum': ['s0', 's1', 's2'],
'fullyObs': True},
{'vnamePrev': 'rock_0',
'vnameCurr': 'rock_1',
'fullyObs': False,
'ValueEnum': ['good', 'bad']}],
'ObsVar': [{'vname': 'obs_sensor',
'ValueEnum': ['ogood', 'obad']}],
'RewardVar': [{'vname': 'reward_rover'}],
'ActionVar': [{'vname': 'action_rover',
'ValueEnum': ['amw', 'ame',
'ac', 'as']}]
}
"""
self.variables = defaultdict(list)
for variable in self.network.findall('Variable'):
_variables = defaultdict(list)
for var in variable.findall('StateVar'):
state_variables = defaultdict(list)
state_variables['vnamePrev'] = var.get('vnamePrev')
state_variables['vnameCurr'] = var.get('vnameCurr')
if var.get('fullyObs'):
state_variables['fullyObs'] = True
else:
state_variables['fullyObs'] = False
state_variables['ValueEnum'] = []
if var.find('NumValues') is not None:
for i in range(0, int(var.find('NumValues').text)):
state_variables['ValueEnum'].append('s' + str(i))
if var.find('ValueEnum') is not None:
state_variables['ValueEnum'] = \
var.find('ValueEnum').text.split()
_variables['StateVar'].append(state_variables)
for var in variable.findall('ObsVar'):
obs_variables = defaultdict(list)
obs_variables['vname'] = var.get('vname')
obs_variables['ValueEnum'] = \
var.find('ValueEnum').text.split()
_variables['ObsVar'].append(obs_variables)
for var in variable.findall('ActionVar'):
action_variables = defaultdict(list)
action_variables['vname'] = var.get('vname')
action_variables['ValueEnum'] = \
var.find('ValueEnum').text.split()
_variables['ActionVar'].append(action_variables)
for var in variable.findall('RewardVar'):
reward_variables = defaultdict(list)
reward_variables['vname'] = var.get('vname')
_variables['RewardVar'].append(reward_variables)
self.variables.update(_variables)
return self.variables | [
"def",
"get_variables",
"(",
"self",
")",
":",
"self",
".",
"variables",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"variable",
"in",
"self",
".",
"network",
".",
"findall",
"(",
"'Variable'",
")",
":",
"_variables",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"var",
"in",
"variable",
".",
"findall",
"(",
"'StateVar'",
")",
":",
"state_variables",
"=",
"defaultdict",
"(",
"list",
")",
"state_variables",
"[",
"'vnamePrev'",
"]",
"=",
"var",
".",
"get",
"(",
"'vnamePrev'",
")",
"state_variables",
"[",
"'vnameCurr'",
"]",
"=",
"var",
".",
"get",
"(",
"'vnameCurr'",
")",
"if",
"var",
".",
"get",
"(",
"'fullyObs'",
")",
":",
"state_variables",
"[",
"'fullyObs'",
"]",
"=",
"True",
"else",
":",
"state_variables",
"[",
"'fullyObs'",
"]",
"=",
"False",
"state_variables",
"[",
"'ValueEnum'",
"]",
"=",
"[",
"]",
"if",
"var",
".",
"find",
"(",
"'NumValues'",
")",
"is",
"not",
"None",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"int",
"(",
"var",
".",
"find",
"(",
"'NumValues'",
")",
".",
"text",
")",
")",
":",
"state_variables",
"[",
"'ValueEnum'",
"]",
".",
"append",
"(",
"'s'",
"+",
"str",
"(",
"i",
")",
")",
"if",
"var",
".",
"find",
"(",
"'ValueEnum'",
")",
"is",
"not",
"None",
":",
"state_variables",
"[",
"'ValueEnum'",
"]",
"=",
"var",
".",
"find",
"(",
"'ValueEnum'",
")",
".",
"text",
".",
"split",
"(",
")",
"_variables",
"[",
"'StateVar'",
"]",
".",
"append",
"(",
"state_variables",
")",
"for",
"var",
"in",
"variable",
".",
"findall",
"(",
"'ObsVar'",
")",
":",
"obs_variables",
"=",
"defaultdict",
"(",
"list",
")",
"obs_variables",
"[",
"'vname'",
"]",
"=",
"var",
".",
"get",
"(",
"'vname'",
")",
"obs_variables",
"[",
"'ValueEnum'",
"]",
"=",
"var",
".",
"find",
"(",
"'ValueEnum'",
")",
".",
"text",
".",
"split",
"(",
")",
"_variables",
"[",
"'ObsVar'",
"]",
".",
"append",
"(",
"obs_variables",
")",
"for",
"var",
"in",
"variable",
".",
"findall",
"(",
"'ActionVar'",
")",
":",
"action_variables",
"=",
"defaultdict",
"(",
"list",
")",
"action_variables",
"[",
"'vname'",
"]",
"=",
"var",
".",
"get",
"(",
"'vname'",
")",
"action_variables",
"[",
"'ValueEnum'",
"]",
"=",
"var",
".",
"find",
"(",
"'ValueEnum'",
")",
".",
"text",
".",
"split",
"(",
")",
"_variables",
"[",
"'ActionVar'",
"]",
".",
"append",
"(",
"action_variables",
")",
"for",
"var",
"in",
"variable",
".",
"findall",
"(",
"'RewardVar'",
")",
":",
"reward_variables",
"=",
"defaultdict",
"(",
"list",
")",
"reward_variables",
"[",
"'vname'",
"]",
"=",
"var",
".",
"get",
"(",
"'vname'",
")",
"_variables",
"[",
"'RewardVar'",
"]",
".",
"append",
"(",
"reward_variables",
")",
"self",
".",
"variables",
".",
"update",
"(",
"_variables",
")",
"return",
"self",
".",
"variables"
] | Returns list of variables of the network
Example
-------
>>> reader = PomdpXReader("pomdpx.xml")
>>> reader.get_variables()
{'StateVar': [
{'vnamePrev': 'rover_0',
'vnameCurr': 'rover_1',
'ValueEnum': ['s0', 's1', 's2'],
'fullyObs': True},
{'vnamePrev': 'rock_0',
'vnameCurr': 'rock_1',
'fullyObs': False,
'ValueEnum': ['good', 'bad']}],
'ObsVar': [{'vname': 'obs_sensor',
'ValueEnum': ['ogood', 'obad']}],
'RewardVar': [{'vname': 'reward_rover'}],
'ActionVar': [{'vname': 'action_rover',
'ValueEnum': ['amw', 'ame',
'ac', 'as']}]
} | [
"Returns",
"list",
"of",
"variables",
"of",
"the",
"network"
] | python | train |
pantsbuild/pants | src/python/pants/engine/native.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/native.py#L211-L224 | def _extern_decl(return_type, arg_types):
"""A decorator for methods corresponding to extern functions. All types should be strings.
The _FFISpecification class is able to automatically convert these into method declarations for
cffi.
"""
def wrapper(func):
signature = _ExternSignature(
return_type=str(return_type),
method_name=str(func.__name__),
arg_types=tuple(arg_types))
func.extern_signature = signature
return func
return wrapper | [
"def",
"_extern_decl",
"(",
"return_type",
",",
"arg_types",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"signature",
"=",
"_ExternSignature",
"(",
"return_type",
"=",
"str",
"(",
"return_type",
")",
",",
"method_name",
"=",
"str",
"(",
"func",
".",
"__name__",
")",
",",
"arg_types",
"=",
"tuple",
"(",
"arg_types",
")",
")",
"func",
".",
"extern_signature",
"=",
"signature",
"return",
"func",
"return",
"wrapper"
] | A decorator for methods corresponding to extern functions. All types should be strings.
The _FFISpecification class is able to automatically convert these into method declarations for
cffi. | [
"A",
"decorator",
"for",
"methods",
"corresponding",
"to",
"extern",
"functions",
".",
"All",
"types",
"should",
"be",
"strings",
"."
] | python | train |
Chilipp/psyplot | psyplot/project.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L2345-L2392 | def close(num=None, figs=True, data=True, ds=True, remove_only=False):
"""
Close the project
This method closes the current project (figures, data and datasets) or the
project specified by `num`
Parameters
----------
num: int, None or 'all'
if :class:`int`, it specifies the number of the project, if None, the
current subproject is closed, if ``'all'``, all open projects are
closed
%(Project.close.parameters)s
See Also
--------
Project.close"""
kws = dict(figs=figs, data=data, ds=ds, remove_only=remove_only)
cp_num = gcp(True).num
got_cp = False
if num is None:
project = gcp()
scp(None)
project.close(**kws)
elif num == 'all':
for project in _open_projects[:]:
project.close(**kws)
got_cp = got_cp or project.main.num == cp_num
del _open_projects[0]
else:
if isinstance(num, Project):
project = num
else:
project = [project for project in _open_projects
if project.num == num][0]
project.close(**kws)
try:
_open_projects.remove(project)
except ValueError:
pass
got_cp = got_cp or project.main.num == cp_num
if got_cp:
if _open_projects:
# set last opened project to the current
scp(_open_projects[-1])
else:
_scp(None, True) | [
"def",
"close",
"(",
"num",
"=",
"None",
",",
"figs",
"=",
"True",
",",
"data",
"=",
"True",
",",
"ds",
"=",
"True",
",",
"remove_only",
"=",
"False",
")",
":",
"kws",
"=",
"dict",
"(",
"figs",
"=",
"figs",
",",
"data",
"=",
"data",
",",
"ds",
"=",
"ds",
",",
"remove_only",
"=",
"remove_only",
")",
"cp_num",
"=",
"gcp",
"(",
"True",
")",
".",
"num",
"got_cp",
"=",
"False",
"if",
"num",
"is",
"None",
":",
"project",
"=",
"gcp",
"(",
")",
"scp",
"(",
"None",
")",
"project",
".",
"close",
"(",
"*",
"*",
"kws",
")",
"elif",
"num",
"==",
"'all'",
":",
"for",
"project",
"in",
"_open_projects",
"[",
":",
"]",
":",
"project",
".",
"close",
"(",
"*",
"*",
"kws",
")",
"got_cp",
"=",
"got_cp",
"or",
"project",
".",
"main",
".",
"num",
"==",
"cp_num",
"del",
"_open_projects",
"[",
"0",
"]",
"else",
":",
"if",
"isinstance",
"(",
"num",
",",
"Project",
")",
":",
"project",
"=",
"num",
"else",
":",
"project",
"=",
"[",
"project",
"for",
"project",
"in",
"_open_projects",
"if",
"project",
".",
"num",
"==",
"num",
"]",
"[",
"0",
"]",
"project",
".",
"close",
"(",
"*",
"*",
"kws",
")",
"try",
":",
"_open_projects",
".",
"remove",
"(",
"project",
")",
"except",
"ValueError",
":",
"pass",
"got_cp",
"=",
"got_cp",
"or",
"project",
".",
"main",
".",
"num",
"==",
"cp_num",
"if",
"got_cp",
":",
"if",
"_open_projects",
":",
"# set last opened project to the current",
"scp",
"(",
"_open_projects",
"[",
"-",
"1",
"]",
")",
"else",
":",
"_scp",
"(",
"None",
",",
"True",
")"
] | Close the project
This method closes the current project (figures, data and datasets) or the
project specified by `num`
Parameters
----------
num: int, None or 'all'
if :class:`int`, it specifies the number of the project, if None, the
current subproject is closed, if ``'all'``, all open projects are
closed
%(Project.close.parameters)s
See Also
--------
Project.close | [
"Close",
"the",
"project"
] | python | train |
gijzelaerr/python-snap7 | example/example.py | https://github.com/gijzelaerr/python-snap7/blob/a6db134c7a3a2ef187b9eca04669221d6fc634c3/example/example.py#L37-L49 | def get_db_row(db, start, size):
"""
Here you see and example of readying out a part of a DB
Args:
db (int): The db to use
start (int): The index of where to start in db data
size (int): The size of the db data to read
"""
type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte]
data = client.db_read(db, start, type_, size)
# print_row(data[:60])
return data | [
"def",
"get_db_row",
"(",
"db",
",",
"start",
",",
"size",
")",
":",
"type_",
"=",
"snap7",
".",
"snap7types",
".",
"wordlen_to_ctypes",
"[",
"snap7",
".",
"snap7types",
".",
"S7WLByte",
"]",
"data",
"=",
"client",
".",
"db_read",
"(",
"db",
",",
"start",
",",
"type_",
",",
"size",
")",
"# print_row(data[:60])",
"return",
"data"
] | Here you see and example of readying out a part of a DB
Args:
db (int): The db to use
start (int): The index of where to start in db data
size (int): The size of the db data to read | [
"Here",
"you",
"see",
"and",
"example",
"of",
"readying",
"out",
"a",
"part",
"of",
"a",
"DB"
] | python | train |
datosgobar/pydatajson | pydatajson/core.py | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/core.py#L153-L189 | def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
datasets_index = {}
distributions_index = {}
fields_index = {}
# recorre todos los datasets
for dataset_index, dataset in enumerate(self.datasets):
if "identifier" in dataset:
datasets_index[dataset["identifier"]] = {
"dataset_index": dataset_index
}
# recorre las distribuciones del dataset
for distribution_index, distribution in enumerate(
dataset.get("distribution", [])):
if "identifier" in distribution:
distributions_index[distribution["identifier"]] = {
"distribution_index": distribution_index,
"dataset_identifier": dataset["identifier"]
}
# recorre los fields de la distribucion
for field_index, field in enumerate(
distribution.get("field", [])):
if "id" in field:
fields_index[field["id"]] = {
"field_index":
field_index,
"dataset_identifier":
dataset["identifier"],
"distribution_identifier":
distribution["identifier"]
}
setattr(self, "_distributions_index", distributions_index)
setattr(self, "_datasets_index", datasets_index)
setattr(self, "_fields_index", fields_index) | [
"def",
"_build_index",
"(",
"self",
")",
":",
"datasets_index",
"=",
"{",
"}",
"distributions_index",
"=",
"{",
"}",
"fields_index",
"=",
"{",
"}",
"# recorre todos los datasets",
"for",
"dataset_index",
",",
"dataset",
"in",
"enumerate",
"(",
"self",
".",
"datasets",
")",
":",
"if",
"\"identifier\"",
"in",
"dataset",
":",
"datasets_index",
"[",
"dataset",
"[",
"\"identifier\"",
"]",
"]",
"=",
"{",
"\"dataset_index\"",
":",
"dataset_index",
"}",
"# recorre las distribuciones del dataset",
"for",
"distribution_index",
",",
"distribution",
"in",
"enumerate",
"(",
"dataset",
".",
"get",
"(",
"\"distribution\"",
",",
"[",
"]",
")",
")",
":",
"if",
"\"identifier\"",
"in",
"distribution",
":",
"distributions_index",
"[",
"distribution",
"[",
"\"identifier\"",
"]",
"]",
"=",
"{",
"\"distribution_index\"",
":",
"distribution_index",
",",
"\"dataset_identifier\"",
":",
"dataset",
"[",
"\"identifier\"",
"]",
"}",
"# recorre los fields de la distribucion",
"for",
"field_index",
",",
"field",
"in",
"enumerate",
"(",
"distribution",
".",
"get",
"(",
"\"field\"",
",",
"[",
"]",
")",
")",
":",
"if",
"\"id\"",
"in",
"field",
":",
"fields_index",
"[",
"field",
"[",
"\"id\"",
"]",
"]",
"=",
"{",
"\"field_index\"",
":",
"field_index",
",",
"\"dataset_identifier\"",
":",
"dataset",
"[",
"\"identifier\"",
"]",
",",
"\"distribution_identifier\"",
":",
"distribution",
"[",
"\"identifier\"",
"]",
"}",
"setattr",
"(",
"self",
",",
"\"_distributions_index\"",
",",
"distributions_index",
")",
"setattr",
"(",
"self",
",",
"\"_datasets_index\"",
",",
"datasets_index",
")",
"setattr",
"(",
"self",
",",
"\"_fields_index\"",
",",
"fields_index",
")"
] | Itera todos los datasets, distribucioens y fields indexandolos. | [
"Itera",
"todos",
"los",
"datasets",
"distribucioens",
"y",
"fields",
"indexandolos",
"."
] | python | train |
tobgu/pyrsistent | pyrsistent/_plist.py | https://github.com/tobgu/pyrsistent/blob/c84dab0daaa44973cbe83830d14888827b307632/pyrsistent/_plist.py#L288-L303 | def plist(iterable=(), reverse=False):
"""
Creates a new persistent list containing all elements of iterable.
Optional parameter reverse specifies if the elements should be inserted in
reverse order or not.
>>> plist([1, 2, 3])
plist([1, 2, 3])
>>> plist([1, 2, 3], reverse=True)
plist([3, 2, 1])
"""
if not reverse:
iterable = list(iterable)
iterable.reverse()
return reduce(lambda pl, elem: pl.cons(elem), iterable, _EMPTY_PLIST) | [
"def",
"plist",
"(",
"iterable",
"=",
"(",
")",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"not",
"reverse",
":",
"iterable",
"=",
"list",
"(",
"iterable",
")",
"iterable",
".",
"reverse",
"(",
")",
"return",
"reduce",
"(",
"lambda",
"pl",
",",
"elem",
":",
"pl",
".",
"cons",
"(",
"elem",
")",
",",
"iterable",
",",
"_EMPTY_PLIST",
")"
] | Creates a new persistent list containing all elements of iterable.
Optional parameter reverse specifies if the elements should be inserted in
reverse order or not.
>>> plist([1, 2, 3])
plist([1, 2, 3])
>>> plist([1, 2, 3], reverse=True)
plist([3, 2, 1]) | [
"Creates",
"a",
"new",
"persistent",
"list",
"containing",
"all",
"elements",
"of",
"iterable",
".",
"Optional",
"parameter",
"reverse",
"specifies",
"if",
"the",
"elements",
"should",
"be",
"inserted",
"in",
"reverse",
"order",
"or",
"not",
"."
] | python | train |
harvard-nrg/yaxil | yaxil/functools/__init__.py | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/functools/__init__.py#L4-L25 | def lru_cache(fn):
'''
Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function
'''
@wraps(fn)
def memoized_fn(*args):
pargs = pickle.dumps(args)
if pargs not in memoized_fn.cache:
memoized_fn.cache[pargs] = fn(*args)
return memoized_fn.cache[pargs]
# propagate function attributes in the event that
# this is applied as a function and not a decorator
for attr, value in iter(fn.__dict__.items()):
setattr(memoized_fn, attr, value)
memoized_fn.cache = {}
return memoized_fn | [
"def",
"lru_cache",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"memoized_fn",
"(",
"*",
"args",
")",
":",
"pargs",
"=",
"pickle",
".",
"dumps",
"(",
"args",
")",
"if",
"pargs",
"not",
"in",
"memoized_fn",
".",
"cache",
":",
"memoized_fn",
".",
"cache",
"[",
"pargs",
"]",
"=",
"fn",
"(",
"*",
"args",
")",
"return",
"memoized_fn",
".",
"cache",
"[",
"pargs",
"]",
"# propagate function attributes in the event that",
"# this is applied as a function and not a decorator",
"for",
"attr",
",",
"value",
"in",
"iter",
"(",
"fn",
".",
"__dict__",
".",
"items",
"(",
")",
")",
":",
"setattr",
"(",
"memoized_fn",
",",
"attr",
",",
"value",
")",
"memoized_fn",
".",
"cache",
"=",
"{",
"}",
"return",
"memoized_fn"
] | Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function | [
"Memoization",
"wrapper",
"that",
"can",
"handle",
"function",
"attributes",
"mutable",
"arguments",
"and",
"can",
"be",
"applied",
"either",
"as",
"a",
"decorator",
"or",
"at",
"runtime",
"."
] | python | train |
ronaldguillen/wave | wave/authentication.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/authentication.py#L132-L139 | def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) | [
"def",
"enforce_csrf",
"(",
"self",
",",
"request",
")",
":",
"reason",
"=",
"CSRFCheck",
"(",
")",
".",
"process_view",
"(",
"request",
",",
"None",
",",
"(",
")",
",",
"{",
"}",
")",
"if",
"reason",
":",
"# CSRF failed, bail with explicit error message",
"raise",
"exceptions",
".",
"PermissionDenied",
"(",
"'CSRF Failed: %s'",
"%",
"reason",
")"
] | Enforce CSRF validation for session based authentication. | [
"Enforce",
"CSRF",
"validation",
"for",
"session",
"based",
"authentication",
"."
] | python | train |
Robin8Put/pmes | pdms/views.py | https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/pdms/views.py#L1359-L1399 | async def post(self, public_key):
"""Writes contents review
"""
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(400)
self.write({"error":400, "reason":"Unexpected data format. JSON required"})
raise tornado.web.Finish
if isinstance(body["message"], str):
message = json.loads(body["message"])
elif isinstance(body["message"], dict):
message = body["message"]
cid = message.get("cid")
review = message.get("review")
rating = message.get("rating")
coinid = message.get("coinid")
if not all([cid, rating, review]):
self.set_status(400)
self.write({"error":400, "reason":"Missed required fields"})
if coinid in settings.bridges.keys():
self.account.blockchain.setendpoint(settings.bridges[coinid])
else:
self.set_status(400)
self.write({"error":400, "reason":"Invalid coinid"})
raise tornado.web.Finish
buyer_address = self.account.validator[coinid](public_key)
review = await self.account.blockchain.addreview(cid=int(cid),buyer_address=buyer_address,
stars=int(rating), review=review)
await self.account.setreview(cid=cid, txid=review["result"]["txid"], coinid=coinid)
self.write({"cid":cid, "review":review, "rating":rating}) | [
"async",
"def",
"post",
"(",
"self",
",",
"public_key",
")",
":",
"if",
"settings",
".",
"SIGNATURE_VERIFICATION",
":",
"super",
"(",
")",
".",
"verify",
"(",
")",
"try",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
")",
"except",
":",
"self",
".",
"set_status",
"(",
"400",
")",
"self",
".",
"write",
"(",
"{",
"\"error\"",
":",
"400",
",",
"\"reason\"",
":",
"\"Unexpected data format. JSON required\"",
"}",
")",
"raise",
"tornado",
".",
"web",
".",
"Finish",
"if",
"isinstance",
"(",
"body",
"[",
"\"message\"",
"]",
",",
"str",
")",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"body",
"[",
"\"message\"",
"]",
")",
"elif",
"isinstance",
"(",
"body",
"[",
"\"message\"",
"]",
",",
"dict",
")",
":",
"message",
"=",
"body",
"[",
"\"message\"",
"]",
"cid",
"=",
"message",
".",
"get",
"(",
"\"cid\"",
")",
"review",
"=",
"message",
".",
"get",
"(",
"\"review\"",
")",
"rating",
"=",
"message",
".",
"get",
"(",
"\"rating\"",
")",
"coinid",
"=",
"message",
".",
"get",
"(",
"\"coinid\"",
")",
"if",
"not",
"all",
"(",
"[",
"cid",
",",
"rating",
",",
"review",
"]",
")",
":",
"self",
".",
"set_status",
"(",
"400",
")",
"self",
".",
"write",
"(",
"{",
"\"error\"",
":",
"400",
",",
"\"reason\"",
":",
"\"Missed required fields\"",
"}",
")",
"if",
"coinid",
"in",
"settings",
".",
"bridges",
".",
"keys",
"(",
")",
":",
"self",
".",
"account",
".",
"blockchain",
".",
"setendpoint",
"(",
"settings",
".",
"bridges",
"[",
"coinid",
"]",
")",
"else",
":",
"self",
".",
"set_status",
"(",
"400",
")",
"self",
".",
"write",
"(",
"{",
"\"error\"",
":",
"400",
",",
"\"reason\"",
":",
"\"Invalid coinid\"",
"}",
")",
"raise",
"tornado",
".",
"web",
".",
"Finish",
"buyer_address",
"=",
"self",
".",
"account",
".",
"validator",
"[",
"coinid",
"]",
"(",
"public_key",
")",
"review",
"=",
"await",
"self",
".",
"account",
".",
"blockchain",
".",
"addreview",
"(",
"cid",
"=",
"int",
"(",
"cid",
")",
",",
"buyer_address",
"=",
"buyer_address",
",",
"stars",
"=",
"int",
"(",
"rating",
")",
",",
"review",
"=",
"review",
")",
"await",
"self",
".",
"account",
".",
"setreview",
"(",
"cid",
"=",
"cid",
",",
"txid",
"=",
"review",
"[",
"\"result\"",
"]",
"[",
"\"txid\"",
"]",
",",
"coinid",
"=",
"coinid",
")",
"self",
".",
"write",
"(",
"{",
"\"cid\"",
":",
"cid",
",",
"\"review\"",
":",
"review",
",",
"\"rating\"",
":",
"rating",
"}",
")"
] | Writes contents review | [
"Writes",
"contents",
"review"
] | python | train |
wq/html-json-forms | html_json_forms/utils.py | https://github.com/wq/html-json-forms/blob/4dfbfabeee924ba832a7a387ab3b02b6d51d9701/html_json_forms/utils.py#L304-L315 | def get_all_items(obj):
"""
dict.items() but with a separate row for each value in a MultiValueDict
"""
if hasattr(obj, 'getlist'):
items = []
for key in obj:
for value in obj.getlist(key):
items.append((key, value))
return items
else:
return obj.items() | [
"def",
"get_all_items",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'getlist'",
")",
":",
"items",
"=",
"[",
"]",
"for",
"key",
"in",
"obj",
":",
"for",
"value",
"in",
"obj",
".",
"getlist",
"(",
"key",
")",
":",
"items",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"return",
"items",
"else",
":",
"return",
"obj",
".",
"items",
"(",
")"
] | dict.items() but with a separate row for each value in a MultiValueDict | [
"dict",
".",
"items",
"()",
"but",
"with",
"a",
"separate",
"row",
"for",
"each",
"value",
"in",
"a",
"MultiValueDict"
] | python | valid |
mrooney/mintapi | mintapi/api.py | https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L380-L392 | def close(self):
"""Logs out and quits the current web driver/selenium session."""
if not self.driver:
return
try:
self.driver.implicitly_wait(1)
self.driver.find_element_by_id('link-logout').click()
except NoSuchElementException:
pass
self.driver.quit()
self.driver = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"driver",
":",
"return",
"try",
":",
"self",
".",
"driver",
".",
"implicitly_wait",
"(",
"1",
")",
"self",
".",
"driver",
".",
"find_element_by_id",
"(",
"'link-logout'",
")",
".",
"click",
"(",
")",
"except",
"NoSuchElementException",
":",
"pass",
"self",
".",
"driver",
".",
"quit",
"(",
")",
"self",
".",
"driver",
"=",
"None"
] | Logs out and quits the current web driver/selenium session. | [
"Logs",
"out",
"and",
"quits",
"the",
"current",
"web",
"driver",
"/",
"selenium",
"session",
"."
] | python | train |
sprockets/sprockets.mixins.statsd | sprockets/mixins/statsd/__init__.py | https://github.com/sprockets/sprockets.mixins.statsd/blob/98dcce37d275a3ab96ef618b4756d7c4618a550a/sprockets/mixins/statsd/__init__.py#L89-L130 | def on_finish(self):
"""Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value to a timer in the following format:
.. code::
<PREFIX>.timers.<host>.package[.module].Class.METHOD.STATUS
sprockets.timers.localhost.tornado.web.RequestHandler.GET.200
"""
if self.statsd_prefix != statsd.STATSD_PREFIX:
statsd.set_prefix(self.statsd_prefix)
if hasattr(self, 'request') and self.request:
if self.statsd_use_hostname:
timer_prefix = 'timers.{0}'.format(socket.gethostname())
counter_prefix = 'counters.{0}'.format(socket.gethostname())
else:
timer_prefix = 'timers'
counter_prefix = 'counters'
statsd.add_timing(timer_prefix,
self.__module__,
str(self.__class__.__name__),
self.request.method,
str(self._status_code),
value=self.request.request_time() * 1000)
statsd.incr(counter_prefix,
self.__module__,
self.__class__.__name__,
self.request.method,
str(self._status_code))
super(RequestMetricsMixin, self).on_finish() | [
"def",
"on_finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"statsd_prefix",
"!=",
"statsd",
".",
"STATSD_PREFIX",
":",
"statsd",
".",
"set_prefix",
"(",
"self",
".",
"statsd_prefix",
")",
"if",
"hasattr",
"(",
"self",
",",
"'request'",
")",
"and",
"self",
".",
"request",
":",
"if",
"self",
".",
"statsd_use_hostname",
":",
"timer_prefix",
"=",
"'timers.{0}'",
".",
"format",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"counter_prefix",
"=",
"'counters.{0}'",
".",
"format",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"else",
":",
"timer_prefix",
"=",
"'timers'",
"counter_prefix",
"=",
"'counters'",
"statsd",
".",
"add_timing",
"(",
"timer_prefix",
",",
"self",
".",
"__module__",
",",
"str",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
",",
"self",
".",
"request",
".",
"method",
",",
"str",
"(",
"self",
".",
"_status_code",
")",
",",
"value",
"=",
"self",
".",
"request",
".",
"request_time",
"(",
")",
"*",
"1000",
")",
"statsd",
".",
"incr",
"(",
"counter_prefix",
",",
"self",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"request",
".",
"method",
",",
"str",
"(",
"self",
".",
"_status_code",
")",
")",
"super",
"(",
"RequestMetricsMixin",
",",
"self",
")",
".",
"on_finish",
"(",
")"
] | Invoked once the request has been finished. Increments a counter
created in the format:
.. code::
<PREFIX>.counters.<host>.package[.module].Class.METHOD.STATUS
sprockets.counters.localhost.tornado.web.RequestHandler.GET.200
Adds a value to a timer in the following format:
.. code::
<PREFIX>.timers.<host>.package[.module].Class.METHOD.STATUS
sprockets.timers.localhost.tornado.web.RequestHandler.GET.200 | [
"Invoked",
"once",
"the",
"request",
"has",
"been",
"finished",
".",
"Increments",
"a",
"counter",
"created",
"in",
"the",
"format",
":"
] | python | train |
saltstack/salt | salt/modules/debuild_pkgbuild.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L594-L945 | def make_repo(repodir,
keyid=None,
env=None,
use_passphrase=False,
gnupghome='/etc/salt/gpgkeys',
runas='root',
timeout=15.0):
'''
Make a package repository and optionally sign it and packages present
Given the repodir (directory to create repository in), create a Debian
repository and optionally sign it and packages present. This state is
best used with onchanges linked to your package building states.
repodir
The directory to find packages that will be in the repository.
keyid
.. versionchanged:: 2016.3.0
Optional Key ID to use in signing packages and repository.
This consists of the last 8 hex digits of the GPG key ID.
Utilizes Public and Private keys associated with keyid which have
been loaded into the minion's Pillar data. Leverages gpg-agent and
gpg-preset-passphrase for caching keys, etc.
These pillar values are assumed to be filenames which are present
in ``gnupghome``. The pillar keys shown below have to match exactly.
For example, contents from a Pillar data file with named Public
and Private keys as follows:
.. code-block:: yaml
gpg_pkg_priv_keyname: gpg_pkg_key.pem
gpg_pkg_pub_keyname: gpg_pkg_key.pub
env
.. versionchanged:: 2016.3.0
A dictionary of environment variables to be utilized in creating the
repository.
use_passphrase : False
.. versionadded:: 2016.3.0
Use a passphrase with the signing key presented in ``keyid``.
Passphrase is received from Pillar data which could be passed on the
command line with ``pillar`` parameter. For example:
.. code-block:: bash
pillar='{ "gpg_passphrase" : "my_passphrase" }'
gnupghome : /etc/salt/gpgkeys
.. versionadded:: 2016.3.0
Location where GPG related files are stored, used with ``keyid``.
runas : root
.. versionadded:: 2016.3.0
User to create the repository as, and optionally sign packages.
.. note::
Ensure the user has correct permissions to any files and
directories which are to be utilized.
timeout : 15.0
.. versionadded:: 2016.3.4
Timeout in seconds to wait for the prompt for inputting the passphrase.
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_repo /var/www/html
'''
res = {
'retcode': 1,
'stdout': '',
'stderr': 'initialization value'
}
retrc = 0
if gnupghome and env is None:
env = {}
env['GNUPGHOME'] = gnupghome
repoconf = os.path.join(repodir, 'conf')
if not os.path.isdir(repoconf):
os.makedirs(repoconf)
codename, repocfg_dists = _get_repo_dists_env(env)
repoconfdist = os.path.join(repoconf, 'distributions')
with salt.utils.files.fopen(repoconfdist, 'w') as fow:
fow.write(salt.utils.stringutils.to_str(repocfg_dists))
repocfg_opts = _get_repo_options_env(env)
repoconfopts = os.path.join(repoconf, 'options')
with salt.utils.files.fopen(repoconfopts, 'w') as fow:
fow.write(salt.utils.stringutils.to_str(repocfg_opts))
cmd = 'chown {0}:{0} -R {1}'.format(runas, repoconf)
retrc = __salt__['cmd.retcode'](cmd, runas='root')
if retrc != 0:
raise SaltInvocationError(
'failed to ensure rights to repoconf directory, error {0}, '
'check logs for further details'.format(retrc)
)
local_keygrip_to_use = None
local_key_fingerprint = None
local_keyid = None
phrase = ''
# preset passphase and interaction with gpg-agent
gpg_info_file = '{0}/gpg-agent-info-salt'.format(gnupghome)
gpg_tty_info_file = '{0}/gpg-tty-info-salt'.format(gnupghome)
# if using older than gnupg 2.1, then env file exists
older_gnupg = __salt__['file.file_exists'](gpg_info_file)
if keyid is not None:
with salt.utils.files.fopen(repoconfdist, 'a') as fow:
fow.write(salt.utils.stringutils.to_str('SignWith: {0}\n'.format(keyid)))
# import_keys
pkg_pub_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_pub_keyname', None))
pkg_priv_key_file = '{0}/{1}'.format(gnupghome, __salt__['pillar.get']('gpg_pkg_priv_keyname', None))
if pkg_pub_key_file is None or pkg_priv_key_file is None:
raise SaltInvocationError(
'Pillar data should contain Public and Private keys associated with \'keyid\''
)
try:
__salt__['gpg.import_key'](user=runas, filename=pkg_pub_key_file, gnupghome=gnupghome)
__salt__['gpg.import_key'](user=runas, filename=pkg_priv_key_file, gnupghome=gnupghome)
except SaltInvocationError:
raise SaltInvocationError(
'Public and Private key files associated with Pillar data and \'keyid\' '
'{0} could not be found'
.format(keyid)
)
# gpg keys should have been loaded as part of setup
# retrieve specified key, obtain fingerprint and preset passphrase
local_keys = __salt__['gpg.list_keys'](user=runas, gnupghome=gnupghome)
for gpg_key in local_keys:
if keyid == gpg_key['keyid'][8:]:
local_keygrip_to_use = gpg_key['fingerprint']
local_key_fingerprint = gpg_key['fingerprint']
local_keyid = gpg_key['keyid']
break
if not older_gnupg:
try:
_check_repo_sign_utils_support('gpg2')
cmd = 'gpg2 --with-keygrip --list-secret-keys'
except CommandExecutionError:
# later gpg versions have dispensed with gpg2 - Ubuntu 18.04
cmd = 'gpg --with-keygrip --list-secret-keys'
local_keys2_keygrip = __salt__['cmd.run'](cmd, runas=runas, env=env)
local_keys2 = iter(local_keys2_keygrip.splitlines())
try:
for line in local_keys2:
if line.startswith('sec'):
line_fingerprint = next(local_keys2).lstrip().rstrip()
if local_key_fingerprint == line_fingerprint:
lkeygrip = next(local_keys2).split('=')
local_keygrip_to_use = lkeygrip[1].lstrip().rstrip()
break
except StopIteration:
raise SaltInvocationError(
'unable to find keygrip associated with fingerprint \'{0}\' for keyid \'{1}\''
.format(local_key_fingerprint, local_keyid)
)
if local_keyid is None:
raise SaltInvocationError(
'The key ID \'{0}\' was not found in GnuPG keyring at \'{1}\''
.format(keyid, gnupghome)
)
_check_repo_sign_utils_support('debsign')
if older_gnupg:
with salt.utils.files.fopen(gpg_info_file, 'r') as fow:
gpg_raw_info = fow.readlines()
for gpg_info_line in gpg_raw_info:
gpg_info_line = salt.utils.stringutils.to_unicode(gpg_info_line)
gpg_info = gpg_info_line.split('=')
env[gpg_info[0]] = gpg_info[1]
break
else:
with salt.utils.files.fopen(gpg_tty_info_file, 'r') as fow:
gpg_raw_info = fow.readlines()
for gpg_tty_info_line in gpg_raw_info:
gpg_tty_info_line = salt.utils.stringutils.to_unicode(gpg_tty_info_line)
gpg_tty_info = gpg_tty_info_line.split('=')
env[gpg_tty_info[0]] = gpg_tty_info[1]
break
if use_passphrase:
_check_repo_gpg_phrase_utils()
phrase = __salt__['pillar.get']('gpg_passphrase')
cmd = '/usr/lib/gnupg2/gpg-preset-passphrase --verbose --preset --passphrase "{0}" {1}'.format(
phrase,
local_keygrip_to_use)
retrc |= __salt__['cmd.retcode'](cmd, runas=runas, env=env)
for debfile in os.listdir(repodir):
abs_file = os.path.join(repodir, debfile)
if debfile.endswith('.changes'):
os.remove(abs_file)
if debfile.endswith('.dsc'):
# sign_it_here
if older_gnupg:
if local_keyid is not None:
cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file)
retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env)
cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format(
codename,
abs_file)
retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env)
else:
# interval of 0.125 is really too fast on some systems
interval = 0.5
if local_keyid is not None:
number_retries = timeout / interval
times_looped = 0
error_msg = 'Failed to debsign file {0}'.format(abs_file)
if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18)
or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)):
cmd = 'debsign --re-sign -k {0} {1}'.format(keyid, abs_file)
try:
proc = salt.utils.vt.Terminal(
cmd,
env=env,
shell=True,
stream_stdout=True,
stream_stderr=True
)
while proc.has_unread_data:
stdout, _ = proc.recv()
if stdout and SIGN_PROMPT_RE.search(stdout):
# have the prompt for inputting the passphrase
proc.sendline(phrase)
else:
times_looped += 1
if times_looped > number_retries:
raise SaltInvocationError(
'Attempting to sign file {0} failed, timed out after {1} seconds'.format(
abs_file,
int(times_looped * interval))
)
time.sleep(interval)
proc_exitstatus = proc.exitstatus
if proc_exitstatus != 0:
raise SaltInvocationError(
'Signing file {0} failed with proc.status {1}'.format(
abs_file,
proc_exitstatus)
)
except salt.utils.vt.TerminalException as err:
trace = traceback.format_exc()
log.error(error_msg, err, trace)
res = {
'retcode': 1,
'stdout': '',
'stderr': trace}
finally:
proc.close(terminate=True, kill=True)
else:
cmd = 'debsign --re-sign -k {0} {1}'.format(local_key_fingerprint, abs_file)
retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env)
number_retries = timeout / interval
times_looped = 0
error_msg = 'Failed to reprepro includedsc file {0}'.format(abs_file)
cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'.format(
codename,
abs_file)
if ((__grains__['os'] in ['Ubuntu'] and __grains__['osmajorrelease'] < 18)
or (__grains__['os'] in ['Debian'] and __grains__['osmajorrelease'] <= 8)):
try:
proc = salt.utils.vt.Terminal(
cmd,
env=env,
shell=True,
cwd=repodir,
stream_stdout=True,
stream_stderr=True
)
while proc.has_unread_data:
stdout, _ = proc.recv()
if stdout and REPREPRO_SIGN_PROMPT_RE.search(stdout):
# have the prompt for inputting the passphrase
proc.sendline(phrase)
else:
times_looped += 1
if times_looped > number_retries:
raise SaltInvocationError(
'Attempting to reprepro includedsc for file {0} failed, timed out after {1} loops'
.format(abs_file, times_looped)
)
time.sleep(interval)
proc_exitstatus = proc.exitstatus
if proc_exitstatus != 0:
raise SaltInvocationError(
'Reprepro includedsc for codename {0} and file {1} failed with proc.status {2}'.format(
codename,
abs_file,
proc_exitstatus)
)
except salt.utils.vt.TerminalException as err:
trace = traceback.format_exc()
log.error(error_msg, err, trace)
res = {
'retcode': 1,
'stdout': '',
'stderr': trace
}
finally:
proc.close(terminate=True, kill=True)
else:
retrc |= __salt__['cmd.retcode'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env)
if retrc != 0:
raise SaltInvocationError(
'Making a repo encountered errors, return error {0}, check logs for further details'.format(retrc))
if debfile.endswith('.deb'):
cmd = 'reprepro --ignore=wrongdistribution --component=main -Vb . includedeb {0} {1}'.format(
codename,
abs_file)
res = __salt__['cmd.run_all'](cmd, runas=runas, cwd=repodir, use_vt=True, env=env)
return res | [
"def",
"make_repo",
"(",
"repodir",
",",
"keyid",
"=",
"None",
",",
"env",
"=",
"None",
",",
"use_passphrase",
"=",
"False",
",",
"gnupghome",
"=",
"'/etc/salt/gpgkeys'",
",",
"runas",
"=",
"'root'",
",",
"timeout",
"=",
"15.0",
")",
":",
"res",
"=",
"{",
"'retcode'",
":",
"1",
",",
"'stdout'",
":",
"''",
",",
"'stderr'",
":",
"'initialization value'",
"}",
"retrc",
"=",
"0",
"if",
"gnupghome",
"and",
"env",
"is",
"None",
":",
"env",
"=",
"{",
"}",
"env",
"[",
"'GNUPGHOME'",
"]",
"=",
"gnupghome",
"repoconf",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repodir",
",",
"'conf'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"repoconf",
")",
":",
"os",
".",
"makedirs",
"(",
"repoconf",
")",
"codename",
",",
"repocfg_dists",
"=",
"_get_repo_dists_env",
"(",
"env",
")",
"repoconfdist",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repoconf",
",",
"'distributions'",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"repoconfdist",
",",
"'w'",
")",
"as",
"fow",
":",
"fow",
".",
"write",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"repocfg_dists",
")",
")",
"repocfg_opts",
"=",
"_get_repo_options_env",
"(",
"env",
")",
"repoconfopts",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repoconf",
",",
"'options'",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"repoconfopts",
",",
"'w'",
")",
"as",
"fow",
":",
"fow",
".",
"write",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"repocfg_opts",
")",
")",
"cmd",
"=",
"'chown {0}:{0} -R {1}'",
".",
"format",
"(",
"runas",
",",
"repoconf",
")",
"retrc",
"=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"'root'",
")",
"if",
"retrc",
"!=",
"0",
":",
"raise",
"SaltInvocationError",
"(",
"'failed to ensure rights to repoconf directory, error {0}, '",
"'check logs for further details'",
".",
"format",
"(",
"retrc",
")",
")",
"local_keygrip_to_use",
"=",
"None",
"local_key_fingerprint",
"=",
"None",
"local_keyid",
"=",
"None",
"phrase",
"=",
"''",
"# preset passphase and interaction with gpg-agent",
"gpg_info_file",
"=",
"'{0}/gpg-agent-info-salt'",
".",
"format",
"(",
"gnupghome",
")",
"gpg_tty_info_file",
"=",
"'{0}/gpg-tty-info-salt'",
".",
"format",
"(",
"gnupghome",
")",
"# if using older than gnupg 2.1, then env file exists",
"older_gnupg",
"=",
"__salt__",
"[",
"'file.file_exists'",
"]",
"(",
"gpg_info_file",
")",
"if",
"keyid",
"is",
"not",
"None",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"repoconfdist",
",",
"'a'",
")",
"as",
"fow",
":",
"fow",
".",
"write",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"'SignWith: {0}\\n'",
".",
"format",
"(",
"keyid",
")",
")",
")",
"# import_keys",
"pkg_pub_key_file",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"gnupghome",
",",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"'gpg_pkg_pub_keyname'",
",",
"None",
")",
")",
"pkg_priv_key_file",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"gnupghome",
",",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"'gpg_pkg_priv_keyname'",
",",
"None",
")",
")",
"if",
"pkg_pub_key_file",
"is",
"None",
"or",
"pkg_priv_key_file",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'Pillar data should contain Public and Private keys associated with \\'keyid\\''",
")",
"try",
":",
"__salt__",
"[",
"'gpg.import_key'",
"]",
"(",
"user",
"=",
"runas",
",",
"filename",
"=",
"pkg_pub_key_file",
",",
"gnupghome",
"=",
"gnupghome",
")",
"__salt__",
"[",
"'gpg.import_key'",
"]",
"(",
"user",
"=",
"runas",
",",
"filename",
"=",
"pkg_priv_key_file",
",",
"gnupghome",
"=",
"gnupghome",
")",
"except",
"SaltInvocationError",
":",
"raise",
"SaltInvocationError",
"(",
"'Public and Private key files associated with Pillar data and \\'keyid\\' '",
"'{0} could not be found'",
".",
"format",
"(",
"keyid",
")",
")",
"# gpg keys should have been loaded as part of setup",
"# retrieve specified key, obtain fingerprint and preset passphrase",
"local_keys",
"=",
"__salt__",
"[",
"'gpg.list_keys'",
"]",
"(",
"user",
"=",
"runas",
",",
"gnupghome",
"=",
"gnupghome",
")",
"for",
"gpg_key",
"in",
"local_keys",
":",
"if",
"keyid",
"==",
"gpg_key",
"[",
"'keyid'",
"]",
"[",
"8",
":",
"]",
":",
"local_keygrip_to_use",
"=",
"gpg_key",
"[",
"'fingerprint'",
"]",
"local_key_fingerprint",
"=",
"gpg_key",
"[",
"'fingerprint'",
"]",
"local_keyid",
"=",
"gpg_key",
"[",
"'keyid'",
"]",
"break",
"if",
"not",
"older_gnupg",
":",
"try",
":",
"_check_repo_sign_utils_support",
"(",
"'gpg2'",
")",
"cmd",
"=",
"'gpg2 --with-keygrip --list-secret-keys'",
"except",
"CommandExecutionError",
":",
"# later gpg versions have dispensed with gpg2 - Ubuntu 18.04",
"cmd",
"=",
"'gpg --with-keygrip --list-secret-keys'",
"local_keys2_keygrip",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"env",
"=",
"env",
")",
"local_keys2",
"=",
"iter",
"(",
"local_keys2_keygrip",
".",
"splitlines",
"(",
")",
")",
"try",
":",
"for",
"line",
"in",
"local_keys2",
":",
"if",
"line",
".",
"startswith",
"(",
"'sec'",
")",
":",
"line_fingerprint",
"=",
"next",
"(",
"local_keys2",
")",
".",
"lstrip",
"(",
")",
".",
"rstrip",
"(",
")",
"if",
"local_key_fingerprint",
"==",
"line_fingerprint",
":",
"lkeygrip",
"=",
"next",
"(",
"local_keys2",
")",
".",
"split",
"(",
"'='",
")",
"local_keygrip_to_use",
"=",
"lkeygrip",
"[",
"1",
"]",
".",
"lstrip",
"(",
")",
".",
"rstrip",
"(",
")",
"break",
"except",
"StopIteration",
":",
"raise",
"SaltInvocationError",
"(",
"'unable to find keygrip associated with fingerprint \\'{0}\\' for keyid \\'{1}\\''",
".",
"format",
"(",
"local_key_fingerprint",
",",
"local_keyid",
")",
")",
"if",
"local_keyid",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'The key ID \\'{0}\\' was not found in GnuPG keyring at \\'{1}\\''",
".",
"format",
"(",
"keyid",
",",
"gnupghome",
")",
")",
"_check_repo_sign_utils_support",
"(",
"'debsign'",
")",
"if",
"older_gnupg",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"gpg_info_file",
",",
"'r'",
")",
"as",
"fow",
":",
"gpg_raw_info",
"=",
"fow",
".",
"readlines",
"(",
")",
"for",
"gpg_info_line",
"in",
"gpg_raw_info",
":",
"gpg_info_line",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"gpg_info_line",
")",
"gpg_info",
"=",
"gpg_info_line",
".",
"split",
"(",
"'='",
")",
"env",
"[",
"gpg_info",
"[",
"0",
"]",
"]",
"=",
"gpg_info",
"[",
"1",
"]",
"break",
"else",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"gpg_tty_info_file",
",",
"'r'",
")",
"as",
"fow",
":",
"gpg_raw_info",
"=",
"fow",
".",
"readlines",
"(",
")",
"for",
"gpg_tty_info_line",
"in",
"gpg_raw_info",
":",
"gpg_tty_info_line",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"gpg_tty_info_line",
")",
"gpg_tty_info",
"=",
"gpg_tty_info_line",
".",
"split",
"(",
"'='",
")",
"env",
"[",
"gpg_tty_info",
"[",
"0",
"]",
"]",
"=",
"gpg_tty_info",
"[",
"1",
"]",
"break",
"if",
"use_passphrase",
":",
"_check_repo_gpg_phrase_utils",
"(",
")",
"phrase",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"'gpg_passphrase'",
")",
"cmd",
"=",
"'/usr/lib/gnupg2/gpg-preset-passphrase --verbose --preset --passphrase \"{0}\" {1}'",
".",
"format",
"(",
"phrase",
",",
"local_keygrip_to_use",
")",
"retrc",
"|=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"env",
"=",
"env",
")",
"for",
"debfile",
"in",
"os",
".",
"listdir",
"(",
"repodir",
")",
":",
"abs_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repodir",
",",
"debfile",
")",
"if",
"debfile",
".",
"endswith",
"(",
"'.changes'",
")",
":",
"os",
".",
"remove",
"(",
"abs_file",
")",
"if",
"debfile",
".",
"endswith",
"(",
"'.dsc'",
")",
":",
"# sign_it_here",
"if",
"older_gnupg",
":",
"if",
"local_keyid",
"is",
"not",
"None",
":",
"cmd",
"=",
"'debsign --re-sign -k {0} {1}'",
".",
"format",
"(",
"keyid",
",",
"abs_file",
")",
"retrc",
"|=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"cwd",
"=",
"repodir",
",",
"use_vt",
"=",
"True",
",",
"env",
"=",
"env",
")",
"cmd",
"=",
"'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'",
".",
"format",
"(",
"codename",
",",
"abs_file",
")",
"retrc",
"|=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"cwd",
"=",
"repodir",
",",
"use_vt",
"=",
"True",
",",
"env",
"=",
"env",
")",
"else",
":",
"# interval of 0.125 is really too fast on some systems",
"interval",
"=",
"0.5",
"if",
"local_keyid",
"is",
"not",
"None",
":",
"number_retries",
"=",
"timeout",
"/",
"interval",
"times_looped",
"=",
"0",
"error_msg",
"=",
"'Failed to debsign file {0}'",
".",
"format",
"(",
"abs_file",
")",
"if",
"(",
"(",
"__grains__",
"[",
"'os'",
"]",
"in",
"[",
"'Ubuntu'",
"]",
"and",
"__grains__",
"[",
"'osmajorrelease'",
"]",
"<",
"18",
")",
"or",
"(",
"__grains__",
"[",
"'os'",
"]",
"in",
"[",
"'Debian'",
"]",
"and",
"__grains__",
"[",
"'osmajorrelease'",
"]",
"<=",
"8",
")",
")",
":",
"cmd",
"=",
"'debsign --re-sign -k {0} {1}'",
".",
"format",
"(",
"keyid",
",",
"abs_file",
")",
"try",
":",
"proc",
"=",
"salt",
".",
"utils",
".",
"vt",
".",
"Terminal",
"(",
"cmd",
",",
"env",
"=",
"env",
",",
"shell",
"=",
"True",
",",
"stream_stdout",
"=",
"True",
",",
"stream_stderr",
"=",
"True",
")",
"while",
"proc",
".",
"has_unread_data",
":",
"stdout",
",",
"_",
"=",
"proc",
".",
"recv",
"(",
")",
"if",
"stdout",
"and",
"SIGN_PROMPT_RE",
".",
"search",
"(",
"stdout",
")",
":",
"# have the prompt for inputting the passphrase",
"proc",
".",
"sendline",
"(",
"phrase",
")",
"else",
":",
"times_looped",
"+=",
"1",
"if",
"times_looped",
">",
"number_retries",
":",
"raise",
"SaltInvocationError",
"(",
"'Attempting to sign file {0} failed, timed out after {1} seconds'",
".",
"format",
"(",
"abs_file",
",",
"int",
"(",
"times_looped",
"*",
"interval",
")",
")",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"proc_exitstatus",
"=",
"proc",
".",
"exitstatus",
"if",
"proc_exitstatus",
"!=",
"0",
":",
"raise",
"SaltInvocationError",
"(",
"'Signing file {0} failed with proc.status {1}'",
".",
"format",
"(",
"abs_file",
",",
"proc_exitstatus",
")",
")",
"except",
"salt",
".",
"utils",
".",
"vt",
".",
"TerminalException",
"as",
"err",
":",
"trace",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"log",
".",
"error",
"(",
"error_msg",
",",
"err",
",",
"trace",
")",
"res",
"=",
"{",
"'retcode'",
":",
"1",
",",
"'stdout'",
":",
"''",
",",
"'stderr'",
":",
"trace",
"}",
"finally",
":",
"proc",
".",
"close",
"(",
"terminate",
"=",
"True",
",",
"kill",
"=",
"True",
")",
"else",
":",
"cmd",
"=",
"'debsign --re-sign -k {0} {1}'",
".",
"format",
"(",
"local_key_fingerprint",
",",
"abs_file",
")",
"retrc",
"|=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"cwd",
"=",
"repodir",
",",
"use_vt",
"=",
"True",
",",
"env",
"=",
"env",
")",
"number_retries",
"=",
"timeout",
"/",
"interval",
"times_looped",
"=",
"0",
"error_msg",
"=",
"'Failed to reprepro includedsc file {0}'",
".",
"format",
"(",
"abs_file",
")",
"cmd",
"=",
"'reprepro --ignore=wrongdistribution --component=main -Vb . includedsc {0} {1}'",
".",
"format",
"(",
"codename",
",",
"abs_file",
")",
"if",
"(",
"(",
"__grains__",
"[",
"'os'",
"]",
"in",
"[",
"'Ubuntu'",
"]",
"and",
"__grains__",
"[",
"'osmajorrelease'",
"]",
"<",
"18",
")",
"or",
"(",
"__grains__",
"[",
"'os'",
"]",
"in",
"[",
"'Debian'",
"]",
"and",
"__grains__",
"[",
"'osmajorrelease'",
"]",
"<=",
"8",
")",
")",
":",
"try",
":",
"proc",
"=",
"salt",
".",
"utils",
".",
"vt",
".",
"Terminal",
"(",
"cmd",
",",
"env",
"=",
"env",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"repodir",
",",
"stream_stdout",
"=",
"True",
",",
"stream_stderr",
"=",
"True",
")",
"while",
"proc",
".",
"has_unread_data",
":",
"stdout",
",",
"_",
"=",
"proc",
".",
"recv",
"(",
")",
"if",
"stdout",
"and",
"REPREPRO_SIGN_PROMPT_RE",
".",
"search",
"(",
"stdout",
")",
":",
"# have the prompt for inputting the passphrase",
"proc",
".",
"sendline",
"(",
"phrase",
")",
"else",
":",
"times_looped",
"+=",
"1",
"if",
"times_looped",
">",
"number_retries",
":",
"raise",
"SaltInvocationError",
"(",
"'Attempting to reprepro includedsc for file {0} failed, timed out after {1} loops'",
".",
"format",
"(",
"abs_file",
",",
"times_looped",
")",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"proc_exitstatus",
"=",
"proc",
".",
"exitstatus",
"if",
"proc_exitstatus",
"!=",
"0",
":",
"raise",
"SaltInvocationError",
"(",
"'Reprepro includedsc for codename {0} and file {1} failed with proc.status {2}'",
".",
"format",
"(",
"codename",
",",
"abs_file",
",",
"proc_exitstatus",
")",
")",
"except",
"salt",
".",
"utils",
".",
"vt",
".",
"TerminalException",
"as",
"err",
":",
"trace",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"log",
".",
"error",
"(",
"error_msg",
",",
"err",
",",
"trace",
")",
"res",
"=",
"{",
"'retcode'",
":",
"1",
",",
"'stdout'",
":",
"''",
",",
"'stderr'",
":",
"trace",
"}",
"finally",
":",
"proc",
".",
"close",
"(",
"terminate",
"=",
"True",
",",
"kill",
"=",
"True",
")",
"else",
":",
"retrc",
"|=",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"cwd",
"=",
"repodir",
",",
"use_vt",
"=",
"True",
",",
"env",
"=",
"env",
")",
"if",
"retrc",
"!=",
"0",
":",
"raise",
"SaltInvocationError",
"(",
"'Making a repo encountered errors, return error {0}, check logs for further details'",
".",
"format",
"(",
"retrc",
")",
")",
"if",
"debfile",
".",
"endswith",
"(",
"'.deb'",
")",
":",
"cmd",
"=",
"'reprepro --ignore=wrongdistribution --component=main -Vb . includedeb {0} {1}'",
".",
"format",
"(",
"codename",
",",
"abs_file",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"runas",
"=",
"runas",
",",
"cwd",
"=",
"repodir",
",",
"use_vt",
"=",
"True",
",",
"env",
"=",
"env",
")",
"return",
"res"
] | Make a package repository and optionally sign it and packages present
Given the repodir (directory to create repository in), create a Debian
repository and optionally sign it and packages present. This state is
best used with onchanges linked to your package building states.
repodir
The directory to find packages that will be in the repository.
keyid
.. versionchanged:: 2016.3.0
Optional Key ID to use in signing packages and repository.
This consists of the last 8 hex digits of the GPG key ID.
Utilizes Public and Private keys associated with keyid which have
been loaded into the minion's Pillar data. Leverages gpg-agent and
gpg-preset-passphrase for caching keys, etc.
These pillar values are assumed to be filenames which are present
in ``gnupghome``. The pillar keys shown below have to match exactly.
For example, contents from a Pillar data file with named Public
and Private keys as follows:
.. code-block:: yaml
gpg_pkg_priv_keyname: gpg_pkg_key.pem
gpg_pkg_pub_keyname: gpg_pkg_key.pub
env
.. versionchanged:: 2016.3.0
A dictionary of environment variables to be utilized in creating the
repository.
use_passphrase : False
.. versionadded:: 2016.3.0
Use a passphrase with the signing key presented in ``keyid``.
Passphrase is received from Pillar data which could be passed on the
command line with ``pillar`` parameter. For example:
.. code-block:: bash
pillar='{ "gpg_passphrase" : "my_passphrase" }'
gnupghome : /etc/salt/gpgkeys
.. versionadded:: 2016.3.0
Location where GPG related files are stored, used with ``keyid``.
runas : root
.. versionadded:: 2016.3.0
User to create the repository as, and optionally sign packages.
.. note::
Ensure the user has correct permissions to any files and
directories which are to be utilized.
timeout : 15.0
.. versionadded:: 2016.3.4
Timeout in seconds to wait for the prompt for inputting the passphrase.
CLI Example:
.. code-block:: bash
salt '*' pkgbuild.make_repo /var/www/html | [
"Make",
"a",
"package",
"repository",
"and",
"optionally",
"sign",
"it",
"and",
"packages",
"present"
] | python | train |
pypa/pipenv | pipenv/vendor/vistir/path.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/path.py#L400-L455 | def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exception
This function will call check :func:`is_readonly_path` before attempting to call
:func:`set_write_bit` on the target path and try again.
"""
# Check for read-only attribute
from .compat import ResourceWarning, FileNotFoundError, PermissionError
PERM_ERRORS = (errno.EACCES, errno.EPERM, errno.ENOENT)
default_warning_message = "Unable to remove file due to permissions restriction: {!r}"
# split the initial exception out into its type, exception, and traceback
exc_type, exc_exception, exc_tb = exc
if is_readonly_path(path):
# Apply write permission and call original function
set_write_bit(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno == errno.ENOENT:
return
elif e.errno in PERM_ERRORS:
remaining = None
if os.path.isdir(path):
remaining =_wait_for_files(path)
if remaining:
warnings.warn(default_warning_message.format(path), ResourceWarning)
return
raise
if exc_exception.errno in PERM_ERRORS:
set_write_bit(path)
remaining = _wait_for_files(path)
try:
func(path)
except (OSError, IOError, FileNotFoundError, PermissionError) as e:
if e.errno in PERM_ERRORS:
warnings.warn(default_warning_message.format(path), ResourceWarning)
pass
elif e.errno == errno.ENOENT: # File already gone
pass
else:
raise
else:
return
elif exc_exception.errno == errno.ENOENT:
pass
else:
raise exc_exception | [
"def",
"handle_remove_readonly",
"(",
"func",
",",
"path",
",",
"exc",
")",
":",
"# Check for read-only attribute",
"from",
".",
"compat",
"import",
"ResourceWarning",
",",
"FileNotFoundError",
",",
"PermissionError",
"PERM_ERRORS",
"=",
"(",
"errno",
".",
"EACCES",
",",
"errno",
".",
"EPERM",
",",
"errno",
".",
"ENOENT",
")",
"default_warning_message",
"=",
"\"Unable to remove file due to permissions restriction: {!r}\"",
"# split the initial exception out into its type, exception, and traceback",
"exc_type",
",",
"exc_exception",
",",
"exc_tb",
"=",
"exc",
"if",
"is_readonly_path",
"(",
"path",
")",
":",
"# Apply write permission and call original function",
"set_write_bit",
"(",
"path",
")",
"try",
":",
"func",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"IOError",
",",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"elif",
"e",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"remaining",
"=",
"None",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"remaining",
"=",
"_wait_for_files",
"(",
"path",
")",
"if",
"remaining",
":",
"warnings",
".",
"warn",
"(",
"default_warning_message",
".",
"format",
"(",
"path",
")",
",",
"ResourceWarning",
")",
"return",
"raise",
"if",
"exc_exception",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"set_write_bit",
"(",
"path",
")",
"remaining",
"=",
"_wait_for_files",
"(",
"path",
")",
"try",
":",
"func",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"IOError",
",",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"in",
"PERM_ERRORS",
":",
"warnings",
".",
"warn",
"(",
"default_warning_message",
".",
"format",
"(",
"path",
")",
",",
"ResourceWarning",
")",
"pass",
"elif",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# File already gone",
"pass",
"else",
":",
"raise",
"else",
":",
"return",
"elif",
"exc_exception",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"pass",
"else",
":",
"raise",
"exc_exception"
] | Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exception
This function will call check :func:`is_readonly_path` before attempting to call
:func:`set_write_bit` on the target path and try again. | [
"Error",
"handler",
"for",
"shutil",
".",
"rmtree",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/pulse/pulse_lib/discrete.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/discrete.py#L74-L88 | def sawtooth(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse.
"""
if period is None:
period = duration
return _sampled_sawtooth_pulse(duration, amp, period, phase=phase, name=name) | [
"def",
"sawtooth",
"(",
"duration",
":",
"int",
",",
"amp",
":",
"complex",
",",
"period",
":",
"float",
"=",
"None",
",",
"phase",
":",
"float",
"=",
"0",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"SamplePulse",
":",
"if",
"period",
"is",
"None",
":",
"period",
"=",
"duration",
"return",
"_sampled_sawtooth_pulse",
"(",
"duration",
",",
"amp",
",",
"period",
",",
"phase",
"=",
"phase",
",",
"name",
"=",
"name",
")"
] | Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse. | [
"Generates",
"sawtooth",
"wave",
"SamplePulse",
"."
] | python | test |
bsolomon1124/pyfinance | pyfinance/general.py | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/general.py#L715-L722 | def loadings(self):
"""Loadings = eigenvectors times sqrt(eigenvalues)."""
loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues)
cols = ["PC%s" % i for i in range(1, self.keep + 1)]
loadings = pd.DataFrame(
loadings, columns=cols, index=self.feature_names
)
return loadings | [
"def",
"loadings",
"(",
"self",
")",
":",
"loadings",
"=",
"self",
".",
"v",
"[",
":",
",",
":",
"self",
".",
"keep",
"]",
"*",
"np",
".",
"sqrt",
"(",
"self",
".",
"eigenvalues",
")",
"cols",
"=",
"[",
"\"PC%s\"",
"%",
"i",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"self",
".",
"keep",
"+",
"1",
")",
"]",
"loadings",
"=",
"pd",
".",
"DataFrame",
"(",
"loadings",
",",
"columns",
"=",
"cols",
",",
"index",
"=",
"self",
".",
"feature_names",
")",
"return",
"loadings"
] | Loadings = eigenvectors times sqrt(eigenvalues). | [
"Loadings",
"=",
"eigenvectors",
"times",
"sqrt",
"(",
"eigenvalues",
")",
"."
] | python | train |
yvesalexandre/bandicoot | bandicoot/individual.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L88-L103 | def interactions_per_contact(records, direction=None):
"""
The number of interactions a user had with each of its contacts.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
"""
if direction is None:
counter = Counter(r.correspondent_id for r in records)
else:
counter = Counter(r.correspondent_id for r in records
if r.direction == direction)
return summary_stats(counter.values()) | [
"def",
"interactions_per_contact",
"(",
"records",
",",
"direction",
"=",
"None",
")",
":",
"if",
"direction",
"is",
"None",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
")",
"else",
":",
"counter",
"=",
"Counter",
"(",
"r",
".",
"correspondent_id",
"for",
"r",
"in",
"records",
"if",
"r",
".",
"direction",
"==",
"direction",
")",
"return",
"summary_stats",
"(",
"counter",
".",
"values",
"(",
")",
")"
] | The number of interactions a user had with each of its contacts.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing. | [
"The",
"number",
"of",
"interactions",
"a",
"user",
"had",
"with",
"each",
"of",
"its",
"contacts",
"."
] | python | train |
nfcpy/nfcpy | src/nfc/snep/client.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/snep/client.py#L254-L268 | def put_records(self, records, timeout=1.0):
"""Send NDEF message records to a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded
and then send via :meth:`put_octets`. Same as::
import ndef
octets = ndef.message_encoder(records)
snep_client.put_octets(octets, timeout)
"""
octets = b''.join(ndef.message_encoder(records))
return self.put_octets(octets, timeout) | [
"def",
"put_records",
"(",
"self",
",",
"records",
",",
"timeout",
"=",
"1.0",
")",
":",
"octets",
"=",
"b''",
".",
"join",
"(",
"ndef",
".",
"message_encoder",
"(",
"records",
")",
")",
"return",
"self",
".",
"put_octets",
"(",
"octets",
",",
"timeout",
")"
] | Send NDEF message records to a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded
and then send via :meth:`put_octets`. Same as::
import ndef
octets = ndef.message_encoder(records)
snep_client.put_octets(octets, timeout) | [
"Send",
"NDEF",
"message",
"records",
"to",
"a",
"SNEP",
"Server",
"."
] | python | train |
rueckstiess/mtools | mtools/mloginfo/sections/restart_section.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mloginfo/sections/restart_section.py#L35-L47 | def run(self):
"""Run this section and print out information."""
if ProfileCollection and isinstance(self.mloginfo.logfile,
ProfileCollection):
print("\n not available for system.profile collections\n")
return
for version, logevent in self.mloginfo.logfile.restarts:
print(" %s version %s"
% (logevent.datetime.strftime("%b %d %H:%M:%S"), version))
if len(self.mloginfo.logfile.restarts) == 0:
print(" no restarts found") | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"ProfileCollection",
"and",
"isinstance",
"(",
"self",
".",
"mloginfo",
".",
"logfile",
",",
"ProfileCollection",
")",
":",
"print",
"(",
"\"\\n not available for system.profile collections\\n\"",
")",
"return",
"for",
"version",
",",
"logevent",
"in",
"self",
".",
"mloginfo",
".",
"logfile",
".",
"restarts",
":",
"print",
"(",
"\" %s version %s\"",
"%",
"(",
"logevent",
".",
"datetime",
".",
"strftime",
"(",
"\"%b %d %H:%M:%S\"",
")",
",",
"version",
")",
")",
"if",
"len",
"(",
"self",
".",
"mloginfo",
".",
"logfile",
".",
"restarts",
")",
"==",
"0",
":",
"print",
"(",
"\" no restarts found\"",
")"
] | Run this section and print out information. | [
"Run",
"this",
"section",
"and",
"print",
"out",
"information",
"."
] | python | train |
nesdis/djongo | djongo/models/fields.py | https://github.com/nesdis/djongo/blob/7f9d79455cf030cb5eee0b822502c50a0d9d3abb/djongo/models/fields.py#L507-L517 | def to_python(self, value):
"""
Overrides Django's default to_python to allow correct
translation to instance.
"""
if value is None or isinstance(value, self.model_container):
return value
assert isinstance(value, dict)
instance = make_mdl(self.model_container, value)
return instance | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"isinstance",
"(",
"value",
",",
"self",
".",
"model_container",
")",
":",
"return",
"value",
"assert",
"isinstance",
"(",
"value",
",",
"dict",
")",
"instance",
"=",
"make_mdl",
"(",
"self",
".",
"model_container",
",",
"value",
")",
"return",
"instance"
] | Overrides Django's default to_python to allow correct
translation to instance. | [
"Overrides",
"Django",
"s",
"default",
"to_python",
"to",
"allow",
"correct",
"translation",
"to",
"instance",
"."
] | python | test |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py#L1628-L1673 | def drop_index(self, index_or_name):
"""Drops the specified index on this collection.
Can be used on non-existant collections or collections with no
indexes. Raises OperationFailure on an error (e.g. trying to
drop an index that does not exist). `index_or_name`
can be either an index name (as returned by `create_index`),
or an index specifier (as passed to `create_index`). An index
specifier should be a list of (key, direction) pairs. Raises
TypeError if index is not an instance of (str, unicode, list).
.. warning::
if a custom name was used on index creation (by
passing the `name` parameter to :meth:`create_index` or
:meth:`ensure_index`) the index **must** be dropped by name.
:Parameters:
- `index_or_name`: index (or name of index) to drop
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection's write concern automatically to this operation
when connected to MongoDB >= 3.4.
"""
name = index_or_name
if isinstance(index_or_name, list):
name = helpers._gen_index_name(index_or_name)
if not isinstance(name, string_type):
raise TypeError("index_or_name must be an index name or list")
self.__database.client._purge_index(
self.__database.name, self.__name, name)
cmd = SON([("dropIndexes", self.__name), ("index", name)])
with self._socket_for_writes() as sock_info:
self._command(sock_info,
cmd,
read_preference=ReadPreference.PRIMARY,
allowable_errors=["ns not found"],
write_concern=self.write_concern,
parse_write_concern_error=True) | [
"def",
"drop_index",
"(",
"self",
",",
"index_or_name",
")",
":",
"name",
"=",
"index_or_name",
"if",
"isinstance",
"(",
"index_or_name",
",",
"list",
")",
":",
"name",
"=",
"helpers",
".",
"_gen_index_name",
"(",
"index_or_name",
")",
"if",
"not",
"isinstance",
"(",
"name",
",",
"string_type",
")",
":",
"raise",
"TypeError",
"(",
"\"index_or_name must be an index name or list\"",
")",
"self",
".",
"__database",
".",
"client",
".",
"_purge_index",
"(",
"self",
".",
"__database",
".",
"name",
",",
"self",
".",
"__name",
",",
"name",
")",
"cmd",
"=",
"SON",
"(",
"[",
"(",
"\"dropIndexes\"",
",",
"self",
".",
"__name",
")",
",",
"(",
"\"index\"",
",",
"name",
")",
"]",
")",
"with",
"self",
".",
"_socket_for_writes",
"(",
")",
"as",
"sock_info",
":",
"self",
".",
"_command",
"(",
"sock_info",
",",
"cmd",
",",
"read_preference",
"=",
"ReadPreference",
".",
"PRIMARY",
",",
"allowable_errors",
"=",
"[",
"\"ns not found\"",
"]",
",",
"write_concern",
"=",
"self",
".",
"write_concern",
",",
"parse_write_concern_error",
"=",
"True",
")"
] | Drops the specified index on this collection.
Can be used on non-existant collections or collections with no
indexes. Raises OperationFailure on an error (e.g. trying to
drop an index that does not exist). `index_or_name`
can be either an index name (as returned by `create_index`),
or an index specifier (as passed to `create_index`). An index
specifier should be a list of (key, direction) pairs. Raises
TypeError if index is not an instance of (str, unicode, list).
.. warning::
if a custom name was used on index creation (by
passing the `name` parameter to :meth:`create_index` or
:meth:`ensure_index`) the index **must** be dropped by name.
:Parameters:
- `index_or_name`: index (or name of index) to drop
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection's write concern automatically to this operation
when connected to MongoDB >= 3.4. | [
"Drops",
"the",
"specified",
"index",
"on",
"this",
"collection",
"."
] | python | train |
ggaughan/pipe2py | pipe2py/modules/piperegex.py | https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/piperegex.py#L47-L79 | def asyncPipeRegex(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously replaces text in items using regexes.
Each has the general format: "In [field] replace [match] with [replace]".
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'RULE': [
{
'field': {'value': <'search field'>},
'match': {'value': <'regex'>},
'replace': {'value': <'replacement'>},
'globalmatch': {'value': '1'},
'singlelinematch': {'value': '2'},
'multilinematch': {'value': '4'},
'casematch': {'value': '8'}
}
]
}
Returns
-------
_OUTPUT : twisted.internet.defer.Deferred generator of items
"""
splits = yield asyncGetSplits(_INPUT, conf['RULE'], **cdicts(opts, kwargs))
asyncConvert = partial(maybeDeferred, convert_func)
asyncFuncs = get_async_dispatch_funcs('pass', asyncConvert)
parsed = yield asyncDispatch(splits, *asyncFuncs)
_OUTPUT = yield maybeDeferred(parse_results, parsed)
returnValue(iter(_OUTPUT)) | [
"def",
"asyncPipeRegex",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"yield",
"asyncGetSplits",
"(",
"_INPUT",
",",
"conf",
"[",
"'RULE'",
"]",
",",
"*",
"*",
"cdicts",
"(",
"opts",
",",
"kwargs",
")",
")",
"asyncConvert",
"=",
"partial",
"(",
"maybeDeferred",
",",
"convert_func",
")",
"asyncFuncs",
"=",
"get_async_dispatch_funcs",
"(",
"'pass'",
",",
"asyncConvert",
")",
"parsed",
"=",
"yield",
"asyncDispatch",
"(",
"splits",
",",
"*",
"asyncFuncs",
")",
"_OUTPUT",
"=",
"yield",
"maybeDeferred",
"(",
"parse_results",
",",
"parsed",
")",
"returnValue",
"(",
"iter",
"(",
"_OUTPUT",
")",
")"
] | An operator that asynchronously replaces text in items using regexes.
Each has the general format: "In [field] replace [match] with [replace]".
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'RULE': [
{
'field': {'value': <'search field'>},
'match': {'value': <'regex'>},
'replace': {'value': <'replacement'>},
'globalmatch': {'value': '1'},
'singlelinematch': {'value': '2'},
'multilinematch': {'value': '4'},
'casematch': {'value': '8'}
}
]
}
Returns
-------
_OUTPUT : twisted.internet.defer.Deferred generator of items | [
"An",
"operator",
"that",
"asynchronously",
"replaces",
"text",
"in",
"items",
"using",
"regexes",
".",
"Each",
"has",
"the",
"general",
"format",
":",
"In",
"[",
"field",
"]",
"replace",
"[",
"match",
"]",
"with",
"[",
"replace",
"]",
".",
"Not",
"loopable",
"."
] | python | train |
ejhigson/nestcheck | nestcheck/estimators.py | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/estimators.py#L141-L173 | def param_cred(ns_run, logw=None, simulate=False, probability=0.5,
param_ind=0):
"""One-tailed credible interval on the value of a single parameter
(component of theta).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if logw needs to be
calculated.
probability: float, optional
Quantile to estimate - must be in open interval (0, 1).
For example, use 0.5 for the median and 0.84 for the upper
84% quantile. Passed to weighted_quantile.
param_ind: int, optional
Index of parameter for which the credible interval should be
calculated. This corresponds to the column of ns_run['theta']
which contains the parameter.
Returns
-------
float
"""
if logw is None:
logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)
w_relative = np.exp(logw - logw.max()) # protect against overflow
return weighted_quantile(probability, ns_run['theta'][:, param_ind],
w_relative) | [
"def",
"param_cred",
"(",
"ns_run",
",",
"logw",
"=",
"None",
",",
"simulate",
"=",
"False",
",",
"probability",
"=",
"0.5",
",",
"param_ind",
"=",
"0",
")",
":",
"if",
"logw",
"is",
"None",
":",
"logw",
"=",
"nestcheck",
".",
"ns_run_utils",
".",
"get_logw",
"(",
"ns_run",
",",
"simulate",
"=",
"simulate",
")",
"w_relative",
"=",
"np",
".",
"exp",
"(",
"logw",
"-",
"logw",
".",
"max",
"(",
")",
")",
"# protect against overflow",
"return",
"weighted_quantile",
"(",
"probability",
",",
"ns_run",
"[",
"'theta'",
"]",
"[",
":",
",",
"param_ind",
"]",
",",
"w_relative",
")"
] | One-tailed credible interval on the value of a single parameter
(component of theta).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if logw needs to be
calculated.
probability: float, optional
Quantile to estimate - must be in open interval (0, 1).
For example, use 0.5 for the median and 0.84 for the upper
84% quantile. Passed to weighted_quantile.
param_ind: int, optional
Index of parameter for which the credible interval should be
calculated. This corresponds to the column of ns_run['theta']
which contains the parameter.
Returns
-------
float | [
"One",
"-",
"tailed",
"credible",
"interval",
"on",
"the",
"value",
"of",
"a",
"single",
"parameter",
"(",
"component",
"of",
"theta",
")",
"."
] | python | train |
log2timeline/plaso | plaso/lib/lexer.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/lexer.py#L307-L313 | def PrintTree(self, depth=''):
"""Print the tree."""
result = '{0:s}{1:s}\n'.format(depth, self.operator)
for part in self.args:
result += '{0:s}-{1:s}\n'.format(depth, part.PrintTree(depth + ' '))
return result | [
"def",
"PrintTree",
"(",
"self",
",",
"depth",
"=",
"''",
")",
":",
"result",
"=",
"'{0:s}{1:s}\\n'",
".",
"format",
"(",
"depth",
",",
"self",
".",
"operator",
")",
"for",
"part",
"in",
"self",
".",
"args",
":",
"result",
"+=",
"'{0:s}-{1:s}\\n'",
".",
"format",
"(",
"depth",
",",
"part",
".",
"PrintTree",
"(",
"depth",
"+",
"' '",
")",
")",
"return",
"result"
] | Print the tree. | [
"Print",
"the",
"tree",
"."
] | python | train |
spacetelescope/pysynphot | pysynphot/reddening.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/reddening.py#L79-L109 | def reddening(self,extval):
"""Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
Returns
-------
ans : `~pysynphot.spectrum.ArraySpectralElement`
Extinction curve to apply to a source spectrum.
"""
T = 10.0**(-0.4*extval*self.obscuration)
ans = ExtinctionSpectralElement(wave=self.wave,
waveunits=self.waveunits,
throughput=T,
name='%s(EBV=%g)'%(self.name, extval))
ans.citation = self.litref
return ans | [
"def",
"reddening",
"(",
"self",
",",
"extval",
")",
":",
"T",
"=",
"10.0",
"**",
"(",
"-",
"0.4",
"*",
"extval",
"*",
"self",
".",
"obscuration",
")",
"ans",
"=",
"ExtinctionSpectralElement",
"(",
"wave",
"=",
"self",
".",
"wave",
",",
"waveunits",
"=",
"self",
".",
"waveunits",
",",
"throughput",
"=",
"T",
",",
"name",
"=",
"'%s(EBV=%g)'",
"%",
"(",
"self",
".",
"name",
",",
"extval",
")",
")",
"ans",
".",
"citation",
"=",
"self",
".",
"litref",
"return",
"ans"
] | Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
Returns
-------
ans : `~pysynphot.spectrum.ArraySpectralElement`
Extinction curve to apply to a source spectrum. | [
"Compute",
"the",
"reddening",
"for",
"the",
"given",
"extinction",
"."
] | python | train |
minio/minio-py | minio/parsers.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L80-L87 | def findall(self, name):
"""Similar to ElementTree.Element.findall()
"""
return [
S3Element(self.root_name, elem)
for elem in self.element.findall('s3:{}'.format(name), _S3_NS)
] | [
"def",
"findall",
"(",
"self",
",",
"name",
")",
":",
"return",
"[",
"S3Element",
"(",
"self",
".",
"root_name",
",",
"elem",
")",
"for",
"elem",
"in",
"self",
".",
"element",
".",
"findall",
"(",
"'s3:{}'",
".",
"format",
"(",
"name",
")",
",",
"_S3_NS",
")",
"]"
] | Similar to ElementTree.Element.findall() | [
"Similar",
"to",
"ElementTree",
".",
"Element",
".",
"findall",
"()"
] | python | train |
GNS3/gns3-server | gns3server/compute/qemu/qcow2.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L91-L106 | def rebase(self, qemu_img, base_image):
"""
Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image
"""
if not os.path.exists(base_image):
raise FileNotFoundError(base_image)
command = [qemu_img, "rebase", "-u", "-b", base_image, self._path]
process = yield from asyncio.create_subprocess_exec(*command)
retcode = yield from process.wait()
if retcode != 0:
raise Qcow2Error("Could not rebase the image")
self._reload() | [
"def",
"rebase",
"(",
"self",
",",
"qemu_img",
",",
"base_image",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base_image",
")",
":",
"raise",
"FileNotFoundError",
"(",
"base_image",
")",
"command",
"=",
"[",
"qemu_img",
",",
"\"rebase\"",
",",
"\"-u\"",
",",
"\"-b\"",
",",
"base_image",
",",
"self",
".",
"_path",
"]",
"process",
"=",
"yield",
"from",
"asyncio",
".",
"create_subprocess_exec",
"(",
"*",
"command",
")",
"retcode",
"=",
"yield",
"from",
"process",
".",
"wait",
"(",
")",
"if",
"retcode",
"!=",
"0",
":",
"raise",
"Qcow2Error",
"(",
"\"Could not rebase the image\"",
")",
"self",
".",
"_reload",
"(",
")"
] | Rebase a linked clone in order to use the correct disk
:param qemu_img: Path to the qemu-img binary
:param base_image: Path to the base image | [
"Rebase",
"a",
"linked",
"clone",
"in",
"order",
"to",
"use",
"the",
"correct",
"disk"
] | python | train |
consbio/parserutils | parserutils/elements.py | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L480-L497 | def set_element_attributes(elem_to_parse, **attrib_kwargs):
"""
Adds the specified key/value pairs to the element's attributes, and
returns the updated set of attributes.
If the element already contains any of the attributes specified in
attrib_kwargs, they are updated accordingly.
"""
element = get_element(elem_to_parse)
if element is None:
return element
if len(attrib_kwargs):
element.attrib.update(attrib_kwargs)
return element.attrib | [
"def",
"set_element_attributes",
"(",
"elem_to_parse",
",",
"*",
"*",
"attrib_kwargs",
")",
":",
"element",
"=",
"get_element",
"(",
"elem_to_parse",
")",
"if",
"element",
"is",
"None",
":",
"return",
"element",
"if",
"len",
"(",
"attrib_kwargs",
")",
":",
"element",
".",
"attrib",
".",
"update",
"(",
"attrib_kwargs",
")",
"return",
"element",
".",
"attrib"
] | Adds the specified key/value pairs to the element's attributes, and
returns the updated set of attributes.
If the element already contains any of the attributes specified in
attrib_kwargs, they are updated accordingly. | [
"Adds",
"the",
"specified",
"key",
"/",
"value",
"pairs",
"to",
"the",
"element",
"s",
"attributes",
"and",
"returns",
"the",
"updated",
"set",
"of",
"attributes",
"."
] | python | train |
knipknap/exscript | Exscript/queue.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L693-L711 | def force_run(self, hosts, function, attempts=1):
"""
Like priority_run(), but starts the task immediately even if that
max_threads is exceeded.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task.
"""
return self._run(hosts,
function,
self.workqueue.priority_enqueue,
True,
attempts) | [
"def",
"force_run",
"(",
"self",
",",
"hosts",
",",
"function",
",",
"attempts",
"=",
"1",
")",
":",
"return",
"self",
".",
"_run",
"(",
"hosts",
",",
"function",
",",
"self",
".",
"workqueue",
".",
"priority_enqueue",
",",
"True",
",",
"attempts",
")"
] | Like priority_run(), but starts the task immediately even if that
max_threads is exceeded.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: function
:param function: The function to execute.
:type attempts: int
:param attempts: The number of attempts on failure.
:rtype: object
:return: An object representing the task. | [
"Like",
"priority_run",
"()",
"but",
"starts",
"the",
"task",
"immediately",
"even",
"if",
"that",
"max_threads",
"is",
"exceeded",
"."
] | python | train |
jason-weirather/py-seq-tools | seqtools/errors.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/errors.py#L53-L60 | def close(self):
"""Set some objects to None to hopefully free up some memory."""
self._target_context_errors = None
self._query_context_errors = None
self._general_errors = None
for ae in self._alignment_errors:
ae.close()
self._alignment_errors = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_target_context_errors",
"=",
"None",
"self",
".",
"_query_context_errors",
"=",
"None",
"self",
".",
"_general_errors",
"=",
"None",
"for",
"ae",
"in",
"self",
".",
"_alignment_errors",
":",
"ae",
".",
"close",
"(",
")",
"self",
".",
"_alignment_errors",
"=",
"None"
] | Set some objects to None to hopefully free up some memory. | [
"Set",
"some",
"objects",
"to",
"None",
"to",
"hopefully",
"free",
"up",
"some",
"memory",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/heterogeneity/loh.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/loh.py#L29-L49 | def get_coords(data):
"""Retrieve coordinates of genes of interest for prioritization.
Can read from CIViC input data or a supplied BED file of chrom, start, end
and gene information.
"""
for category, vtypes in [("LOH", {"LOSS", "HETEROZYGOSITY"}),
("amplification", {"AMPLIFICATION"})]:
out = tz.get_in([category, dd.get_genome_build(data)], _COORDS, {})
priority_file = dd.get_svprioritize(data)
if priority_file:
if os.path.basename(priority_file).find("civic") >= 0:
for chrom, start, end, gene in _civic_regions(priority_file, vtypes, dd.get_disease(data)):
out[gene] = (chrom, start, end)
elif os.path.basename(priority_file).find(".bed") >= 0:
for line in utils.open_gzipsafe(priority_file):
parts = line.strip().split("\t")
if len(parts) >= 4:
chrom, start, end, gene = parts[:4]
out[gene] = (chrom, int(start), int(end))
yield category, out | [
"def",
"get_coords",
"(",
"data",
")",
":",
"for",
"category",
",",
"vtypes",
"in",
"[",
"(",
"\"LOH\"",
",",
"{",
"\"LOSS\"",
",",
"\"HETEROZYGOSITY\"",
"}",
")",
",",
"(",
"\"amplification\"",
",",
"{",
"\"AMPLIFICATION\"",
"}",
")",
"]",
":",
"out",
"=",
"tz",
".",
"get_in",
"(",
"[",
"category",
",",
"dd",
".",
"get_genome_build",
"(",
"data",
")",
"]",
",",
"_COORDS",
",",
"{",
"}",
")",
"priority_file",
"=",
"dd",
".",
"get_svprioritize",
"(",
"data",
")",
"if",
"priority_file",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"priority_file",
")",
".",
"find",
"(",
"\"civic\"",
")",
">=",
"0",
":",
"for",
"chrom",
",",
"start",
",",
"end",
",",
"gene",
"in",
"_civic_regions",
"(",
"priority_file",
",",
"vtypes",
",",
"dd",
".",
"get_disease",
"(",
"data",
")",
")",
":",
"out",
"[",
"gene",
"]",
"=",
"(",
"chrom",
",",
"start",
",",
"end",
")",
"elif",
"os",
".",
"path",
".",
"basename",
"(",
"priority_file",
")",
".",
"find",
"(",
"\".bed\"",
")",
">=",
"0",
":",
"for",
"line",
"in",
"utils",
".",
"open_gzipsafe",
"(",
"priority_file",
")",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"len",
"(",
"parts",
")",
">=",
"4",
":",
"chrom",
",",
"start",
",",
"end",
",",
"gene",
"=",
"parts",
"[",
":",
"4",
"]",
"out",
"[",
"gene",
"]",
"=",
"(",
"chrom",
",",
"int",
"(",
"start",
")",
",",
"int",
"(",
"end",
")",
")",
"yield",
"category",
",",
"out"
] | Retrieve coordinates of genes of interest for prioritization.
Can read from CIViC input data or a supplied BED file of chrom, start, end
and gene information. | [
"Retrieve",
"coordinates",
"of",
"genes",
"of",
"interest",
"for",
"prioritization",
"."
] | python | train |
openai/pachi-py | pachi_py/pachi/tools/sgflib/sgflib.py | https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L164-L172 | def parseOneGame(self):
""" Parses one game from 'self.data'. Returns a 'GameTree' containing
one game, or 'None' if the end of 'self.data' has been reached."""
if self.index < self.datalen:
match = self.reGameTreeStart.match(self.data, self.index)
if match:
self.index = match.end()
return self.parseGameTree()
return None | [
"def",
"parseOneGame",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
"<",
"self",
".",
"datalen",
":",
"match",
"=",
"self",
".",
"reGameTreeStart",
".",
"match",
"(",
"self",
".",
"data",
",",
"self",
".",
"index",
")",
"if",
"match",
":",
"self",
".",
"index",
"=",
"match",
".",
"end",
"(",
")",
"return",
"self",
".",
"parseGameTree",
"(",
")",
"return",
"None"
] | Parses one game from 'self.data'. Returns a 'GameTree' containing
one game, or 'None' if the end of 'self.data' has been reached. | [
"Parses",
"one",
"game",
"from",
"self",
".",
"data",
".",
"Returns",
"a",
"GameTree",
"containing",
"one",
"game",
"or",
"None",
"if",
"the",
"end",
"of",
"self",
".",
"data",
"has",
"been",
"reached",
"."
] | python | train |
pgxcentre/geneparse | geneparse/readers/vcf.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/vcf.py#L58-L76 | def iter_genotypes(self):
"""Iterates on available markers.
Returns:
Genotypes instances.
"""
for v in self.get_vcf():
alleles = {v.REF} | set(v.ALT)
if self.quality_field:
variant = ImputedVariant(v.ID, v.CHROM, v.POS, alleles,
getattr(v, self.quality_field))
else:
variant = Variant(v.ID, v.CHROM, v.POS, alleles)
for coded_allele, g in self._make_genotypes(v.ALT, v.genotypes):
yield Genotypes(variant, g, v.REF, coded_allele,
multiallelic=len(v.ALT) > 1) | [
"def",
"iter_genotypes",
"(",
"self",
")",
":",
"for",
"v",
"in",
"self",
".",
"get_vcf",
"(",
")",
":",
"alleles",
"=",
"{",
"v",
".",
"REF",
"}",
"|",
"set",
"(",
"v",
".",
"ALT",
")",
"if",
"self",
".",
"quality_field",
":",
"variant",
"=",
"ImputedVariant",
"(",
"v",
".",
"ID",
",",
"v",
".",
"CHROM",
",",
"v",
".",
"POS",
",",
"alleles",
",",
"getattr",
"(",
"v",
",",
"self",
".",
"quality_field",
")",
")",
"else",
":",
"variant",
"=",
"Variant",
"(",
"v",
".",
"ID",
",",
"v",
".",
"CHROM",
",",
"v",
".",
"POS",
",",
"alleles",
")",
"for",
"coded_allele",
",",
"g",
"in",
"self",
".",
"_make_genotypes",
"(",
"v",
".",
"ALT",
",",
"v",
".",
"genotypes",
")",
":",
"yield",
"Genotypes",
"(",
"variant",
",",
"g",
",",
"v",
".",
"REF",
",",
"coded_allele",
",",
"multiallelic",
"=",
"len",
"(",
"v",
".",
"ALT",
")",
">",
"1",
")"
] | Iterates on available markers.
Returns:
Genotypes instances. | [
"Iterates",
"on",
"available",
"markers",
"."
] | python | train |
log2timeline/plaso | plaso/parsers/manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/manager.py#L354-L392 | def GetParsers(cls, parser_filter_expression=None):
"""Retrieves the registered parsers and plugins.
Retrieves a dictionary of all registered parsers and associated plugins
from a parser filter string. The filter string can contain direct names of
parsers, presets or plugins. The filter string can also negate selection
if prepended with an exclamation point, e.g.: "foo,!foo/bar" would include
parser foo but not include plugin bar. A list of specific included and
excluded plugins is also passed to each parser's class.
The three types of entries in the filter string:
* name of a parser: this would be the exact name of a single parser to
include (or exclude), e.g. foo;
* name of a preset, e.g. win7: the presets are defined in
plaso/parsers/presets.py;
* name of a plugin: if a plugin name is included the parent parser will be
included in the list of registered parsers;
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Yields:
tuple: containing:
* str: name of the parser:
* type: parser class (subclass of BaseParser).
"""
includes, excludes = cls._GetParserFilters(parser_filter_expression)
for parser_name, parser_class in iter(cls._parser_classes.items()):
# If there are no includes all parsers are included by default.
if not includes and parser_name in excludes:
continue
if includes and parser_name not in includes:
continue
yield parser_name, parser_class | [
"def",
"GetParsers",
"(",
"cls",
",",
"parser_filter_expression",
"=",
"None",
")",
":",
"includes",
",",
"excludes",
"=",
"cls",
".",
"_GetParserFilters",
"(",
"parser_filter_expression",
")",
"for",
"parser_name",
",",
"parser_class",
"in",
"iter",
"(",
"cls",
".",
"_parser_classes",
".",
"items",
"(",
")",
")",
":",
"# If there are no includes all parsers are included by default.",
"if",
"not",
"includes",
"and",
"parser_name",
"in",
"excludes",
":",
"continue",
"if",
"includes",
"and",
"parser_name",
"not",
"in",
"includes",
":",
"continue",
"yield",
"parser_name",
",",
"parser_class"
] | Retrieves the registered parsers and plugins.
Retrieves a dictionary of all registered parsers and associated plugins
from a parser filter string. The filter string can contain direct names of
parsers, presets or plugins. The filter string can also negate selection
if prepended with an exclamation point, e.g.: "foo,!foo/bar" would include
parser foo but not include plugin bar. A list of specific included and
excluded plugins is also passed to each parser's class.
The three types of entries in the filter string:
* name of a parser: this would be the exact name of a single parser to
include (or exclude), e.g. foo;
* name of a preset, e.g. win7: the presets are defined in
plaso/parsers/presets.py;
* name of a plugin: if a plugin name is included the parent parser will be
included in the list of registered parsers;
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Yields:
tuple: containing:
* str: name of the parser:
* type: parser class (subclass of BaseParser). | [
"Retrieves",
"the",
"registered",
"parsers",
"and",
"plugins",
"."
] | python | train |
mar10/wsgidav | wsgidav/util.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L874-L935 | def add_property_response(multistatusEL, href, propList):
"""Append <response> element to <multistatus> element.
<prop> node depends on the value type:
- str or unicode: add element with this content
- None: add an empty element
- etree.Element: add XML element as child
- DAVError: add an empty element to an own <propstatus> for this status code
@param multistatusEL: etree.Element
@param href: global URL of the resource, e.g. 'http://server:port/path'.
@param propList: list of 2-tuples (name, value)
"""
# Split propList by status code and build a unique list of namespaces
nsCount = 1
nsDict = {}
nsMap = {}
propDict = {}
for name, value in propList:
status = "200 OK"
if isinstance(value, DAVError):
status = get_http_status_string(value)
# Always generate *empty* elements for props with error status
value = None
# Collect namespaces, so we can declare them in the <response> for
# compacter output
ns, _ = split_namespace(name)
if ns != "DAV:" and ns not in nsDict and ns != "":
nsDict[ns] = True
nsMap["NS{}".format(nsCount)] = ns
nsCount += 1
propDict.setdefault(status, []).append((name, value))
# <response>
responseEL = make_sub_element(multistatusEL, "{DAV:}response", nsmap=nsMap)
# log("href value:{}".format(string_repr(href)))
# etree.SubElement(responseEL, "{DAV:}href").text = toUnicode(href)
etree.SubElement(responseEL, "{DAV:}href").text = href
# etree.SubElement(responseEL, "{DAV:}href").text = compat.quote(href, safe="/" + "!*'(),"
# + "$-_|.")
# One <propstat> per status code
for status in propDict:
propstatEL = etree.SubElement(responseEL, "{DAV:}propstat")
# List of <prop>
propEL = etree.SubElement(propstatEL, "{DAV:}prop")
for name, value in propDict[status]:
if value is None:
etree.SubElement(propEL, name)
elif is_etree_element(value):
propEL.append(value)
else:
# value must be string or unicode
# log("{} value:{}".format(name, string_repr(value)))
# etree.SubElement(propEL, name).text = value
etree.SubElement(propEL, name).text = to_unicode_safe(value)
# <status>
etree.SubElement(propstatEL, "{DAV:}status").text = "HTTP/1.1 {}".format(status) | [
"def",
"add_property_response",
"(",
"multistatusEL",
",",
"href",
",",
"propList",
")",
":",
"# Split propList by status code and build a unique list of namespaces",
"nsCount",
"=",
"1",
"nsDict",
"=",
"{",
"}",
"nsMap",
"=",
"{",
"}",
"propDict",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"propList",
":",
"status",
"=",
"\"200 OK\"",
"if",
"isinstance",
"(",
"value",
",",
"DAVError",
")",
":",
"status",
"=",
"get_http_status_string",
"(",
"value",
")",
"# Always generate *empty* elements for props with error status",
"value",
"=",
"None",
"# Collect namespaces, so we can declare them in the <response> for",
"# compacter output",
"ns",
",",
"_",
"=",
"split_namespace",
"(",
"name",
")",
"if",
"ns",
"!=",
"\"DAV:\"",
"and",
"ns",
"not",
"in",
"nsDict",
"and",
"ns",
"!=",
"\"\"",
":",
"nsDict",
"[",
"ns",
"]",
"=",
"True",
"nsMap",
"[",
"\"NS{}\"",
".",
"format",
"(",
"nsCount",
")",
"]",
"=",
"ns",
"nsCount",
"+=",
"1",
"propDict",
".",
"setdefault",
"(",
"status",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")",
"# <response>",
"responseEL",
"=",
"make_sub_element",
"(",
"multistatusEL",
",",
"\"{DAV:}response\"",
",",
"nsmap",
"=",
"nsMap",
")",
"# log(\"href value:{}\".format(string_repr(href)))",
"# etree.SubElement(responseEL, \"{DAV:}href\").text = toUnicode(href)",
"etree",
".",
"SubElement",
"(",
"responseEL",
",",
"\"{DAV:}href\"",
")",
".",
"text",
"=",
"href",
"# etree.SubElement(responseEL, \"{DAV:}href\").text = compat.quote(href, safe=\"/\" + \"!*'(),\"",
"# + \"$-_|.\")",
"# One <propstat> per status code",
"for",
"status",
"in",
"propDict",
":",
"propstatEL",
"=",
"etree",
".",
"SubElement",
"(",
"responseEL",
",",
"\"{DAV:}propstat\"",
")",
"# List of <prop>",
"propEL",
"=",
"etree",
".",
"SubElement",
"(",
"propstatEL",
",",
"\"{DAV:}prop\"",
")",
"for",
"name",
",",
"value",
"in",
"propDict",
"[",
"status",
"]",
":",
"if",
"value",
"is",
"None",
":",
"etree",
".",
"SubElement",
"(",
"propEL",
",",
"name",
")",
"elif",
"is_etree_element",
"(",
"value",
")",
":",
"propEL",
".",
"append",
"(",
"value",
")",
"else",
":",
"# value must be string or unicode",
"# log(\"{} value:{}\".format(name, string_repr(value)))",
"# etree.SubElement(propEL, name).text = value",
"etree",
".",
"SubElement",
"(",
"propEL",
",",
"name",
")",
".",
"text",
"=",
"to_unicode_safe",
"(",
"value",
")",
"# <status>",
"etree",
".",
"SubElement",
"(",
"propstatEL",
",",
"\"{DAV:}status\"",
")",
".",
"text",
"=",
"\"HTTP/1.1 {}\"",
".",
"format",
"(",
"status",
")"
] | Append <response> element to <multistatus> element.
<prop> node depends on the value type:
- str or unicode: add element with this content
- None: add an empty element
- etree.Element: add XML element as child
- DAVError: add an empty element to an own <propstatus> for this status code
@param multistatusEL: etree.Element
@param href: global URL of the resource, e.g. 'http://server:port/path'.
@param propList: list of 2-tuples (name, value) | [
"Append",
"<response",
">",
"element",
"to",
"<multistatus",
">",
"element",
"."
] | python | valid |
blockstack/virtualchain | virtualchain/lib/blockchain/bitcoin_blockchain/bits.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/bits.py#L1181-L1197 | def btc_tx_sign_input(tx, idx, prevout_script, prevout_amount, private_key_info, hashcode=SIGHASH_ALL, hashcodes=None, segwit=None, scriptsig_type=None, redeem_script=None, witness_script=None, **blockchain_opts):
"""
Sign a particular input in the given transaction.
@private_key_info can either be a private key, or it can be a dict with 'redeem_script' and 'private_keys' defined
Returns the tx with the signed input
"""
if segwit is None:
segwit = get_features('segwit')
if scriptsig_type is None:
scriptsig_type = btc_privkey_scriptsig_classify(private_key_info)
if scriptsig_type in ['p2wpkh', 'p2wsh', 'p2sh-p2wpkh', 'p2sh-p2wsh'] and not segwit:
raise ValueError("Segwit is not enabled, but {} is a segwit scriptsig type".format(prevout_script))
return btc_tx_sign(tx, idx, prevout_script, prevout_amount, private_key_info, scriptsig_type, hashcode=hashcode, hashcodes=hashcodes, redeem_script=redeem_script, witness_script=witness_script) | [
"def",
"btc_tx_sign_input",
"(",
"tx",
",",
"idx",
",",
"prevout_script",
",",
"prevout_amount",
",",
"private_key_info",
",",
"hashcode",
"=",
"SIGHASH_ALL",
",",
"hashcodes",
"=",
"None",
",",
"segwit",
"=",
"None",
",",
"scriptsig_type",
"=",
"None",
",",
"redeem_script",
"=",
"None",
",",
"witness_script",
"=",
"None",
",",
"*",
"*",
"blockchain_opts",
")",
":",
"if",
"segwit",
"is",
"None",
":",
"segwit",
"=",
"get_features",
"(",
"'segwit'",
")",
"if",
"scriptsig_type",
"is",
"None",
":",
"scriptsig_type",
"=",
"btc_privkey_scriptsig_classify",
"(",
"private_key_info",
")",
"if",
"scriptsig_type",
"in",
"[",
"'p2wpkh'",
",",
"'p2wsh'",
",",
"'p2sh-p2wpkh'",
",",
"'p2sh-p2wsh'",
"]",
"and",
"not",
"segwit",
":",
"raise",
"ValueError",
"(",
"\"Segwit is not enabled, but {} is a segwit scriptsig type\"",
".",
"format",
"(",
"prevout_script",
")",
")",
"return",
"btc_tx_sign",
"(",
"tx",
",",
"idx",
",",
"prevout_script",
",",
"prevout_amount",
",",
"private_key_info",
",",
"scriptsig_type",
",",
"hashcode",
"=",
"hashcode",
",",
"hashcodes",
"=",
"hashcodes",
",",
"redeem_script",
"=",
"redeem_script",
",",
"witness_script",
"=",
"witness_script",
")"
] | Sign a particular input in the given transaction.
@private_key_info can either be a private key, or it can be a dict with 'redeem_script' and 'private_keys' defined
Returns the tx with the signed input | [
"Sign",
"a",
"particular",
"input",
"in",
"the",
"given",
"transaction",
".",
"@private_key_info",
"can",
"either",
"be",
"a",
"private",
"key",
"or",
"it",
"can",
"be",
"a",
"dict",
"with",
"redeem_script",
"and",
"private_keys",
"defined"
] | python | train |
thombashi/SimpleSQLite | simplesqlite/core.py | https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L503-L519 | def insert(self, table_name, record, attr_names=None):
"""
Send an INSERT query to the database.
:param str table_name: Table name of executing the query.
:param record: Record to be inserted.
:type record: |dict|/|namedtuple|/|list|/|tuple|
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records`
"""
self.insert_many(table_name, records=[record], attr_names=attr_names) | [
"def",
"insert",
"(",
"self",
",",
"table_name",
",",
"record",
",",
"attr_names",
"=",
"None",
")",
":",
"self",
".",
"insert_many",
"(",
"table_name",
",",
"records",
"=",
"[",
"record",
"]",
",",
"attr_names",
"=",
"attr_names",
")"
] | Send an INSERT query to the database.
:param str table_name: Table name of executing the query.
:param record: Record to be inserted.
:type record: |dict|/|namedtuple|/|list|/|tuple|
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records` | [
"Send",
"an",
"INSERT",
"query",
"to",
"the",
"database",
"."
] | python | train |
pyviz/holoviews | holoviews/core/spaces.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L1894-L1908 | def keys(self, full_grid=False):
"""Returns the keys of the GridSpace
Args:
full_grid (bool, optional): Return full cross-product of keys
Returns:
List of keys
"""
keys = super(GridSpace, self).keys()
if self.ndims == 1 or not full_grid:
return keys
dim1_keys = sorted(set(k[0] for k in keys))
dim2_keys = sorted(set(k[1] for k in keys))
return [(d1, d2) for d1 in dim1_keys for d2 in dim2_keys] | [
"def",
"keys",
"(",
"self",
",",
"full_grid",
"=",
"False",
")",
":",
"keys",
"=",
"super",
"(",
"GridSpace",
",",
"self",
")",
".",
"keys",
"(",
")",
"if",
"self",
".",
"ndims",
"==",
"1",
"or",
"not",
"full_grid",
":",
"return",
"keys",
"dim1_keys",
"=",
"sorted",
"(",
"set",
"(",
"k",
"[",
"0",
"]",
"for",
"k",
"in",
"keys",
")",
")",
"dim2_keys",
"=",
"sorted",
"(",
"set",
"(",
"k",
"[",
"1",
"]",
"for",
"k",
"in",
"keys",
")",
")",
"return",
"[",
"(",
"d1",
",",
"d2",
")",
"for",
"d1",
"in",
"dim1_keys",
"for",
"d2",
"in",
"dim2_keys",
"]"
] | Returns the keys of the GridSpace
Args:
full_grid (bool, optional): Return full cross-product of keys
Returns:
List of keys | [
"Returns",
"the",
"keys",
"of",
"the",
"GridSpace"
] | python | train |
quantumlib/Cirq | cirq/ops/linear_combinations.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/linear_combinations.py#L94-L107 | def matrix(self) -> np.ndarray:
"""Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary.
"""
num_qubits = self.num_qubits()
if num_qubits is None:
raise ValueError('Unknown number of qubits')
num_dim = 2 ** num_qubits
result = np.zeros((num_dim, num_dim), dtype=np.complex128)
for gate, coefficient in self.items():
result += protocols.unitary(gate) * coefficient
return result | [
"def",
"matrix",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"num_qubits",
"=",
"self",
".",
"num_qubits",
"(",
")",
"if",
"num_qubits",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown number of qubits'",
")",
"num_dim",
"=",
"2",
"**",
"num_qubits",
"result",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_dim",
",",
"num_dim",
")",
",",
"dtype",
"=",
"np",
".",
"complex128",
")",
"for",
"gate",
",",
"coefficient",
"in",
"self",
".",
"items",
"(",
")",
":",
"result",
"+=",
"protocols",
".",
"unitary",
"(",
"gate",
")",
"*",
"coefficient",
"return",
"result"
] | Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary. | [
"Reconstructs",
"matrix",
"of",
"self",
"using",
"unitaries",
"of",
"underlying",
"gates",
"."
] | python | train |
PrefPy/prefpy | prefpy/mechanismMcmc.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmc.py#L328-L339 | def createBinaryRelation(self, m):
"""
Initialize a two-dimensional array of size m by m.
:ivar int m: A value for m.
"""
binaryRelation = []
for i in range(m):
binaryRelation.append(range(m))
binaryRelation[i][i] = 0
return binaryRelation | [
"def",
"createBinaryRelation",
"(",
"self",
",",
"m",
")",
":",
"binaryRelation",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"m",
")",
":",
"binaryRelation",
".",
"append",
"(",
"range",
"(",
"m",
")",
")",
"binaryRelation",
"[",
"i",
"]",
"[",
"i",
"]",
"=",
"0",
"return",
"binaryRelation"
] | Initialize a two-dimensional array of size m by m.
:ivar int m: A value for m. | [
"Initialize",
"a",
"two",
"-",
"dimensional",
"array",
"of",
"size",
"m",
"by",
"m",
".",
":",
"ivar",
"int",
"m",
":",
"A",
"value",
"for",
"m",
"."
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3263-L3268 | def coords_intersect(self):
"""Coordinates of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self)
)) | [
"def",
"coords_intersect",
"(",
"self",
")",
":",
"return",
"set",
".",
"intersection",
"(",
"*",
"map",
"(",
"set",
",",
"(",
"getattr",
"(",
"arr",
",",
"'coords_intersect'",
",",
"arr",
".",
"coords",
")",
"for",
"arr",
"in",
"self",
")",
")",
")"
] | Coordinates of the arrays in this list that are used in all arrays | [
"Coordinates",
"of",
"the",
"arrays",
"in",
"this",
"list",
"that",
"are",
"used",
"in",
"all",
"arrays"
] | python | train |
KrzyHonk/bpmn-python | bpmn_python/bpmn_diagram_export.py | https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L174-L190 | def export_boundary_event_info(node_params, output_element):
"""
Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element.
"""
output_element.set(consts.Consts.parallel_multiple, node_params[consts.Consts.parallel_multiple])
output_element.set(consts.Consts.cancel_activity, node_params[consts.Consts.cancel_activity])
output_element.set(consts.Consts.attached_to_ref, node_params[consts.Consts.attached_to_ref])
definitions = node_params[consts.Consts.event_definitions]
for definition in definitions:
definition_id = definition[consts.Consts.id]
definition_type = definition[consts.Consts.definition_type]
output_definition = eTree.SubElement(output_element, definition_type)
if definition_id != "":
output_definition.set(consts.Consts.id, definition_id) | [
"def",
"export_boundary_event_info",
"(",
"node_params",
",",
"output_element",
")",
":",
"output_element",
".",
"set",
"(",
"consts",
".",
"Consts",
".",
"parallel_multiple",
",",
"node_params",
"[",
"consts",
".",
"Consts",
".",
"parallel_multiple",
"]",
")",
"output_element",
".",
"set",
"(",
"consts",
".",
"Consts",
".",
"cancel_activity",
",",
"node_params",
"[",
"consts",
".",
"Consts",
".",
"cancel_activity",
"]",
")",
"output_element",
".",
"set",
"(",
"consts",
".",
"Consts",
".",
"attached_to_ref",
",",
"node_params",
"[",
"consts",
".",
"Consts",
".",
"attached_to_ref",
"]",
")",
"definitions",
"=",
"node_params",
"[",
"consts",
".",
"Consts",
".",
"event_definitions",
"]",
"for",
"definition",
"in",
"definitions",
":",
"definition_id",
"=",
"definition",
"[",
"consts",
".",
"Consts",
".",
"id",
"]",
"definition_type",
"=",
"definition",
"[",
"consts",
".",
"Consts",
".",
"definition_type",
"]",
"output_definition",
"=",
"eTree",
".",
"SubElement",
"(",
"output_element",
",",
"definition_type",
")",
"if",
"definition_id",
"!=",
"\"\"",
":",
"output_definition",
".",
"set",
"(",
"consts",
".",
"Consts",
".",
"id",
",",
"definition_id",
")"
] | Adds IntermediateCatchEvent attributes to exported XML element
:param node_params: dictionary with given intermediate catch event parameters,
:param output_element: object representing BPMN XML 'intermediateCatchEvent' element. | [
"Adds",
"IntermediateCatchEvent",
"attributes",
"to",
"exported",
"XML",
"element"
] | python | train |
tariqdaouda/pyGeno | pyGeno/bootstrap.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L91-L100 | def printDatawraps() :
"""print all available datawraps for bootstraping"""
l = listDatawraps()
printf("Available datawraps for boostraping\n")
for k, v in l.iteritems() :
printf(k)
printf("~"*len(k) + "|")
for vv in v :
printf(" "*len(k) + "|" + "~~~:> " + vv)
printf('\n') | [
"def",
"printDatawraps",
"(",
")",
":",
"l",
"=",
"listDatawraps",
"(",
")",
"printf",
"(",
"\"Available datawraps for boostraping\\n\"",
")",
"for",
"k",
",",
"v",
"in",
"l",
".",
"iteritems",
"(",
")",
":",
"printf",
"(",
"k",
")",
"printf",
"(",
"\"~\"",
"*",
"len",
"(",
"k",
")",
"+",
"\"|\"",
")",
"for",
"vv",
"in",
"v",
":",
"printf",
"(",
"\" \"",
"*",
"len",
"(",
"k",
")",
"+",
"\"|\"",
"+",
"\"~~~:> \"",
"+",
"vv",
")",
"printf",
"(",
"'\\n'",
")"
] | print all available datawraps for bootstraping | [
"print",
"all",
"available",
"datawraps",
"for",
"bootstraping"
] | python | train |
delph-in/pydelphin | delphin/mrs/query.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L297-L303 | def intrinsic_variables(xmrs):
"""Return the list of all intrinsic variables in *xmrs*"""
ivs = set(
ep.intrinsic_variable for ep in xmrs.eps()
if not ep.is_quantifier() and ep.intrinsic_variable is not None
)
return sorted(ivs, key=var_id) | [
"def",
"intrinsic_variables",
"(",
"xmrs",
")",
":",
"ivs",
"=",
"set",
"(",
"ep",
".",
"intrinsic_variable",
"for",
"ep",
"in",
"xmrs",
".",
"eps",
"(",
")",
"if",
"not",
"ep",
".",
"is_quantifier",
"(",
")",
"and",
"ep",
".",
"intrinsic_variable",
"is",
"not",
"None",
")",
"return",
"sorted",
"(",
"ivs",
",",
"key",
"=",
"var_id",
")"
] | Return the list of all intrinsic variables in *xmrs* | [
"Return",
"the",
"list",
"of",
"all",
"intrinsic",
"variables",
"in",
"*",
"xmrs",
"*"
] | python | train |
pgmpy/pgmpy | pgmpy/models/BayesianModel.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/BayesianModel.py#L456-L509 | def fit(self, data, estimator=None, state_names=[], complete_samples_only=True, **kwargs):
"""
Estimates the CPD for each variable based on a given data set.
Parameters
----------
data: pandas DataFrame object
DataFrame object with column names identical to the variable names of the network.
(If some values in the data are missing the data cells should be set to `numpy.NaN`.
Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)
estimator: Estimator class
One of:
- MaximumLikelihoodEstimator (default)
- BayesianEstimator: In this case, pass 'prior_type' and either 'pseudo_counts'
or 'equivalent_sample_size' as additional keyword arguments.
See `BayesianEstimator.get_parameters()` for usage.
state_names: dict (optional)
A dict indicating, for each variable, the discrete set of states
that the variable can take. If unspecified, the observed values
in the data set are taken to be the only possible states.
complete_samples_only: bool (default `True`)
Specifies how to deal with missing data, if present. If set to `True` all rows
that contain `np.Nan` somewhere are ignored. If `False` then, for each variable,
every row where neither the variable nor its parents are `np.NaN` is used.
Examples
--------
>>> import pandas as pd
>>> from pgmpy.models import BayesianModel
>>> from pgmpy.estimators import MaximumLikelihoodEstimator
>>> data = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]})
>>> model = BayesianModel([('A', 'C'), ('B', 'C')])
>>> model.fit(data)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7fb98a7d50f0>,
<TabularCPD representing P(B:2) at 0x7fb98a7d5588>,
<TabularCPD representing P(C:2 | A:2, B:2) at 0x7fb98a7b1f98>]
"""
from pgmpy.estimators import MaximumLikelihoodEstimator, BayesianEstimator, BaseEstimator
if estimator is None:
estimator = MaximumLikelihoodEstimator
else:
if not issubclass(estimator, BaseEstimator):
raise TypeError("Estimator object should be a valid pgmpy estimator.")
_estimator = estimator(self, data, state_names=state_names,
complete_samples_only=complete_samples_only)
cpds_list = _estimator.get_parameters(**kwargs)
self.add_cpds(*cpds_list) | [
"def",
"fit",
"(",
"self",
",",
"data",
",",
"estimator",
"=",
"None",
",",
"state_names",
"=",
"[",
"]",
",",
"complete_samples_only",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pgmpy",
".",
"estimators",
"import",
"MaximumLikelihoodEstimator",
",",
"BayesianEstimator",
",",
"BaseEstimator",
"if",
"estimator",
"is",
"None",
":",
"estimator",
"=",
"MaximumLikelihoodEstimator",
"else",
":",
"if",
"not",
"issubclass",
"(",
"estimator",
",",
"BaseEstimator",
")",
":",
"raise",
"TypeError",
"(",
"\"Estimator object should be a valid pgmpy estimator.\"",
")",
"_estimator",
"=",
"estimator",
"(",
"self",
",",
"data",
",",
"state_names",
"=",
"state_names",
",",
"complete_samples_only",
"=",
"complete_samples_only",
")",
"cpds_list",
"=",
"_estimator",
".",
"get_parameters",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"add_cpds",
"(",
"*",
"cpds_list",
")"
] | Estimates the CPD for each variable based on a given data set.
Parameters
----------
data: pandas DataFrame object
DataFrame object with column names identical to the variable names of the network.
(If some values in the data are missing the data cells should be set to `numpy.NaN`.
Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)
estimator: Estimator class
One of:
- MaximumLikelihoodEstimator (default)
- BayesianEstimator: In this case, pass 'prior_type' and either 'pseudo_counts'
or 'equivalent_sample_size' as additional keyword arguments.
See `BayesianEstimator.get_parameters()` for usage.
state_names: dict (optional)
A dict indicating, for each variable, the discrete set of states
that the variable can take. If unspecified, the observed values
in the data set are taken to be the only possible states.
complete_samples_only: bool (default `True`)
Specifies how to deal with missing data, if present. If set to `True` all rows
that contain `np.Nan` somewhere are ignored. If `False` then, for each variable,
every row where neither the variable nor its parents are `np.NaN` is used.
Examples
--------
>>> import pandas as pd
>>> from pgmpy.models import BayesianModel
>>> from pgmpy.estimators import MaximumLikelihoodEstimator
>>> data = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]})
>>> model = BayesianModel([('A', 'C'), ('B', 'C')])
>>> model.fit(data)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7fb98a7d50f0>,
<TabularCPD representing P(B:2) at 0x7fb98a7d5588>,
<TabularCPD representing P(C:2 | A:2, B:2) at 0x7fb98a7b1f98>] | [
"Estimates",
"the",
"CPD",
"for",
"each",
"variable",
"based",
"on",
"a",
"given",
"data",
"set",
"."
] | python | train |
aouyar/PyMunin | pysysinfo/asterisk.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/asterisk.py#L339-L348 | def hasApplication(self, app):
"""Returns True if app is among the loaded modules.
@param app: Module name.
@return: Boolean
"""
if self._applications is None:
self._initApplicationList()
return app in self._applications | [
"def",
"hasApplication",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"_applications",
"is",
"None",
":",
"self",
".",
"_initApplicationList",
"(",
")",
"return",
"app",
"in",
"self",
".",
"_applications"
] | Returns True if app is among the loaded modules.
@param app: Module name.
@return: Boolean | [
"Returns",
"True",
"if",
"app",
"is",
"among",
"the",
"loaded",
"modules",
"."
] | python | train |
python-rope/rope | rope/contrib/autoimport.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/contrib/autoimport.py#L160-L169 | def update_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module
`modname` is the name of a module.
"""
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleNotFoundError:
pass | [
"def",
"update_module",
"(",
"self",
",",
"modname",
",",
"underlined",
"=",
"None",
")",
":",
"try",
":",
"pymodule",
"=",
"self",
".",
"project",
".",
"get_module",
"(",
"modname",
")",
"self",
".",
"_add_names",
"(",
"pymodule",
",",
"modname",
",",
"underlined",
")",
"except",
"exceptions",
".",
"ModuleNotFoundError",
":",
"pass"
] | Update the cache for global names in `modname` module
`modname` is the name of a module. | [
"Update",
"the",
"cache",
"for",
"global",
"names",
"in",
"modname",
"module"
] | python | train |
trailofbits/manticore | manticore/platforms/linux.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1574-L1587 | def sys_dup(self, fd):
"""
Duplicates an open file descriptor
:rtype: int
:param fd: the open file descriptor to duplicate.
:return: the new file descriptor.
"""
if not self._is_fd_open(fd):
logger.info("DUP: Passed fd is not open. Returning EBADF")
return -errno.EBADF
newfd = self._dup(fd)
return newfd | [
"def",
"sys_dup",
"(",
"self",
",",
"fd",
")",
":",
"if",
"not",
"self",
".",
"_is_fd_open",
"(",
"fd",
")",
":",
"logger",
".",
"info",
"(",
"\"DUP: Passed fd is not open. Returning EBADF\"",
")",
"return",
"-",
"errno",
".",
"EBADF",
"newfd",
"=",
"self",
".",
"_dup",
"(",
"fd",
")",
"return",
"newfd"
] | Duplicates an open file descriptor
:rtype: int
:param fd: the open file descriptor to duplicate.
:return: the new file descriptor. | [
"Duplicates",
"an",
"open",
"file",
"descriptor",
":",
"rtype",
":",
"int",
":",
"param",
"fd",
":",
"the",
"open",
"file",
"descriptor",
"to",
"duplicate",
".",
":",
"return",
":",
"the",
"new",
"file",
"descriptor",
"."
] | python | valid |
alej0varas/django-registration-rest-framework | registration_api/serializers.py | https://github.com/alej0varas/django-registration-rest-framework/blob/485be6bd9c366c79d9974a4cdeb6d4931d6c6183/registration_api/serializers.py#L11-L15 | def to_native(self, obj):
"""Remove password field when serializing an object"""
ret = super(UserSerializer, self).to_native(obj)
del ret['password']
return ret | [
"def",
"to_native",
"(",
"self",
",",
"obj",
")",
":",
"ret",
"=",
"super",
"(",
"UserSerializer",
",",
"self",
")",
".",
"to_native",
"(",
"obj",
")",
"del",
"ret",
"[",
"'password'",
"]",
"return",
"ret"
] | Remove password field when serializing an object | [
"Remove",
"password",
"field",
"when",
"serializing",
"an",
"object"
] | python | train |
hannorein/rebound | rebound/simulation.py | https://github.com/hannorein/rebound/blob/bb0f814c98e629401acaab657cae2304b0e003f7/rebound/simulation.py#L176-L190 | def coordinates(self):
"""
Get or set the internal coordinate system.
Available coordinate systems are:
- ``'jacobi'`` (default)
- ``'democraticheliocentric'``
- ``'whds'``
"""
i = self._coordinates
for name, _i in COORDINATES.items():
if i==_i:
return name
return i | [
"def",
"coordinates",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"_coordinates",
"for",
"name",
",",
"_i",
"in",
"COORDINATES",
".",
"items",
"(",
")",
":",
"if",
"i",
"==",
"_i",
":",
"return",
"name",
"return",
"i"
] | Get or set the internal coordinate system.
Available coordinate systems are:
- ``'jacobi'`` (default)
- ``'democraticheliocentric'``
- ``'whds'`` | [
"Get",
"or",
"set",
"the",
"internal",
"coordinate",
"system",
"."
] | python | train |
trevisanj/f311 | f311/explorer/vis/plotsp.py | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/explorer/vis/plotsp.py#L239-L300 | def draw_spectra_stacked(ss, title=None, num_rows=None, setup=_default_setup):
"""Same as plot_spectra_stacked(), but does not call plt.show(); returns figure"""
n = len(ss)
assert n > 0, "ss is empty"
if not num_rows:
num_rows = n
num_cols = 1
else:
num_cols = int(np.ceil(float(n) / num_rows))
a99.format_BLB()
fig, axarr = plt.subplots(num_rows, num_cols, sharex=True, squeeze=False)
xmin = 1e38
xmax = -1e38
i, j = -1, num_cols
xunit, yunit = None, None
any_span = False
for s in ss:
j += 1
if j >= num_cols:
i += 1
if i >= num_rows:
break
j = 0
assert isinstance(s, ft.Spectrum)
ax = axarr[i, j]
y = s.y
ax.plot(s.x, y)
ymin_, ymax = ax.get_ylim()
ymin_now = ymin_ if setup.ymin is None else setup.ymin
ax.set_ylim([ymin_now, ymin_now + (ymax - ymin_now) * (1 + _T)]) # prevents top of line from being hidden by plot box
_set_plot(ax.set_ylabel, setup.fmt_ylabel, s)
_set_plot(ax.set_title, setup.fmt_title, s)
if len(s.x) > 0:
xmin, xmax = min(min(s.x), xmin), max(max(s.x), xmax)
any_span = True
if xunit is None:
xunit = s.xunit
else:
if xunit != s.xunit:
raise RuntimeError("Spectra x-units do not match")
if yunit is None:
yunit = s.yunit
else:
if yunit != s.yunit:
raise RuntimeError("Spectra x-units do not match")
if any_span:
span = xmax - xmin
ax.set_xlim([xmin - span * _T, xmax + span * _T])
for j in range(num_cols):
ax = axarr[num_rows - 1, j]
if setup.flag_xlabel and setup.fmt_xlabel:
_set_plot(ax.set_xlabel, setup.fmt_xlabel, s)
plt.tight_layout()
if title is not None:
fig.canvas.set_window_title(title)
return fig | [
"def",
"draw_spectra_stacked",
"(",
"ss",
",",
"title",
"=",
"None",
",",
"num_rows",
"=",
"None",
",",
"setup",
"=",
"_default_setup",
")",
":",
"n",
"=",
"len",
"(",
"ss",
")",
"assert",
"n",
">",
"0",
",",
"\"ss is empty\"",
"if",
"not",
"num_rows",
":",
"num_rows",
"=",
"n",
"num_cols",
"=",
"1",
"else",
":",
"num_cols",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"float",
"(",
"n",
")",
"/",
"num_rows",
")",
")",
"a99",
".",
"format_BLB",
"(",
")",
"fig",
",",
"axarr",
"=",
"plt",
".",
"subplots",
"(",
"num_rows",
",",
"num_cols",
",",
"sharex",
"=",
"True",
",",
"squeeze",
"=",
"False",
")",
"xmin",
"=",
"1e38",
"xmax",
"=",
"-",
"1e38",
"i",
",",
"j",
"=",
"-",
"1",
",",
"num_cols",
"xunit",
",",
"yunit",
"=",
"None",
",",
"None",
"any_span",
"=",
"False",
"for",
"s",
"in",
"ss",
":",
"j",
"+=",
"1",
"if",
"j",
">=",
"num_cols",
":",
"i",
"+=",
"1",
"if",
"i",
">=",
"num_rows",
":",
"break",
"j",
"=",
"0",
"assert",
"isinstance",
"(",
"s",
",",
"ft",
".",
"Spectrum",
")",
"ax",
"=",
"axarr",
"[",
"i",
",",
"j",
"]",
"y",
"=",
"s",
".",
"y",
"ax",
".",
"plot",
"(",
"s",
".",
"x",
",",
"y",
")",
"ymin_",
",",
"ymax",
"=",
"ax",
".",
"get_ylim",
"(",
")",
"ymin_now",
"=",
"ymin_",
"if",
"setup",
".",
"ymin",
"is",
"None",
"else",
"setup",
".",
"ymin",
"ax",
".",
"set_ylim",
"(",
"[",
"ymin_now",
",",
"ymin_now",
"+",
"(",
"ymax",
"-",
"ymin_now",
")",
"*",
"(",
"1",
"+",
"_T",
")",
"]",
")",
"# prevents top of line from being hidden by plot box",
"_set_plot",
"(",
"ax",
".",
"set_ylabel",
",",
"setup",
".",
"fmt_ylabel",
",",
"s",
")",
"_set_plot",
"(",
"ax",
".",
"set_title",
",",
"setup",
".",
"fmt_title",
",",
"s",
")",
"if",
"len",
"(",
"s",
".",
"x",
")",
">",
"0",
":",
"xmin",
",",
"xmax",
"=",
"min",
"(",
"min",
"(",
"s",
".",
"x",
")",
",",
"xmin",
")",
",",
"max",
"(",
"max",
"(",
"s",
".",
"x",
")",
",",
"xmax",
")",
"any_span",
"=",
"True",
"if",
"xunit",
"is",
"None",
":",
"xunit",
"=",
"s",
".",
"xunit",
"else",
":",
"if",
"xunit",
"!=",
"s",
".",
"xunit",
":",
"raise",
"RuntimeError",
"(",
"\"Spectra x-units do not match\"",
")",
"if",
"yunit",
"is",
"None",
":",
"yunit",
"=",
"s",
".",
"yunit",
"else",
":",
"if",
"yunit",
"!=",
"s",
".",
"yunit",
":",
"raise",
"RuntimeError",
"(",
"\"Spectra x-units do not match\"",
")",
"if",
"any_span",
":",
"span",
"=",
"xmax",
"-",
"xmin",
"ax",
".",
"set_xlim",
"(",
"[",
"xmin",
"-",
"span",
"*",
"_T",
",",
"xmax",
"+",
"span",
"*",
"_T",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"num_cols",
")",
":",
"ax",
"=",
"axarr",
"[",
"num_rows",
"-",
"1",
",",
"j",
"]",
"if",
"setup",
".",
"flag_xlabel",
"and",
"setup",
".",
"fmt_xlabel",
":",
"_set_plot",
"(",
"ax",
".",
"set_xlabel",
",",
"setup",
".",
"fmt_xlabel",
",",
"s",
")",
"plt",
".",
"tight_layout",
"(",
")",
"if",
"title",
"is",
"not",
"None",
":",
"fig",
".",
"canvas",
".",
"set_window_title",
"(",
"title",
")",
"return",
"fig"
] | Same as plot_spectra_stacked(), but does not call plt.show(); returns figure | [
"Same",
"as",
"plot_spectra_stacked",
"()",
"but",
"does",
"not",
"call",
"plt",
".",
"show",
"()",
";",
"returns",
"figure"
] | python | train |
SpriteLink/NIPAP | nipap-cli/nipap_cli/nipap_cli.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-cli/nipap_cli/nipap_cli.py#L1279-L1302 | def remove_pool(arg, opts, shell_opts):
""" Remove pool
"""
remove_confirmed = shell_opts.force
res = Pool.list({ 'name': arg })
if len(res) < 1:
print("No pool with name '%s' found." % arg, file=sys.stderr)
sys.exit(1)
p = res[0]
if not remove_confirmed:
res = input("Do you really want to remove the pool '%s'? [y/N]: " % p.name)
if res == 'y':
remove_confirmed = True
else:
print("Operation canceled.")
if remove_confirmed:
p.remove()
print("Pool '%s' removed." % p.name) | [
"def",
"remove_pool",
"(",
"arg",
",",
"opts",
",",
"shell_opts",
")",
":",
"remove_confirmed",
"=",
"shell_opts",
".",
"force",
"res",
"=",
"Pool",
".",
"list",
"(",
"{",
"'name'",
":",
"arg",
"}",
")",
"if",
"len",
"(",
"res",
")",
"<",
"1",
":",
"print",
"(",
"\"No pool with name '%s' found.\"",
"%",
"arg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"p",
"=",
"res",
"[",
"0",
"]",
"if",
"not",
"remove_confirmed",
":",
"res",
"=",
"input",
"(",
"\"Do you really want to remove the pool '%s'? [y/N]: \"",
"%",
"p",
".",
"name",
")",
"if",
"res",
"==",
"'y'",
":",
"remove_confirmed",
"=",
"True",
"else",
":",
"print",
"(",
"\"Operation canceled.\"",
")",
"if",
"remove_confirmed",
":",
"p",
".",
"remove",
"(",
")",
"print",
"(",
"\"Pool '%s' removed.\"",
"%",
"p",
".",
"name",
")"
] | Remove pool | [
"Remove",
"pool"
] | python | train |
wmayner/pyphi | pyphi/models/actual_causation.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/actual_causation.py#L248-L251 | def irreducible_causes(self):
"""The set of irreducible causes in this |Account|."""
return tuple(link for link in self
if link.direction is Direction.CAUSE) | [
"def",
"irreducible_causes",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"link",
"for",
"link",
"in",
"self",
"if",
"link",
".",
"direction",
"is",
"Direction",
".",
"CAUSE",
")"
] | The set of irreducible causes in this |Account|. | [
"The",
"set",
"of",
"irreducible",
"causes",
"in",
"this",
"|Account|",
"."
] | python | train |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L76-L95 | def update_content_item(access_token, content_item_id, payload):
'''
Name: update_content_item
Parameters: access_token, content_item_id, payload (dict)
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
content_item_url =\
construct_content_item_url(enrichment_url, content_item_id)
payload = create_random_payload(payload)
request = requests.put(content_item_url, json=payload, headers=headers)
if request.status_code == 200:
content_item = request.json()
return content_item
return {'status': request.status_code, "message": request.text} | [
"def",
"update_content_item",
"(",
"access_token",
",",
"content_item_id",
",",
"payload",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"content_item_url",
"=",
"construct_content_item_url",
"(",
"enrichment_url",
",",
"content_item_id",
")",
"payload",
"=",
"create_random_payload",
"(",
"payload",
")",
"request",
"=",
"requests",
".",
"put",
"(",
"content_item_url",
",",
"json",
"=",
"payload",
",",
"headers",
"=",
"headers",
")",
"if",
"request",
".",
"status_code",
"==",
"200",
":",
"content_item",
"=",
"request",
".",
"json",
"(",
")",
"return",
"content_item",
"return",
"{",
"'status'",
":",
"request",
".",
"status_code",
",",
"\"message\"",
":",
"request",
".",
"text",
"}"
] | Name: update_content_item
Parameters: access_token, content_item_id, payload (dict)
Return: dictionary | [
"Name",
":",
"update_content_item",
"Parameters",
":",
"access_token",
"content_item_id",
"payload",
"(",
"dict",
")",
"Return",
":",
"dictionary"
] | python | train |
JasonKessler/scattertext | scattertext/PriorFactory.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/PriorFactory.py#L95-L103 | def use_all_categories(self):
'''
Returns
-------
PriorFactory
'''
term_df = self.term_ranker.get_ranks()
self.priors += term_df.sum(axis=1).fillna(0.)
return self | [
"def",
"use_all_categories",
"(",
"self",
")",
":",
"term_df",
"=",
"self",
".",
"term_ranker",
".",
"get_ranks",
"(",
")",
"self",
".",
"priors",
"+=",
"term_df",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"fillna",
"(",
"0.",
")",
"return",
"self"
] | Returns
-------
PriorFactory | [
"Returns",
"-------",
"PriorFactory"
] | python | train |
seleniumbase/SeleniumBase | seleniumbase/utilities/selenium_grid/download_selenium_server.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/utilities/selenium_grid/download_selenium_server.py#L20-L35 | def download_selenium_server():
"""
Downloads the Selenium Server JAR file from its
online location and stores it locally.
"""
try:
local_file = open(JAR_FILE, 'wb')
remote_file = urlopen(SELENIUM_JAR)
print('Downloading the Selenium Server JAR file...\n')
local_file.write(remote_file.read())
local_file.close()
remote_file.close()
print('Download Complete!')
except Exception:
raise Exception("Error downloading the Selenium Server JAR file.\n"
"Details: %s" % sys.exc_info()[1]) | [
"def",
"download_selenium_server",
"(",
")",
":",
"try",
":",
"local_file",
"=",
"open",
"(",
"JAR_FILE",
",",
"'wb'",
")",
"remote_file",
"=",
"urlopen",
"(",
"SELENIUM_JAR",
")",
"print",
"(",
"'Downloading the Selenium Server JAR file...\\n'",
")",
"local_file",
".",
"write",
"(",
"remote_file",
".",
"read",
"(",
")",
")",
"local_file",
".",
"close",
"(",
")",
"remote_file",
".",
"close",
"(",
")",
"print",
"(",
"'Download Complete!'",
")",
"except",
"Exception",
":",
"raise",
"Exception",
"(",
"\"Error downloading the Selenium Server JAR file.\\n\"",
"\"Details: %s\"",
"%",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
")"
] | Downloads the Selenium Server JAR file from its
online location and stores it locally. | [
"Downloads",
"the",
"Selenium",
"Server",
"JAR",
"file",
"from",
"its",
"online",
"location",
"and",
"stores",
"it",
"locally",
"."
] | python | train |
nylas/nylas-python | nylas/utils.py | https://github.com/nylas/nylas-python/blob/c3e4dfc152b09bb8f886b1c64c6919b1f642cbc8/nylas/utils.py#L5-L12 | def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)):
"""
Convert a datetime to a timestamp.
https://stackoverflow.com/a/8778548/141395
"""
delta = dt - epoch
# return delta.total_seconds()
return delta.seconds + delta.days * 86400 | [
"def",
"timestamp_from_dt",
"(",
"dt",
",",
"epoch",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
")",
":",
"delta",
"=",
"dt",
"-",
"epoch",
"# return delta.total_seconds()",
"return",
"delta",
".",
"seconds",
"+",
"delta",
".",
"days",
"*",
"86400"
] | Convert a datetime to a timestamp.
https://stackoverflow.com/a/8778548/141395 | [
"Convert",
"a",
"datetime",
"to",
"a",
"timestamp",
".",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"8778548",
"/",
"141395"
] | python | train |
miso-belica/sumy | sumy/evaluation/rouge.py | https://github.com/miso-belica/sumy/blob/099ab4938e2c1b6a011297375586bac2953641b9/sumy/evaluation/rouge.py#L220-L251 | def _union_lcs(evaluated_sentences, reference_sentence):
"""
Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence
between reference sentence ri and candidate summary C. For example, if
r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and
c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 is
“w1 w2” and the longest common subsequence of r_i and c2 is “w1 w3 w5”. The
union longest common subsequence of r_i, c1, and c2 is “w1 w2 w3 w5” and
LCS_u(r_i, C) = 4/5.
:param evaluated_sentences:
The sentences that have been picked by the summarizer
:param reference_sentence:
One of the sentences in the reference summaries
:returns float: LCS_u(r_i, C)
:raises ValueError: raises exception if a param has len <= 0
"""
if len(evaluated_sentences) <= 0:
raise (ValueError("Collections must contain at least 1 sentence."))
lcs_union = set()
reference_words = _split_into_words([reference_sentence])
combined_lcs_length = 0
for eval_s in evaluated_sentences:
evaluated_words = _split_into_words([eval_s])
lcs = set(_recon_lcs(reference_words, evaluated_words))
combined_lcs_length += len(lcs)
lcs_union = lcs_union.union(lcs)
union_lcs_count = len(lcs_union)
union_lcs_value = union_lcs_count / combined_lcs_length
return union_lcs_value | [
"def",
"_union_lcs",
"(",
"evaluated_sentences",
",",
"reference_sentence",
")",
":",
"if",
"len",
"(",
"evaluated_sentences",
")",
"<=",
"0",
":",
"raise",
"(",
"ValueError",
"(",
"\"Collections must contain at least 1 sentence.\"",
")",
")",
"lcs_union",
"=",
"set",
"(",
")",
"reference_words",
"=",
"_split_into_words",
"(",
"[",
"reference_sentence",
"]",
")",
"combined_lcs_length",
"=",
"0",
"for",
"eval_s",
"in",
"evaluated_sentences",
":",
"evaluated_words",
"=",
"_split_into_words",
"(",
"[",
"eval_s",
"]",
")",
"lcs",
"=",
"set",
"(",
"_recon_lcs",
"(",
"reference_words",
",",
"evaluated_words",
")",
")",
"combined_lcs_length",
"+=",
"len",
"(",
"lcs",
")",
"lcs_union",
"=",
"lcs_union",
".",
"union",
"(",
"lcs",
")",
"union_lcs_count",
"=",
"len",
"(",
"lcs_union",
")",
"union_lcs_value",
"=",
"union_lcs_count",
"/",
"combined_lcs_length",
"return",
"union_lcs_value"
] | Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence
between reference sentence ri and candidate summary C. For example, if
r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and
c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 is
“w1 w2” and the longest common subsequence of r_i and c2 is “w1 w3 w5”. The
union longest common subsequence of r_i, c1, and c2 is “w1 w2 w3 w5” and
LCS_u(r_i, C) = 4/5.
:param evaluated_sentences:
The sentences that have been picked by the summarizer
:param reference_sentence:
One of the sentences in the reference summaries
:returns float: LCS_u(r_i, C)
:raises ValueError: raises exception if a param has len <= 0 | [
"Returns",
"LCS_u",
"(",
"r_i",
"C",
")",
"which",
"is",
"the",
"LCS",
"score",
"of",
"the",
"union",
"longest",
"common",
"subsequence",
"between",
"reference",
"sentence",
"ri",
"and",
"candidate",
"summary",
"C",
".",
"For",
"example",
"if",
"r_i",
"=",
"w1",
"w2",
"w3",
"w4",
"w5",
"and",
"C",
"contains",
"two",
"sentences",
":",
"c1",
"=",
"w1",
"w2",
"w6",
"w7",
"w8",
"and",
"c2",
"=",
"w1",
"w3",
"w8",
"w9",
"w5",
"then",
"the",
"longest",
"common",
"subsequence",
"of",
"r_i",
"and",
"c1",
"is",
"“w1",
"w2”",
"and",
"the",
"longest",
"common",
"subsequence",
"of",
"r_i",
"and",
"c2",
"is",
"“w1",
"w3",
"w5”",
".",
"The",
"union",
"longest",
"common",
"subsequence",
"of",
"r_i",
"c1",
"and",
"c2",
"is",
"“w1",
"w2",
"w3",
"w5”",
"and",
"LCS_u",
"(",
"r_i",
"C",
")",
"=",
"4",
"/",
"5",
"."
] | python | train |
HPENetworking/PYHPEIMC | build/lib/pyhpeimc/wsm/acinfo.py | https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/wsm/acinfo.py#L15-L76 | def get_ac_info_all(auth, url):
"""
function takes no input as input to RESTFUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each element of the list represents a single wireless controller which has been
discovered in the HPE IMC WSM module
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.wsm.acinfo import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> ac_info_all = get_ac_info_all(auth.creds, auth.url)
>>> assert type(ac_info_all) is list
>>> assert len(ac_info_all[0]) == 12
>>> assert 'hardwareVersion' in ac_info_all[0]
>>> assert 'ipAddress' in ac_info_all[0]
>>> assert 'label' in ac_info_all[0]
>>> assert 'macAddress' in ac_info_all[0]
>>> assert 'onlineApCount' in ac_info_all[0]
>>> assert 'onlineClientCount' in ac_info_all[0]
>>> assert 'pingStatus' in ac_info_all[0]
>>> assert 'serialId' in ac_info_all[0]
>>> assert 'softwareVersion' in ac_info_all[0]
>>> assert 'status' in ac_info_all[0]
>>> assert 'sysName' in ac_info_all[0]
>>> assert 'type' in ac_info_all[0]
"""
get_ac_info_all_url = "/imcrs/wlan/acInfo/queryAcBasicInfo"
f_url = url + get_ac_info_all_url
payload = None
r = requests.get(f_url, auth=auth,
headers=HEADERS) # creates the URL using the payload variable as the contents
# print(r.status_code)
try:
if r.status_code == 200:
if len(r.text) > 0:
return json.loads(r.text)['acBasicInfo']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_ac_info_all: An Error has occured" | [
"def",
"get_ac_info_all",
"(",
"auth",
",",
"url",
")",
":",
"get_ac_info_all_url",
"=",
"\"/imcrs/wlan/acInfo/queryAcBasicInfo\"",
"f_url",
"=",
"url",
"+",
"get_ac_info_all_url",
"payload",
"=",
"None",
"r",
"=",
"requests",
".",
"get",
"(",
"f_url",
",",
"auth",
"=",
"auth",
",",
"headers",
"=",
"HEADERS",
")",
"# creates the URL using the payload variable as the contents",
"# print(r.status_code)",
"try",
":",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"if",
"len",
"(",
"r",
".",
"text",
")",
">",
"0",
":",
"return",
"json",
".",
"loads",
"(",
"r",
".",
"text",
")",
"[",
"'acBasicInfo'",
"]",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"return",
"\"Error:\\n\"",
"+",
"str",
"(",
"e",
")",
"+",
"\" get_ac_info_all: An Error has occured\""
] | function takes no input as input to RESTFUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each element of the list represents a single wireless controller which has been
discovered in the HPE IMC WSM module
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.wsm.acinfo import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> ac_info_all = get_ac_info_all(auth.creds, auth.url)
>>> assert type(ac_info_all) is list
>>> assert len(ac_info_all[0]) == 12
>>> assert 'hardwareVersion' in ac_info_all[0]
>>> assert 'ipAddress' in ac_info_all[0]
>>> assert 'label' in ac_info_all[0]
>>> assert 'macAddress' in ac_info_all[0]
>>> assert 'onlineApCount' in ac_info_all[0]
>>> assert 'onlineClientCount' in ac_info_all[0]
>>> assert 'pingStatus' in ac_info_all[0]
>>> assert 'serialId' in ac_info_all[0]
>>> assert 'softwareVersion' in ac_info_all[0]
>>> assert 'status' in ac_info_all[0]
>>> assert 'sysName' in ac_info_all[0]
>>> assert 'type' in ac_info_all[0] | [
"function",
"takes",
"no",
"input",
"as",
"input",
"to",
"RESTFUL",
"call",
"to",
"HP",
"IMC"
] | python | train |
optimizely/python-sdk | optimizely/event_builder.py | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/event_builder.py#L272-L293 | def create_impression_event(self, experiment, variation_id, user_id, attributes):
""" Create impression Event to be sent to the logging endpoint.
Args:
experiment: Experiment for which impression needs to be recorded.
variation_id: ID for variation which would be presented to user.
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Event object encapsulating the impression event.
"""
params = self._get_common_params(user_id, attributes)
impression_params = self._get_required_params_for_impression(experiment, variation_id)
params[self.EventParams.USERS][0][self.EventParams.SNAPSHOTS].append(impression_params)
return Event(self.EVENTS_URL,
params,
http_verb=self.HTTP_VERB,
headers=self.HTTP_HEADERS) | [
"def",
"create_impression_event",
"(",
"self",
",",
"experiment",
",",
"variation_id",
",",
"user_id",
",",
"attributes",
")",
":",
"params",
"=",
"self",
".",
"_get_common_params",
"(",
"user_id",
",",
"attributes",
")",
"impression_params",
"=",
"self",
".",
"_get_required_params_for_impression",
"(",
"experiment",
",",
"variation_id",
")",
"params",
"[",
"self",
".",
"EventParams",
".",
"USERS",
"]",
"[",
"0",
"]",
"[",
"self",
".",
"EventParams",
".",
"SNAPSHOTS",
"]",
".",
"append",
"(",
"impression_params",
")",
"return",
"Event",
"(",
"self",
".",
"EVENTS_URL",
",",
"params",
",",
"http_verb",
"=",
"self",
".",
"HTTP_VERB",
",",
"headers",
"=",
"self",
".",
"HTTP_HEADERS",
")"
] | Create impression Event to be sent to the logging endpoint.
Args:
experiment: Experiment for which impression needs to be recorded.
variation_id: ID for variation which would be presented to user.
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Event object encapsulating the impression event. | [
"Create",
"impression",
"Event",
"to",
"be",
"sent",
"to",
"the",
"logging",
"endpoint",
"."
] | python | train |
Netflix-Skunkworks/historical | historical/historical-cookiecutter/historical_{{cookiecutter.technology_slug}}/{{cookiecutter.technology_slug}}/collector.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/historical-cookiecutter/historical_{{cookiecutter.technology_slug}}/{{cookiecutter.technology_slug}}/collector.py#L47-L58 | def group_records_by_type(records):
"""Break records into two lists; create/update events and delete events."""
update_records, delete_records = [], []
for r in records:
if isinstance(r, str):
break
if r['detail']['eventName'] in UPDATE_EVENTS:
update_records.append(r)
else:
delete_records.append(r)
return update_records, delete_records | [
"def",
"group_records_by_type",
"(",
"records",
")",
":",
"update_records",
",",
"delete_records",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"r",
"in",
"records",
":",
"if",
"isinstance",
"(",
"r",
",",
"str",
")",
":",
"break",
"if",
"r",
"[",
"'detail'",
"]",
"[",
"'eventName'",
"]",
"in",
"UPDATE_EVENTS",
":",
"update_records",
".",
"append",
"(",
"r",
")",
"else",
":",
"delete_records",
".",
"append",
"(",
"r",
")",
"return",
"update_records",
",",
"delete_records"
] | Break records into two lists; create/update events and delete events. | [
"Break",
"records",
"into",
"two",
"lists",
";",
"create",
"/",
"update",
"events",
"and",
"delete",
"events",
"."
] | python | train |
cqparts/cqparts | src/cqparts/params/parametric_object.py | https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L103-L123 | def class_params(cls, hidden=True):
"""
Gets all class parameters, and their :class:`Parameter` instances.
:return: dict of the form: ``{<name>: <Parameter instance>, ... }``
:rtype: :class:`dict`
.. note::
The :class:`Parameter` instances returned do not have a value, only
a default value.
To get a list of an **instance's** parameters and values, use
:meth:`params` instead.
"""
param_names = cls.class_param_names(hidden=hidden)
return dict(
(name, getattr(cls, name))
for name in param_names
) | [
"def",
"class_params",
"(",
"cls",
",",
"hidden",
"=",
"True",
")",
":",
"param_names",
"=",
"cls",
".",
"class_param_names",
"(",
"hidden",
"=",
"hidden",
")",
"return",
"dict",
"(",
"(",
"name",
",",
"getattr",
"(",
"cls",
",",
"name",
")",
")",
"for",
"name",
"in",
"param_names",
")"
] | Gets all class parameters, and their :class:`Parameter` instances.
:return: dict of the form: ``{<name>: <Parameter instance>, ... }``
:rtype: :class:`dict`
.. note::
The :class:`Parameter` instances returned do not have a value, only
a default value.
To get a list of an **instance's** parameters and values, use
:meth:`params` instead. | [
"Gets",
"all",
"class",
"parameters",
"and",
"their",
":",
"class",
":",
"Parameter",
"instances",
"."
] | python | train |
ellmetha/django-machina | machina/apps/forum_tracking/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L117-L121 | def mark_topics_read(self, request, pk):
""" Marks forum topics as read. """
track_handler.mark_forums_read([self.forum, ], request.user)
messages.success(request, self.success_message)
return HttpResponseRedirect(self.get_forum_url()) | [
"def",
"mark_topics_read",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"track_handler",
".",
"mark_forums_read",
"(",
"[",
"self",
".",
"forum",
",",
"]",
",",
"request",
".",
"user",
")",
"messages",
".",
"success",
"(",
"request",
",",
"self",
".",
"success_message",
")",
"return",
"HttpResponseRedirect",
"(",
"self",
".",
"get_forum_url",
"(",
")",
")"
] | Marks forum topics as read. | [
"Marks",
"forum",
"topics",
"as",
"read",
"."
] | python | train |
biocore/burrito | burrito/util.py | https://github.com/biocore/burrito/blob/3b1dcc560431cc2b7a4856b99aafe36d32082356/burrito/util.py#L447-L469 | def _error_on_missing_application(self, params):
""" Raise an ApplicationNotFoundError if the app is not accessible
This method checks in the system path (usually $PATH) or for
the existence of self._command. If self._command is not found
in either place, an ApplicationNotFoundError is raised to
inform the user that the application they are trying to access is
not available.
This method should be overwritten when self._command does not
represent the relevant executable (e.g., self._command = 'prog -a')
or in more complex cases where the file to be executed may be
passed as a parameter (e.g., with java jar files, where the
jar file is passed to java via '-jar'). It can also be overwritten
to by-pass testing for application presence by never raising an
error.
"""
command = self._command
# strip off " characters, in case we got a FilePath object
found_in_path = which(command.strip('"')) is not None
if not (exists(command) or found_in_path):
raise ApplicationNotFoundError("Cannot find %s. Is it installed? "
"Is it in your path?" % command) | [
"def",
"_error_on_missing_application",
"(",
"self",
",",
"params",
")",
":",
"command",
"=",
"self",
".",
"_command",
"# strip off \" characters, in case we got a FilePath object",
"found_in_path",
"=",
"which",
"(",
"command",
".",
"strip",
"(",
"'\"'",
")",
")",
"is",
"not",
"None",
"if",
"not",
"(",
"exists",
"(",
"command",
")",
"or",
"found_in_path",
")",
":",
"raise",
"ApplicationNotFoundError",
"(",
"\"Cannot find %s. Is it installed? \"",
"\"Is it in your path?\"",
"%",
"command",
")"
] | Raise an ApplicationNotFoundError if the app is not accessible
This method checks in the system path (usually $PATH) or for
the existence of self._command. If self._command is not found
in either place, an ApplicationNotFoundError is raised to
inform the user that the application they are trying to access is
not available.
This method should be overwritten when self._command does not
represent the relevant executable (e.g., self._command = 'prog -a')
or in more complex cases where the file to be executed may be
passed as a parameter (e.g., with java jar files, where the
jar file is passed to java via '-jar'). It can also be overwritten
to by-pass testing for application presence by never raising an
error. | [
"Raise",
"an",
"ApplicationNotFoundError",
"if",
"the",
"app",
"is",
"not",
"accessible"
] | python | train |
mohabusama/pyguacamole | guacamole/client.py | https://github.com/mohabusama/pyguacamole/blob/344dccc6cb3a9a045afeaf337677e5d0001aa83a/guacamole/client.py#L131-L136 | def send_instruction(self, instruction):
"""
Send instruction after encoding.
"""
self.logger.debug('Sending instruction: %s' % str(instruction))
return self.send(instruction.encode()) | [
"def",
"send_instruction",
"(",
"self",
",",
"instruction",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Sending instruction: %s'",
"%",
"str",
"(",
"instruction",
")",
")",
"return",
"self",
".",
"send",
"(",
"instruction",
".",
"encode",
"(",
")",
")"
] | Send instruction after encoding. | [
"Send",
"instruction",
"after",
"encoding",
"."
] | python | test |
quantopian/qgrid | qgrid/pd_json/json.py | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/json.py#L441-L513 | def _try_convert_data(self, name, data, use_dtypes=True,
convert_dates=True):
""" try to parse a ndarray like into a column by inferring dtype """
# don't try to coerce, unless a force conversion
if use_dtypes:
if self.dtype is False:
return data, False
elif self.dtype is True:
pass
else:
# dtype to force
dtype = (self.dtype.get(name)
if isinstance(self.dtype, dict) else self.dtype)
if dtype is not None:
try:
dtype = np.dtype(dtype)
return data.astype(dtype), True
except:
return data, False
if convert_dates:
new_data, result = self._try_convert_to_date(data)
if result:
return new_data, True
result = False
if data.dtype == 'object':
# try float
try:
data = data.astype('float64')
result = True
except:
pass
if data.dtype.kind == 'f':
if data.dtype != 'float64':
# coerce floats to 64
try:
data = data.astype('float64')
result = True
except:
pass
# do't coerce 0-len data
if len(data) and (data.dtype == 'float' or data.dtype == 'object'):
# coerce ints if we can
try:
new_data = data.astype('int64')
if (new_data == data).all():
data = new_data
result = True
except:
pass
# coerce ints to 64
if data.dtype == 'int':
# coerce floats to 64
try:
data = data.astype('int64')
result = True
except:
pass
return data, result | [
"def",
"_try_convert_data",
"(",
"self",
",",
"name",
",",
"data",
",",
"use_dtypes",
"=",
"True",
",",
"convert_dates",
"=",
"True",
")",
":",
"# don't try to coerce, unless a force conversion",
"if",
"use_dtypes",
":",
"if",
"self",
".",
"dtype",
"is",
"False",
":",
"return",
"data",
",",
"False",
"elif",
"self",
".",
"dtype",
"is",
"True",
":",
"pass",
"else",
":",
"# dtype to force",
"dtype",
"=",
"(",
"self",
".",
"dtype",
".",
"get",
"(",
"name",
")",
"if",
"isinstance",
"(",
"self",
".",
"dtype",
",",
"dict",
")",
"else",
"self",
".",
"dtype",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"try",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"return",
"data",
".",
"astype",
"(",
"dtype",
")",
",",
"True",
"except",
":",
"return",
"data",
",",
"False",
"if",
"convert_dates",
":",
"new_data",
",",
"result",
"=",
"self",
".",
"_try_convert_to_date",
"(",
"data",
")",
"if",
"result",
":",
"return",
"new_data",
",",
"True",
"result",
"=",
"False",
"if",
"data",
".",
"dtype",
"==",
"'object'",
":",
"# try float",
"try",
":",
"data",
"=",
"data",
".",
"astype",
"(",
"'float64'",
")",
"result",
"=",
"True",
"except",
":",
"pass",
"if",
"data",
".",
"dtype",
".",
"kind",
"==",
"'f'",
":",
"if",
"data",
".",
"dtype",
"!=",
"'float64'",
":",
"# coerce floats to 64",
"try",
":",
"data",
"=",
"data",
".",
"astype",
"(",
"'float64'",
")",
"result",
"=",
"True",
"except",
":",
"pass",
"# do't coerce 0-len data",
"if",
"len",
"(",
"data",
")",
"and",
"(",
"data",
".",
"dtype",
"==",
"'float'",
"or",
"data",
".",
"dtype",
"==",
"'object'",
")",
":",
"# coerce ints if we can",
"try",
":",
"new_data",
"=",
"data",
".",
"astype",
"(",
"'int64'",
")",
"if",
"(",
"new_data",
"==",
"data",
")",
".",
"all",
"(",
")",
":",
"data",
"=",
"new_data",
"result",
"=",
"True",
"except",
":",
"pass",
"# coerce ints to 64",
"if",
"data",
".",
"dtype",
"==",
"'int'",
":",
"# coerce floats to 64",
"try",
":",
"data",
"=",
"data",
".",
"astype",
"(",
"'int64'",
")",
"result",
"=",
"True",
"except",
":",
"pass",
"return",
"data",
",",
"result"
] | try to parse a ndarray like into a column by inferring dtype | [
"try",
"to",
"parse",
"a",
"ndarray",
"like",
"into",
"a",
"column",
"by",
"inferring",
"dtype"
] | python | train |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1032-L1048 | def _get_web_auth_token(self):
"""
Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session.
"""
request = _Request(self.network, "auth.getToken")
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
e = doc.getElementsByTagName("token")[0]
return e.firstChild.data | [
"def",
"_get_web_auth_token",
"(",
"self",
")",
":",
"request",
"=",
"_Request",
"(",
"self",
".",
"network",
",",
"\"auth.getToken\"",
")",
"# default action is that a request is signed only when",
"# a session key is provided.",
"request",
".",
"sign_it",
"(",
")",
"doc",
"=",
"request",
".",
"execute",
"(",
")",
"e",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"token\"",
")",
"[",
"0",
"]",
"return",
"e",
".",
"firstChild",
".",
"data"
] | Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session. | [
"Retrieves",
"a",
"token",
"from",
"the",
"network",
"for",
"web",
"authentication",
".",
"The",
"token",
"then",
"has",
"to",
"be",
"authorized",
"from",
"getAuthURL",
"before",
"creating",
"session",
"."
] | python | train |
yougov/openpack | openpack/basepack.py | https://github.com/yougov/openpack/blob/1412ec34c1bab6ba6c8ae5490c2205d696f13717/openpack/basepack.py#L507-L518 | def from_element(cls, element):
"given an element, parse out the proper ContentType"
# disambiguate the subclass
ns, class_name = parse_tag(element.tag)
class_ = getattr(ContentType, class_name)
if not class_:
msg = 'Invalid Types child element: %(class_name)s' % vars()
raise ValueError(msg)
# construct the subclass
key = element.get(class_.key_name)
name = element.get('ContentType')
return class_(name, key) | [
"def",
"from_element",
"(",
"cls",
",",
"element",
")",
":",
"# disambiguate the subclass",
"ns",
",",
"class_name",
"=",
"parse_tag",
"(",
"element",
".",
"tag",
")",
"class_",
"=",
"getattr",
"(",
"ContentType",
",",
"class_name",
")",
"if",
"not",
"class_",
":",
"msg",
"=",
"'Invalid Types child element: %(class_name)s'",
"%",
"vars",
"(",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# construct the subclass",
"key",
"=",
"element",
".",
"get",
"(",
"class_",
".",
"key_name",
")",
"name",
"=",
"element",
".",
"get",
"(",
"'ContentType'",
")",
"return",
"class_",
"(",
"name",
",",
"key",
")"
] | given an element, parse out the proper ContentType | [
"given",
"an",
"element",
"parse",
"out",
"the",
"proper",
"ContentType"
] | python | test |
couchbase/couchbase-python-client | couchbase/deprecation.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/deprecation.py#L4-L19 | def deprecate_module_attribute(mod, deprecated):
"""Return a wrapped object that warns about deprecated accesses"""
deprecated = set(deprecated)
class Wrapper(object):
def __getattr__(self, attr):
if attr in deprecated:
warnings.warn("Property %s is deprecated" % attr)
return getattr(mod, attr)
def __setattr__(self, attr, value):
if attr in deprecated:
warnings.warn("Property %s is deprecated" % attr)
return setattr(mod, attr, value)
return Wrapper() | [
"def",
"deprecate_module_attribute",
"(",
"mod",
",",
"deprecated",
")",
":",
"deprecated",
"=",
"set",
"(",
"deprecated",
")",
"class",
"Wrapper",
"(",
"object",
")",
":",
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"in",
"deprecated",
":",
"warnings",
".",
"warn",
"(",
"\"Property %s is deprecated\"",
"%",
"attr",
")",
"return",
"getattr",
"(",
"mod",
",",
"attr",
")",
"def",
"__setattr__",
"(",
"self",
",",
"attr",
",",
"value",
")",
":",
"if",
"attr",
"in",
"deprecated",
":",
"warnings",
".",
"warn",
"(",
"\"Property %s is deprecated\"",
"%",
"attr",
")",
"return",
"setattr",
"(",
"mod",
",",
"attr",
",",
"value",
")",
"return",
"Wrapper",
"(",
")"
] | Return a wrapped object that warns about deprecated accesses | [
"Return",
"a",
"wrapped",
"object",
"that",
"warns",
"about",
"deprecated",
"accesses"
] | python | train |
great-expectations/great_expectations | great_expectations/data_asset/base.py | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/data_asset/base.py#L962-L1056 | def _format_map_output(self,
result_format, success,
element_count, nonnull_count,
unexpected_count,
unexpected_list, unexpected_index_list
):
"""Helper function to construct expectation result objects for map_expectations (such as column_map_expectation
and file_lines_map_expectation).
Expectations support four result_formats: BOOLEAN_ONLY, BASIC, SUMMARY, and COMPLETE.
In each case, the object returned has a different set of populated fields.
See :ref:`result_format` for more information.
This function handles the logic for mapping those fields for column_map_expectations.
"""
# NB: unexpected_count parameter is explicit some implementing classes may limit the length of unexpected_list
# Retain support for string-only output formats:
result_format = parse_result_format(result_format)
# Incrementally add to result and return when all values for the specified level are present
return_obj = {
'success': success
}
if result_format['result_format'] == 'BOOLEAN_ONLY':
return return_obj
missing_count = element_count - nonnull_count
if element_count > 0:
unexpected_percent = unexpected_count / element_count
missing_percent = missing_count / element_count
if nonnull_count > 0:
unexpected_percent_nonmissing = unexpected_count / nonnull_count
else:
unexpected_percent_nonmissing = None
else:
missing_percent = None
unexpected_percent = None
unexpected_percent_nonmissing = None
return_obj['result'] = {
'element_count': element_count,
'missing_count': missing_count,
'missing_percent': missing_percent,
'unexpected_count': unexpected_count,
'unexpected_percent': unexpected_percent,
'unexpected_percent_nonmissing': unexpected_percent_nonmissing,
'partial_unexpected_list': unexpected_list[:result_format['partial_unexpected_count']]
}
if result_format['result_format'] == 'BASIC':
return return_obj
# Try to return the most common values, if possible.
if 0 < result_format.get('partial_unexpected_count'):
try:
partial_unexpected_counts = [
{'value': key, 'count': value}
for key, value
in sorted(
Counter(unexpected_list).most_common(result_format['partial_unexpected_count']),
key=lambda x: (-x[1], x[0]))
]
except TypeError:
partial_unexpected_counts = [
'partial_exception_counts requires a hashable type']
finally:
return_obj['result'].update(
{
'partial_unexpected_index_list': unexpected_index_list[:result_format[
'partial_unexpected_count']] if unexpected_index_list is not None else None,
'partial_unexpected_counts': partial_unexpected_counts
}
)
if result_format['result_format'] == 'SUMMARY':
return return_obj
return_obj['result'].update(
{
'unexpected_list': unexpected_list,
'unexpected_index_list': unexpected_index_list
}
)
if result_format['result_format'] == 'COMPLETE':
return return_obj
raise ValueError("Unknown result_format %s." %
(result_format['result_format'],)) | [
"def",
"_format_map_output",
"(",
"self",
",",
"result_format",
",",
"success",
",",
"element_count",
",",
"nonnull_count",
",",
"unexpected_count",
",",
"unexpected_list",
",",
"unexpected_index_list",
")",
":",
"# NB: unexpected_count parameter is explicit some implementing classes may limit the length of unexpected_list",
"# Retain support for string-only output formats:",
"result_format",
"=",
"parse_result_format",
"(",
"result_format",
")",
"# Incrementally add to result and return when all values for the specified level are present",
"return_obj",
"=",
"{",
"'success'",
":",
"success",
"}",
"if",
"result_format",
"[",
"'result_format'",
"]",
"==",
"'BOOLEAN_ONLY'",
":",
"return",
"return_obj",
"missing_count",
"=",
"element_count",
"-",
"nonnull_count",
"if",
"element_count",
">",
"0",
":",
"unexpected_percent",
"=",
"unexpected_count",
"/",
"element_count",
"missing_percent",
"=",
"missing_count",
"/",
"element_count",
"if",
"nonnull_count",
">",
"0",
":",
"unexpected_percent_nonmissing",
"=",
"unexpected_count",
"/",
"nonnull_count",
"else",
":",
"unexpected_percent_nonmissing",
"=",
"None",
"else",
":",
"missing_percent",
"=",
"None",
"unexpected_percent",
"=",
"None",
"unexpected_percent_nonmissing",
"=",
"None",
"return_obj",
"[",
"'result'",
"]",
"=",
"{",
"'element_count'",
":",
"element_count",
",",
"'missing_count'",
":",
"missing_count",
",",
"'missing_percent'",
":",
"missing_percent",
",",
"'unexpected_count'",
":",
"unexpected_count",
",",
"'unexpected_percent'",
":",
"unexpected_percent",
",",
"'unexpected_percent_nonmissing'",
":",
"unexpected_percent_nonmissing",
",",
"'partial_unexpected_list'",
":",
"unexpected_list",
"[",
":",
"result_format",
"[",
"'partial_unexpected_count'",
"]",
"]",
"}",
"if",
"result_format",
"[",
"'result_format'",
"]",
"==",
"'BASIC'",
":",
"return",
"return_obj",
"# Try to return the most common values, if possible.",
"if",
"0",
"<",
"result_format",
".",
"get",
"(",
"'partial_unexpected_count'",
")",
":",
"try",
":",
"partial_unexpected_counts",
"=",
"[",
"{",
"'value'",
":",
"key",
",",
"'count'",
":",
"value",
"}",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"Counter",
"(",
"unexpected_list",
")",
".",
"most_common",
"(",
"result_format",
"[",
"'partial_unexpected_count'",
"]",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"-",
"x",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
")",
")",
"]",
"except",
"TypeError",
":",
"partial_unexpected_counts",
"=",
"[",
"'partial_exception_counts requires a hashable type'",
"]",
"finally",
":",
"return_obj",
"[",
"'result'",
"]",
".",
"update",
"(",
"{",
"'partial_unexpected_index_list'",
":",
"unexpected_index_list",
"[",
":",
"result_format",
"[",
"'partial_unexpected_count'",
"]",
"]",
"if",
"unexpected_index_list",
"is",
"not",
"None",
"else",
"None",
",",
"'partial_unexpected_counts'",
":",
"partial_unexpected_counts",
"}",
")",
"if",
"result_format",
"[",
"'result_format'",
"]",
"==",
"'SUMMARY'",
":",
"return",
"return_obj",
"return_obj",
"[",
"'result'",
"]",
".",
"update",
"(",
"{",
"'unexpected_list'",
":",
"unexpected_list",
",",
"'unexpected_index_list'",
":",
"unexpected_index_list",
"}",
")",
"if",
"result_format",
"[",
"'result_format'",
"]",
"==",
"'COMPLETE'",
":",
"return",
"return_obj",
"raise",
"ValueError",
"(",
"\"Unknown result_format %s.\"",
"%",
"(",
"result_format",
"[",
"'result_format'",
"]",
",",
")",
")"
] | Helper function to construct expectation result objects for map_expectations (such as column_map_expectation
and file_lines_map_expectation).
Expectations support four result_formats: BOOLEAN_ONLY, BASIC, SUMMARY, and COMPLETE.
In each case, the object returned has a different set of populated fields.
See :ref:`result_format` for more information.
This function handles the logic for mapping those fields for column_map_expectations. | [
"Helper",
"function",
"to",
"construct",
"expectation",
"result",
"objects",
"for",
"map_expectations",
"(",
"such",
"as",
"column_map_expectation",
"and",
"file_lines_map_expectation",
")",
"."
] | python | train |
jason-weirather/py-seq-tools | seqtools/structure/transcript/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/structure/transcript/__init__.py#L164-L170 | def set_strand(self,dir):
"""Set the strand (direction)
:param dir: direction + or -
:type dir: char
"""
self._options = self._options._replace(direction = dir) | [
"def",
"set_strand",
"(",
"self",
",",
"dir",
")",
":",
"self",
".",
"_options",
"=",
"self",
".",
"_options",
".",
"_replace",
"(",
"direction",
"=",
"dir",
")"
] | Set the strand (direction)
:param dir: direction + or -
:type dir: char | [
"Set",
"the",
"strand",
"(",
"direction",
")"
] | python | train |
slightlynybbled/tk_tools | tk_tools/groups.py | https://github.com/slightlynybbled/tk_tools/blob/7c1792cad42890251a34f0617ce9b4b3e7abcf50/tk_tools/groups.py#L447-L458 | def get(self):
"""
Retrieve the GUI elements for program use.
:return: a dictionary containing all \
of the data from the key/value entries
"""
data = dict()
for label, entry in zip(self.keys, self.values):
data[label.cget('text')] = entry.get()
return data | [
"def",
"get",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"label",
",",
"entry",
"in",
"zip",
"(",
"self",
".",
"keys",
",",
"self",
".",
"values",
")",
":",
"data",
"[",
"label",
".",
"cget",
"(",
"'text'",
")",
"]",
"=",
"entry",
".",
"get",
"(",
")",
"return",
"data"
] | Retrieve the GUI elements for program use.
:return: a dictionary containing all \
of the data from the key/value entries | [
"Retrieve",
"the",
"GUI",
"elements",
"for",
"program",
"use",
"."
] | python | train |
dpgaspar/Flask-AppBuilder | flask_appbuilder/cli.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/cli.py#L113-L123 | def version():
"""
Flask-AppBuilder package version
"""
click.echo(
click.style(
"F.A.B Version: {0}.".format(current_app.appbuilder.version),
bg="blue",
fg="white"
)
) | [
"def",
"version",
"(",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"F.A.B Version: {0}.\"",
".",
"format",
"(",
"current_app",
".",
"appbuilder",
".",
"version",
")",
",",
"bg",
"=",
"\"blue\"",
",",
"fg",
"=",
"\"white\"",
")",
")"
] | Flask-AppBuilder package version | [
"Flask",
"-",
"AppBuilder",
"package",
"version"
] | python | train |
ska-sa/katcp-python | katcp/sampling.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L109-L156 | def get_strategy(cls, strategyName, inform_callback, sensor,
*params, **kwargs):
"""Factory method to create a strategy object.
Parameters
----------
strategyName : str
Name of strategy.
inform_callback : callable, signature inform_callback(sensor, reading)
Callback to receive inform messages.
sensor : Sensor object
Sensor to sample.
params : list of objects
Custom sampling parameters for specified strategy.
Keyword Arguments
-----------------
ioloop : tornado.ioloop.IOLoop instance, optional
Tornado ioloop to use, otherwise tornado.ioloop.IOLoop.current()
Returns
-------
strategy : :class:`SampleStrategy` object
The created sampling strategy.
"""
if strategyName not in cls.SAMPLING_LOOKUP_REV:
raise ValueError("Unknown sampling strategy '%s'. "
"Known strategies are %s."
% (strategyName, cls.SAMPLING_LOOKUP.values()))
strategyType = cls.SAMPLING_LOOKUP_REV[strategyName]
if strategyType == cls.NONE:
return SampleNone(inform_callback, sensor, *params, **kwargs)
elif strategyType == cls.AUTO:
return SampleAuto(inform_callback, sensor, *params, **kwargs)
elif strategyType == cls.EVENT:
return SampleEvent(inform_callback, sensor, *params, **kwargs)
elif strategyType == cls.DIFFERENTIAL:
return SampleDifferential(inform_callback, sensor,
*params, **kwargs)
elif strategyType == cls.PERIOD:
return SamplePeriod(inform_callback, sensor, *params, **kwargs)
elif strategyType == cls.EVENT_RATE:
return SampleEventRate(inform_callback, sensor, *params, **kwargs)
elif strategyType == cls.DIFFERENTIAL_RATE:
return SampleDifferentialRate(inform_callback, sensor,
*params, **kwargs) | [
"def",
"get_strategy",
"(",
"cls",
",",
"strategyName",
",",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"strategyName",
"not",
"in",
"cls",
".",
"SAMPLING_LOOKUP_REV",
":",
"raise",
"ValueError",
"(",
"\"Unknown sampling strategy '%s'. \"",
"\"Known strategies are %s.\"",
"%",
"(",
"strategyName",
",",
"cls",
".",
"SAMPLING_LOOKUP",
".",
"values",
"(",
")",
")",
")",
"strategyType",
"=",
"cls",
".",
"SAMPLING_LOOKUP_REV",
"[",
"strategyName",
"]",
"if",
"strategyType",
"==",
"cls",
".",
"NONE",
":",
"return",
"SampleNone",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"AUTO",
":",
"return",
"SampleAuto",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"EVENT",
":",
"return",
"SampleEvent",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"DIFFERENTIAL",
":",
"return",
"SampleDifferential",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"PERIOD",
":",
"return",
"SamplePeriod",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"EVENT_RATE",
":",
"return",
"SampleEventRate",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")",
"elif",
"strategyType",
"==",
"cls",
".",
"DIFFERENTIAL_RATE",
":",
"return",
"SampleDifferentialRate",
"(",
"inform_callback",
",",
"sensor",
",",
"*",
"params",
",",
"*",
"*",
"kwargs",
")"
] | Factory method to create a strategy object.
Parameters
----------
strategyName : str
Name of strategy.
inform_callback : callable, signature inform_callback(sensor, reading)
Callback to receive inform messages.
sensor : Sensor object
Sensor to sample.
params : list of objects
Custom sampling parameters for specified strategy.
Keyword Arguments
-----------------
ioloop : tornado.ioloop.IOLoop instance, optional
Tornado ioloop to use, otherwise tornado.ioloop.IOLoop.current()
Returns
-------
strategy : :class:`SampleStrategy` object
The created sampling strategy. | [
"Factory",
"method",
"to",
"create",
"a",
"strategy",
"object",
"."
] | python | train |
redhat-cip/python-dciclient | dciclient/v1/shell_commands/topic.py | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/shell_commands/topic.py#L207-L222 | def list_attached_team(context, id, sort, limit, where, verbose):
"""list_attached_team(context, id, sort, limit. where. verbose)
List teams attached to a topic.
>>> dcictl topic-list-team
:param string id: ID of the topic to list teams for [required]
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param string where: An optional filter criteria
:param boolean verbose: Display verbose output
"""
result = topic.list_teams(context, id=id, sort=sort, limit=limit,
where=where)
utils.format_output(result, context.format, verbose=verbose) | [
"def",
"list_attached_team",
"(",
"context",
",",
"id",
",",
"sort",
",",
"limit",
",",
"where",
",",
"verbose",
")",
":",
"result",
"=",
"topic",
".",
"list_teams",
"(",
"context",
",",
"id",
"=",
"id",
",",
"sort",
"=",
"sort",
",",
"limit",
"=",
"limit",
",",
"where",
"=",
"where",
")",
"utils",
".",
"format_output",
"(",
"result",
",",
"context",
".",
"format",
",",
"verbose",
"=",
"verbose",
")"
] | list_attached_team(context, id, sort, limit. where. verbose)
List teams attached to a topic.
>>> dcictl topic-list-team
:param string id: ID of the topic to list teams for [required]
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param string where: An optional filter criteria
:param boolean verbose: Display verbose output | [
"list_attached_team",
"(",
"context",
"id",
"sort",
"limit",
".",
"where",
".",
"verbose",
")"
] | python | train |
RobotStudio/bors | bors/api/websock.py | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/websock.py#L54-L57 | def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket"""
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) | [
"def",
"_on_set_auth",
"(",
"self",
",",
"sock",
",",
"token",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"f\"Token received: {token}\"",
")",
"sock",
".",
"setAuthtoken",
"(",
"token",
")"
] | Set Auth request received from websocket | [
"Set",
"Auth",
"request",
"received",
"from",
"websocket"
] | python | train |
rueckstiess/mtools | mtools/util/logevent.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logevent.py#L839-L842 | def to_json(self, labels=None):
"""Convert LogEvent object to valid JSON."""
output = self.to_dict(labels)
return json.dumps(output, cls=DateTimeEncoder, ensure_ascii=False) | [
"def",
"to_json",
"(",
"self",
",",
"labels",
"=",
"None",
")",
":",
"output",
"=",
"self",
".",
"to_dict",
"(",
"labels",
")",
"return",
"json",
".",
"dumps",
"(",
"output",
",",
"cls",
"=",
"DateTimeEncoder",
",",
"ensure_ascii",
"=",
"False",
")"
] | Convert LogEvent object to valid JSON. | [
"Convert",
"LogEvent",
"object",
"to",
"valid",
"JSON",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.