hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2f9be1bb0d326f06c6e6fbd5b49648aaafd4d87c | mfincker/sweettweet-app | backend/sweettweet/services/utils.py | [
"BSD-3-Clause"
] | Python | alarm_metric | <not_specific> | def alarm_metric(a_true, a_pred):
'''
Returned a modified precision and recall score for the alarm prediction
task that counts an alarm prediction as positive if it happens
withing 15 min of a real hypoglycemic event
'''
a_pred_padded = np.pad(a_pred, pad_width = ((0, 0),(3,3)), constant_values = 0) # pad array... |
Returned a modified precision and recall score for the alarm prediction
task that counts an alarm prediction as positive if it happens
withing 15 min of a real hypoglycemic event
| Returned a modified precision and recall score for the alarm prediction
task that counts an alarm prediction as positive if it happens
withing 15 min of a real hypoglycemic event | [
"Returned",
"a",
"modified",
"precision",
"and",
"recall",
"score",
"for",
"the",
"alarm",
"prediction",
"task",
"that",
"counts",
"an",
"alarm",
"prediction",
"as",
"positive",
"if",
"it",
"happens",
"withing",
"15",
"min",
"of",
"a",
"real",
"hypoglycemic",
... | def alarm_metric(a_true, a_pred):
a_pred_padded = np.pad(a_pred, pad_width = ((0, 0),(3,3)), constant_values = 0)
a_true_padded = np.pad(a_true, pad_width = ((0, 0),(3,3)), constant_values = 0)
r = rolling_window(a_pred_padded, 7)
a_pred_all = (np.sum(r, axis = 2) >= 1).astype(int).flatten()
t = rolling_window(... | [
"def",
"alarm_metric",
"(",
"a_true",
",",
"a_pred",
")",
":",
"a_pred_padded",
"=",
"np",
".",
"pad",
"(",
"a_pred",
",",
"pad_width",
"=",
"(",
"(",
"0",
",",
"0",
")",
",",
"(",
"3",
",",
"3",
")",
")",
",",
"constant_values",
"=",
"0",
")",
... | Returned a modified precision and recall score for the alarm prediction
task that counts an alarm prediction as positive if it happens
withing 15 min of a real hypoglycemic event | [
"Returned",
"a",
"modified",
"precision",
"and",
"recall",
"score",
"for",
"the",
"alarm",
"prediction",
"task",
"that",
"counts",
"an",
"alarm",
"prediction",
"as",
"positive",
"if",
"it",
"happens",
"withing",
"15",
"min",
"of",
"a",
"real",
"hypoglycemic",
... | [
"'''\n\tReturned a modified precision and recall score for the alarm prediction\n\ttask that counts an alarm prediction as positive if it happens\n\twithing 15 min of a real hypoglycemic event\n\t'''",
"# pad array to acount for +/- 15 min",
"# true positive for precision",
"# false positive",
"# true posit... | [
{
"param": "a_true",
"type": null
},
{
"param": "a_pred",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "a_true",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_pred",
"type": null,
"docstring": null,
"docstring_tokens... |
2f9be1bb0d326f06c6e6fbd5b49648aaafd4d87c | mfincker/sweettweet-app | backend/sweettweet/services/utils.py | [
"BSD-3-Clause"
] | Python | glu_to_alarm | <not_specific> | def glu_to_alarm(y_true, y_pred):
'''
Convert glucose levels to alarm.
Alarm state is positive if glucose at time
t and t-1 is < 70 and >70 at time t-2.
'''
hypo_real = (y_true < 70).astype(int)
hypo_pred = (y_pred < 70).astype(int)
a_pred = np.array([hypo_pred[0]] + [True if (hypo_pred[i] == True and hypo_p... |
Convert glucose levels to alarm.
Alarm state is positive if glucose at time
t and t-1 is < 70 and >70 at time t-2.
| Convert glucose levels to alarm.
Alarm state is positive if glucose at time
t and t-1 is < 70 and >70 at time t-2. | [
"Convert",
"glucose",
"levels",
"to",
"alarm",
".",
"Alarm",
"state",
"is",
"positive",
"if",
"glucose",
"at",
"time",
"t",
"and",
"t",
"-",
"1",
"is",
"<",
"70",
"and",
">",
"70",
"at",
"time",
"t",
"-",
"2",
"."
] | def glu_to_alarm(y_true, y_pred):
hypo_real = (y_true < 70).astype(int)
hypo_pred = (y_pred < 70).astype(int)
a_pred = np.array([hypo_pred[0]] + [True if (hypo_pred[i] == True and hypo_pred[i-1] == False)
else False
for i in range(1, len(hypo_pred))], ndmin = 2)
a_true = np.array([hypo_r... | [
"def",
"glu_to_alarm",
"(",
"y_true",
",",
"y_pred",
")",
":",
"hypo_real",
"=",
"(",
"y_true",
"<",
"70",
")",
".",
"astype",
"(",
"int",
")",
"hypo_pred",
"=",
"(",
"y_pred",
"<",
"70",
")",
".",
"astype",
"(",
"int",
")",
"a_pred",
"=",
"np",
... | Convert glucose levels to alarm. | [
"Convert",
"glucose",
"levels",
"to",
"alarm",
"."
] | [
"'''\n\tConvert glucose levels to alarm.\n\n\tAlarm state is positive if glucose at time \n\tt and t-1 is < 70 and >70 at time t-2.\n\t'''"
] | [
{
"param": "y_true",
"type": null
},
{
"param": "y_pred",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "y_true",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y_pred",
"type": null,
"docstring": null,
"docstring_tokens... |
4ab810e4a20314a42961e4f2d4a38ae6934857b1 | emlynjdavies/PySilCam | pysilcam/silcreport.py | [
"BSD-3-Clause"
] | Python | silcreport | null | def silcreport():
"""Generate a report figure for a processed dataset from the SilCam.
You can access this function from the command line using the below documentation.
Usage:
silcam-report <configfile> <statsfile> [--type=<particle_type>]
[--dpi=<dpi>] [--monitor]
Argum... | Generate a report figure for a processed dataset from the SilCam.
You can access this function from the command line using the below documentation.
Usage:
silcam-report <configfile> <statsfile> [--type=<particle_type>]
[--dpi=<dpi>] [--monitor]
Arguments:
configfile:... | Generate a report figure for a processed dataset from the SilCam.
You can access this function from the command line using the below documentation.
| [
"Generate",
"a",
"report",
"figure",
"for",
"a",
"processed",
"dataset",
"from",
"the",
"SilCam",
".",
"You",
"can",
"access",
"this",
"function",
"from",
"the",
"command",
"line",
"using",
"the",
"below",
"documentation",
"."
] | def silcreport():
args = docopt(silcreport.__doc__)
particle_type = scpp.outputPartType.all
particle_type_str = 'all'
if args['--type'] == 'oil':
particle_type = scpp.outputPartType.oil
particle_type_str = args['--type']
elif args['--type'] == 'gas':
particle_type = scpp.outp... | [
"def",
"silcreport",
"(",
")",
":",
"args",
"=",
"docopt",
"(",
"silcreport",
".",
"__doc__",
")",
"particle_type",
"=",
"scpp",
".",
"outputPartType",
".",
"all",
"particle_type_str",
"=",
"'all'",
"if",
"args",
"[",
"'--type'",
"]",
"==",
"'oil'",
":",
... | Generate a report figure for a processed dataset from the SilCam. | [
"Generate",
"a",
"report",
"figure",
"for",
"a",
"processed",
"dataset",
"from",
"the",
"SilCam",
"."
] | [
"\"\"\"Generate a report figure for a processed dataset from the SilCam.\n\n You can access this function from the command line using the below documentation.\n\n Usage:\n silcam-report <configfile> <statsfile> [--type=<particle_type>]\n [--dpi=<dpi>] [--monitor]\n\n Arguments:\... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "configfile",
"type": null,
"docstring": "The config filename associated with the data",
"docstring_tokens": [
"The",
"config",
"filename",
"associated",
"with",
... |
6d6accf244dded64b9cfaf0b6c6e65d876319bb0 | emlynjdavies/PySilCam | pysilcam/silcamgui/interactive_summary.py | [
"BSD-3-Clause"
] | Python | modify_av_wind | null | def modify_av_wind(self):
'''allow the user to modify the averaging period of interest'''
window_seconds = self.plot_fame.graph_view.av_window.seconds
input_value, okPressed = QInputDialog.getInt(self, "Get integer", "Average window:", window_seconds, 0, 60*60, 1)
if okPressed:
... | allow the user to modify the averaging period of interest | allow the user to modify the averaging period of interest | [
"allow",
"the",
"user",
"to",
"modify",
"the",
"averaging",
"period",
"of",
"interest"
] | def modify_av_wind(self):
window_seconds = self.plot_fame.graph_view.av_window.seconds
input_value, okPressed = QInputDialog.getInt(self, "Get integer", "Average window:", window_seconds, 0, 60*60, 1)
if okPressed:
self.plot_fame.graph_view.av_window = pd.Timedelta(seconds=input_valu... | [
"def",
"modify_av_wind",
"(",
"self",
")",
":",
"window_seconds",
"=",
"self",
".",
"plot_fame",
".",
"graph_view",
".",
"av_window",
".",
"seconds",
"input_value",
",",
"okPressed",
"=",
"QInputDialog",
".",
"getInt",
"(",
"self",
",",
"\"Get integer\"",
",",... | allow the user to modify the averaging period of interest | [
"allow",
"the",
"user",
"to",
"modify",
"the",
"averaging",
"period",
"of",
"interest"
] | [
"'''allow the user to modify the averaging period of interest'''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d6accf244dded64b9cfaf0b6c6e65d876319bb0 | emlynjdavies/PySilCam | pysilcam/silcamgui/interactive_summary.py | [
"BSD-3-Clause"
] | Python | load_data | <not_specific> | def load_data(self):
'''handles loading of data, depending on what is available'''
self.datadir = os.path.split(self.configfile)[0]
self.stats_filename = ''
self.stats_filename = QFileDialog.getOpenFileName(self,
caption='Load a ... | handles loading of data, depending on what is available | handles loading of data, depending on what is available | [
"handles",
"loading",
"of",
"data",
"depending",
"on",
"what",
"is",
"available"
] | def load_data(self):
self.datadir = os.path.split(self.configfile)[0]
self.stats_filename = ''
self.stats_filename = QFileDialog.getOpenFileName(self,
caption='Load a *-STATS.csv file',
... | [
"def",
"load_data",
"(",
"self",
")",
":",
"self",
".",
"datadir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"configfile",
")",
"[",
"0",
"]",
"self",
".",
"stats_filename",
"=",
"''",
"self",
".",
"stats_filename",
"=",
"QFileDialog",
... | handles loading of data, depending on what is available | [
"handles",
"loading",
"of",
"data",
"depending",
"on",
"what",
"is",
"available"
] | [
"'''handles loading of data, depending on what is available'''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d6accf244dded64b9cfaf0b6c6e65d876319bb0 | emlynjdavies/PySilCam | pysilcam/silcamgui/interactive_summary.py | [
"BSD-3-Clause"
] | Python | load_from_timeseries | null | def load_from_timeseries(self):
'''uses timeseries xls sheets assuming they are available'''
timeseriesgas_file = self.stats_filename.replace('-STATS.csv', '-TIMESERIESgas.xlsx')
timeseriesoil_file = self.stats_filename.replace('-STATS.csv', '-TIMESERIESoil.xlsx')
gas = pd.read_excel(ti... | uses timeseries xls sheets assuming they are available | uses timeseries xls sheets assuming they are available | [
"uses",
"timeseries",
"xls",
"sheets",
"assuming",
"they",
"are",
"available"
] | def load_from_timeseries(self):
timeseriesgas_file = self.stats_filename.replace('-STATS.csv', '-TIMESERIESgas.xlsx')
timeseriesoil_file = self.stats_filename.replace('-STATS.csv', '-TIMESERIESoil.xlsx')
gas = pd.read_excel(timeseriesgas_file, parse_dates=['Time'])
oil = pd.read_excel(ti... | [
"def",
"load_from_timeseries",
"(",
"self",
")",
":",
"timeseriesgas_file",
"=",
"self",
".",
"stats_filename",
".",
"replace",
"(",
"'-STATS.csv'",
",",
"'-TIMESERIESgas.xlsx'",
")",
"timeseriesoil_file",
"=",
"self",
".",
"stats_filename",
".",
"replace",
"(",
"... | uses timeseries xls sheets assuming they are available | [
"uses",
"timeseries",
"xls",
"sheets",
"assuming",
"they",
"are",
"available"
] | [
"'''uses timeseries xls sheets assuming they are available'''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d6accf244dded64b9cfaf0b6c6e65d876319bb0 | emlynjdavies/PySilCam | pysilcam/silcamgui/interactive_summary.py | [
"BSD-3-Clause"
] | Python | load_from_stats | null | def load_from_stats(self):
'''loads stats data and converts to timeseries without saving'''
stats = pd.read_csv(self.stats_filename, parse_dates=['timestamp'])
u = stats['timestamp'].unique()
u = pd.to_datetime(u)
sample_volume = scpp.get_sample_volume(self.settings.PostProcess.... | loads stats data and converts to timeseries without saving | loads stats data and converts to timeseries without saving | [
"loads",
"stats",
"data",
"and",
"converts",
"to",
"timeseries",
"without",
"saving"
] | def load_from_stats(self):
stats = pd.read_csv(self.stats_filename, parse_dates=['timestamp'])
u = stats['timestamp'].unique()
u = pd.to_datetime(u)
sample_volume = scpp.get_sample_volume(self.settings.PostProcess.pix_size,
path_length=self.... | [
"def",
"load_from_stats",
"(",
"self",
")",
":",
"stats",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"stats_filename",
",",
"parse_dates",
"=",
"[",
"'timestamp'",
"]",
")",
"u",
"=",
"stats",
"[",
"'timestamp'",
"]",
".",
"unique",
"(",
")",
"u",
... | loads stats data and converts to timeseries without saving | [
"loads",
"stats",
"data",
"and",
"converts",
"to",
"timeseries",
"without",
"saving"
] | [
"'''loads stats data and converts to timeseries without saving'''",
"# @todo make this number of particles per image, and sum according to index later"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d6accf244dded64b9cfaf0b6c6e65d876319bb0 | emlynjdavies/PySilCam | pysilcam/silcamgui/interactive_summary.py | [
"BSD-3-Clause"
] | Python | on_click | null | def on_click(self, event):
'''if you click the correct place, update the plot based on where you click'''
if event.inaxes is not None:
try:
self.mid_time = pd.to_datetime(matplotlib.dates.num2date(event.xdata)).tz_convert(None)
self.update_plot()
e... | if you click the correct place, update the plot based on where you click | if you click the correct place, update the plot based on where you click | [
"if",
"you",
"click",
"the",
"correct",
"place",
"update",
"the",
"plot",
"based",
"on",
"where",
"you",
"click"
] | def on_click(self, event):
if event.inaxes is not None:
try:
self.mid_time = pd.to_datetime(matplotlib.dates.num2date(event.xdata)).tz_convert(None)
self.update_plot()
except:
pass
else:
pass | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"inaxes",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"mid_time",
"=",
"pd",
".",
"to_datetime",
"(",
"matplotlib",
".",
"dates",
".",
"num2date",
"(",
"event",
".",
... | if you click the correct place, update the plot based on where you click | [
"if",
"you",
"click",
"the",
"correct",
"place",
"update",
"the",
"plot",
"based",
"on",
"where",
"you",
"click"
] | [
"'''if you click the correct place, update the plot based on where you click'''"
] | [
{
"param": "self",
"type": null
},
{
"param": "event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "event",
"type": null,
"docstring": null,
"docstring_tokens": ... |
33bec52846fb4a6ba5320383914e3f390e150b09 | emlynjdavies/PySilCam | pysilcam/config.py | [
"BSD-3-Clause"
] | Python | load_config | <not_specific> | def load_config(filename):
'''Load config file and validate content
Args:
filename (str) : filename including path
Raises:
RuntimeError : when file could not be read
Returns:
ConfigParser : with the file parsed
'''
#Check that the file exists
if not os.path.exists(... | Load config file and validate content
Args:
filename (str) : filename including path
Raises:
RuntimeError : when file could not be read
Returns:
ConfigParser : with the file parsed
| Load config file and validate content | [
"Load",
"config",
"file",
"and",
"validate",
"content"
] | def load_config(filename):
if not os.path.exists(filename):
raise RuntimeError('Config file not found: {0}'.format(filename))
conf = configparser.ConfigParser()
files_parsed = conf.read(filename)
if filename not in files_parsed:
raise RuntimeError('Could not parse config file {0}'.format... | [
"def",
"load_config",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"RuntimeError",
"(",
"'Config file not found: {0}'",
".",
"format",
"(",
"filename",
")",
")",
"conf",
"=",
"configparser",
... | Load config file and validate content | [
"Load",
"config",
"file",
"and",
"validate",
"content"
] | [
"'''Load config file and validate content\n \n Args:\n filename (str) : filename including path\n\n Raises:\n RuntimeError : when file could not be read\n\n Returns:\n ConfigParser : with the file parsed\n\n '''",
"#Check that the file exists",
"##Create ConfigParser and populate ... | [
{
"param": "filename",
"type": null
}
] | {
"returns": [
{
"docstring": "ConfigParser : with the file parsed",
"docstring_tokens": [
"ConfigParser",
":",
"with",
"the",
"file",
"parsed"
],
"type": null
}
],
"raises": [
{
"docstring": "when file could not be read",
... |
33bec52846fb4a6ba5320383914e3f390e150b09 | emlynjdavies/PySilCam | pysilcam/config.py | [
"BSD-3-Clause"
] | Python | default_config_path | <not_specific> | def default_config_path():
'''return the path to the default config file
Returns:
path_to_config (str) : path to the default config file
'''
path = os.path.dirname(__file__)
path_to_config = os.path.join(path, 'config_example.ini')
return path_to_config | return the path to the default config file
Returns:
path_to_config (str) : path to the default config file
| return the path to the default config file | [
"return",
"the",
"path",
"to",
"the",
"default",
"config",
"file"
] | def default_config_path():
path = os.path.dirname(__file__)
path_to_config = os.path.join(path, 'config_example.ini')
return path_to_config | [
"def",
"default_config_path",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"path_to_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'config_example.ini'",
")",
"return",
"path_to_config"
] | return the path to the default config file | [
"return",
"the",
"path",
"to",
"the",
"default",
"config",
"file"
] | [
"'''return the path to the default config file\n\n Returns:\n path_to_config (str) : path to the default config file\n '''"
] | [] | {
"returns": [
{
"docstring": "path_to_config (str) : path to the default config file",
"docstring_tokens": [
"path_to_config",
"(",
"str",
")",
":",
"path",
"to",
"the",
"default",
"config",
"file"
],
... |
33bec52846fb4a6ba5320383914e3f390e150b09 | emlynjdavies/PySilCam | pysilcam/config.py | [
"BSD-3-Clause"
] | Python | load_camera_config | <not_specific> | def load_camera_config(filename, config=None):
'''Load camera config file and validate content
Args:
filename (str) : filename including path to camera config file
config=None (dict) : a dictionnary to store key-values. If config does not exist, an empty dict is created
Returns:
... | Load camera config file and validate content
Args:
filename (str) : filename including path to camera config file
config=None (dict) : a dictionnary to store key-values. If config does not exist, an empty dict is created
Returns:
dict() : with key value pairs of camera... | Load camera config file and validate content | [
"Load",
"camera",
"config",
"file",
"and",
"validate",
"content"
] | def load_camera_config(filename, config=None):
if (config == None):
config = dict()
if (filename == None):
return config
filename = os.path.normpath(filename)
if not os.path.exists(filename):
logger.info('Camera config file not found: {0}'.format(filename))
logger.debug('Came... | [
"def",
"load_camera_config",
"(",
"filename",
",",
"config",
"=",
"None",
")",
":",
"if",
"(",
"config",
"==",
"None",
")",
":",
"config",
"=",
"dict",
"(",
")",
"if",
"(",
"filename",
"==",
"None",
")",
":",
"return",
"config",
"filename",
"=",
"os"... | Load camera config file and validate content | [
"Load",
"camera",
"config",
"file",
"and",
"validate",
"content"
] | [
"'''Load camera config file and validate content\n \n Args:\n filename (str) : filename including path to camera config file\n config=None (dict) : a dictionnary to store key-values. If config does not exist, an empty dict is created\n\n Returns:\n dict() : with key value ... | [
{
"param": "filename",
"type": null
},
{
"param": "config",
"type": null
}
] | {
"returns": [
{
"docstring": "dict() : with key value pairs of camera settings",
"docstring_tokens": [
"dict",
"()",
":",
"with",
"key",
"value",
"pairs",
"of",
"camera",
"settings"
],
"type": nul... |
33bec52846fb4a6ba5320383914e3f390e150b09 | emlynjdavies/PySilCam | pysilcam/config.py | [
"BSD-3-Clause"
] | Python | updatePathLength | null | def updatePathLength(settings, logger):
'''Adjusts the path length of systems with the actuator installed and RS232
connected.
Args:
settings (PySilcamSettings): Settings read from a .ini file
settings.logfile is optional
set... | Adjusts the path length of systems with the actuator installed and RS232
connected.
Args:
settings (PySilcamSettings): Settings read from a .ini file
settings.logfile is optional
settings.loglevel mest exist
logger (logge... | Adjusts the path length of systems with the actuator installed and RS232
connected. | [
"Adjusts",
"the",
"path",
"length",
"of",
"systems",
"with",
"the",
"actuator",
"installed",
"and",
"RS232",
"connected",
"."
] | def updatePathLength(settings, logger):
try:
logger.info('Updating path length')
pl = scog.PathLength(settings.PostProcess.com_port)
pl.gap_to_mm(settings.PostProcess.path_length)
pl.finish()
except:
logger.warning('Could not open port. Path length will not be adjusted.') | [
"def",
"updatePathLength",
"(",
"settings",
",",
"logger",
")",
":",
"try",
":",
"logger",
".",
"info",
"(",
"'Updating path length'",
")",
"pl",
"=",
"scog",
".",
"PathLength",
"(",
"settings",
".",
"PostProcess",
".",
"com_port",
")",
"pl",
".",
"gap_to_... | Adjusts the path length of systems with the actuator installed and RS232
connected. | [
"Adjusts",
"the",
"path",
"length",
"of",
"systems",
"with",
"the",
"actuator",
"installed",
"and",
"RS232",
"connected",
"."
] | [
"'''Adjusts the path length of systems with the actuator installed and RS232\n connected.\n\n Args:\n settings (PySilcamSettings): Settings read from a .ini file\n settings.logfile is optional\n settings.loglevel mest exist\n ... | [
{
"param": "settings",
"type": null
},
{
"param": "logger",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "settings",
"type": null,
"docstring": "Settings read from a .ini file\nsettings.logfile is optional\nsettings.loglevel mest exist",
"docstring_tokens": [
"Settings",
"read",
"from",
"a",
... |
c6aaac3bb916a1d2f6fff2e3d6a290e8491718d2 | emlynjdavies/PySilCam | pysilcam/process.py | [
"BSD-3-Clause"
] | Python | extract_roi | <not_specific> | def extract_roi(im, bbox):
''' given an image (im) and bounding box (bbox), this will return the roi
Args:
im : any image, such as background-corrected image (imc)
bbox : bounding box from regionprops [r1, c1, r2, c2]
Returns:
roi : i... | given an image (im) and bounding box (bbox), this will return the roi
Args:
im : any image, such as background-corrected image (imc)
bbox : bounding box from regionprops [r1, c1, r2, c2]
Returns:
roi : image cropped to region of interest... | given an image (im) and bounding box (bbox), this will return the roi | [
"given",
"an",
"image",
"(",
"im",
")",
"and",
"bounding",
"box",
"(",
"bbox",
")",
"this",
"will",
"return",
"the",
"roi"
] | def extract_roi(im, bbox):
roi = im[bbox[0]:bbox[2], bbox[1]:bbox[3]]
return roi | [
"def",
"extract_roi",
"(",
"im",
",",
"bbox",
")",
":",
"roi",
"=",
"im",
"[",
"bbox",
"[",
"0",
"]",
":",
"bbox",
"[",
"2",
"]",
",",
"bbox",
"[",
"1",
"]",
":",
"bbox",
"[",
"3",
"]",
"]",
"return",
"roi"
] | given an image (im) and bounding box (bbox), this will return the roi | [
"given",
"an",
"image",
"(",
"im",
")",
"and",
"bounding",
"box",
"(",
"bbox",
")",
"this",
"will",
"return",
"the",
"roi"
] | [
"''' given an image (im) and bounding box (bbox), this will return the roi\n\n Args:\n im : any image, such as background-corrected image (imc)\n bbox : bounding box from regionprops [r1, c1, r2, c2]\n\n Returns:\n roi : image cropped to reg... | [
{
"param": "im",
"type": null
},
{
"param": "bbox",
"type": null
}
] | {
"returns": [
{
"docstring": "roi : image cropped to region of interest",
"docstring_tokens": [
"roi",
":",
"image",
"cropped",
"to",
"region",
"of",
"interest"
],
"type": null
}
],
"raises": [],
"pa... |
c6aaac3bb916a1d2f6fff2e3d6a290e8491718d2 | emlynjdavies/PySilCam | pysilcam/process.py | [
"BSD-3-Clause"
] | Python | statextract | <not_specific> | def statextract(imc, settings, timestamp, nnmodel, class_labels):
'''extracts statistics of particles in imc (raw corrected image)
Args:
imc : background-corrected image
timestamp : timestamp of image collection
settings : PyS... | extracts statistics of particles in imc (raw corrected image)
Args:
imc : background-corrected image
timestamp : timestamp of image collection
settings : PySilCam settings
nnmodel : loaded tensorflow mo... | extracts statistics of particles in imc (raw corrected image) | [
"extracts",
"statistics",
"of",
"particles",
"in",
"imc",
"(",
"raw",
"corrected",
"image",
")"
] | def statextract(imc, settings, timestamp, nnmodel, class_labels):
logger.debug('segment')
img = np.uint8(np.min(imc, axis=2))
if settings.Process.real_time_stats:
imbw = image2blackwhite_fast(img, settings.Process.threshold)
else:
imbw = image2blackwhite_accurate(img, settings.Process.t... | [
"def",
"statextract",
"(",
"imc",
",",
"settings",
",",
"timestamp",
",",
"nnmodel",
",",
"class_labels",
")",
":",
"logger",
".",
"debug",
"(",
"'segment'",
")",
"img",
"=",
"np",
".",
"uint8",
"(",
"np",
".",
"min",
"(",
"imc",
",",
"axis",
"=",
... | extracts statistics of particles in imc (raw corrected image) | [
"extracts",
"statistics",
"of",
"particles",
"in",
"imc",
"(",
"raw",
"corrected",
"image",
")"
] | [
"'''extracts statistics of particles in imc (raw corrected image)\n\n Args:\n imc : background-corrected image\n timestamp : timestamp of image collection\n settings : PySilCam settings\n nnmodel : loaded... | [
{
"param": "imc",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "timestamp",
"type": null
},
{
"param": "nnmodel",
"type": null
},
{
"param": "class_labels",
"type": null
}
] | {
"returns": [
{
"docstring": "stats : (list of particle statistics for every particle, according to Partstats class)\nimbw : segmented image\nsaturation : percentage saturation of image",
"docstring_tokens": [
"stats",
":",... |
c6aaac3bb916a1d2f6fff2e3d6a290e8491718d2 | emlynjdavies/PySilCam | pysilcam/process.py | [
"BSD-3-Clause"
] | Python | write_segmented_images | null | def write_segmented_images(imbw, imc, settings, timestamp):
'''writes binary images as bmp files to the same place as hdf5 files if loglevel is in DEBUG mode
Useful for checking threshold and segmentation
Args:
imbw : segmented image
settings : PySi... | writes binary images as bmp files to the same place as hdf5 files if loglevel is in DEBUG mode
Useful for checking threshold and segmentation
Args:
imbw : segmented image
settings : PySilCam settings
timestamp : timestamp of im... | writes binary images as bmp files to the same place as hdf5 files if loglevel is in DEBUG mode
Useful for checking threshold and segmentation | [
"writes",
"binary",
"images",
"as",
"bmp",
"files",
"to",
"the",
"same",
"place",
"as",
"hdf5",
"files",
"if",
"loglevel",
"is",
"in",
"DEBUG",
"mode",
"Useful",
"for",
"checking",
"threshold",
"and",
"segmentation"
] | def write_segmented_images(imbw, imc, settings, timestamp):
if (settings.General.loglevel == 'DEBUG') and settings.ExportParticles.export_images:
fname = os.path.join(settings.ExportParticles.outputpath, timestamp.strftime('D%Y%m%dT%H%M%S.%f-SEG.bmp'))
imbw_ = np.uint8(255*imbw)
imsave(fname... | [
"def",
"write_segmented_images",
"(",
"imbw",
",",
"imc",
",",
"settings",
",",
"timestamp",
")",
":",
"if",
"(",
"settings",
".",
"General",
".",
"loglevel",
"==",
"'DEBUG'",
")",
"and",
"settings",
".",
"ExportParticles",
".",
"export_images",
":",
"fname"... | writes binary images as bmp files to the same place as hdf5 files if loglevel is in DEBUG mode
Useful for checking threshold and segmentation | [
"writes",
"binary",
"images",
"as",
"bmp",
"files",
"to",
"the",
"same",
"place",
"as",
"hdf5",
"files",
"if",
"loglevel",
"is",
"in",
"DEBUG",
"mode",
"Useful",
"for",
"checking",
"threshold",
"and",
"segmentation"
] | [
"'''writes binary images as bmp files to the same place as hdf5 files if loglevel is in DEBUG mode\n Useful for checking threshold and segmentation\n\n Args:\n imbw : segmented image\n settings : PySilCam settings\n timestamp : t... | [
{
"param": "imbw",
"type": null
},
{
"param": "imc",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "timestamp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "imbw",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "imc",
"type": null,
"docstring": null,
"docstring_tokens": []... |
c6aaac3bb916a1d2f6fff2e3d6a290e8491718d2 | emlynjdavies/PySilCam | pysilcam/process.py | [
"BSD-3-Clause"
] | Python | extract_particles | <not_specific> | def extract_particles(imc, timestamp, settings, nnmodel, class_labels, region_properties):
'''extracts the particles to build stats and export particle rois to HDF5 files writted to disc in the location of settings.ExportParticles.outputpath
Args:
imc : background-corrected imag... | extracts the particles to build stats and export particle rois to HDF5 files writted to disc in the location of settings.ExportParticles.outputpath
Args:
imc : background-corrected image
timestamp : timestamp of image collection
settings ... | extracts the particles to build stats and export particle rois to HDF5 files writted to disc in the location of settings.ExportParticles.outputpath | [
"extracts",
"the",
"particles",
"to",
"build",
"stats",
"and",
"export",
"particle",
"rois",
"to",
"HDF5",
"files",
"writted",
"to",
"disc",
"in",
"the",
"location",
"of",
"settings",
".",
"ExportParticles",
".",
"outputpath"
] | def extract_particles(imc, timestamp, settings, nnmodel, class_labels, region_properties):
filenames = ['not_exported'] * len(region_properties)
predictions = np.zeros((len(region_properties),
len(class_labels)),
dtype='float64')
predictions *= np.nan
filename = timestamp.strftime('D%Y... | [
"def",
"extract_particles",
"(",
"imc",
",",
"timestamp",
",",
"settings",
",",
"nnmodel",
",",
"class_labels",
",",
"region_properties",
")",
":",
"filenames",
"=",
"[",
"'not_exported'",
"]",
"*",
"len",
"(",
"region_properties",
")",
"predictions",
"=",
"np... | extracts the particles to build stats and export particle rois to HDF5 files writted to disc in the location of settings.ExportParticles.outputpath | [
"extracts",
"the",
"particles",
"to",
"build",
"stats",
"and",
"export",
"particle",
"rois",
"to",
"HDF5",
"files",
"writted",
"to",
"disc",
"in",
"the",
"location",
"of",
"settings",
".",
"ExportParticles",
".",
"outputpath"
] | [
"'''extracts the particles to build stats and export particle rois to HDF5 files writted to disc in the location of settings.ExportParticles.outputpath\n\n Args:\n imc : background-corrected image\n timestamp : timestamp of image collection\n setting... | [
{
"param": "imc",
"type": null
},
{
"param": "timestamp",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "nnmodel",
"type": null
},
{
"param": "class_labels",
"type": null
},
{
"param": "region_properties",
"type": null
}
] | {
"returns": [
{
"docstring": "stats : (list of particle statistics for every particle, according to Partstats class)",
"docstring_tokens": [
"stats",
":",
"(",
"list",
"of",
"particle",
"statistics",
"for",
... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | update | null | def update(self, imc, imbw, times, d50_ts, vd_mean, display):
'''Update plot data without full replotting for speed'''
if display==True:
self.image.set_data(np.uint8(imc))
self.image_bw.set_data(np.uint8(imbw>0))
#Show the last 50 D50 values
self.d50_plot.set_da... | Update plot data without full replotting for speed | Update plot data without full replotting for speed | [
"Update",
"plot",
"data",
"without",
"full",
"replotting",
"for",
"speed"
] | def update(self, imc, imbw, times, d50_ts, vd_mean, display):
if display==True:
self.image.set_data(np.uint8(imc))
self.image_bw.set_data(np.uint8(imbw>0))
self.d50_plot.set_data(range(len(d50_ts[-50:])), d50_ts[-50:])
norm = np.sum(vd_mean['total'].vd_mean)/100
s... | [
"def",
"update",
"(",
"self",
",",
"imc",
",",
"imbw",
",",
"times",
",",
"d50_ts",
",",
"vd_mean",
",",
"display",
")",
":",
"if",
"display",
"==",
"True",
":",
"self",
".",
"image",
".",
"set_data",
"(",
"np",
".",
"uint8",
"(",
"imc",
")",
")"... | Update plot data without full replotting for speed | [
"Update",
"plot",
"data",
"without",
"full",
"replotting",
"for",
"speed"
] | [
"'''Update plot data without full replotting for speed'''",
"#Show the last 50 D50 values",
"# self.line_oil.set_data(vd_mean['oil'].dias, vd_mean['oil'].vd_mean/norm)",
"# self.line_gas.set_data(vd_mean['gas'].dias, vd_mean['gas'].vd_mean/norm)",
"#Fast redraw of dynamic figure elements only"... | [
{
"param": "self",
"type": null
},
{
"param": "imc",
"type": null
},
{
"param": "imbw",
"type": null
},
{
"param": "times",
"type": null
},
{
"param": "d50_ts",
"type": null
},
{
"param": "vd_mean",
"type": null
},
{
"param": "display",
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "imc",
"type": null,
"docstring": null,
"docstring_tokens": []... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | psd | <not_specific> | def psd(stats, settings, ax, line=None, c='k'):
'''
Plot a normalised particle volume distribution
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings
ax () ... |
Plot a normalised particle volume distribution
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings
ax () : axis to plot data on
line=N... | Plot a normalised particle volume distribution | [
"Plot",
"a",
"normalised",
"particle",
"volume",
"distribution"
] | def psd(stats, settings, ax, line=None, c='k'):
dias, vd = sc_pp.vd_from_stats(stats, settings)
if line:
line.set_data(dias, vd/np.sum(vd)*100)
else:
line, = ax.plot(dias,vd/np.sum(vd)*100, color=c)
ax.set_xscale('log')
ax.set_xlabel('Equiv. diam (um)')
ax.set_ylabel(... | [
"def",
"psd",
"(",
"stats",
",",
"settings",
",",
"ax",
",",
"line",
"=",
"None",
",",
"c",
"=",
"'k'",
")",
":",
"dias",
",",
"vd",
"=",
"sc_pp",
".",
"vd_from_stats",
"(",
"stats",
",",
"settings",
")",
"if",
"line",
":",
"line",
".",
"set_data... | Plot a normalised particle volume distribution | [
"Plot",
"a",
"normalised",
"particle",
"volume",
"distribution"
] | [
"'''\n Plot a normalised particle volume distribution\n \n Args:\n stats (DataFrame) : particle statistics from silcam process\n settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings\n ax () : axis to plot data on\... | [
{
"param": "stats",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "ax",
"type": null
},
{
"param": "line",
"type": null
},
{
"param": "c",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "stats",
"type": null,
"docstring": "particle statistics from silcam process",
"docstring_tokens": [
"partic... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | nd_scaled | <not_specific> | def nd_scaled(stats, settings, ax, c='k'):
'''
Plot the particle number distribution, scaled to the total volume of water sampled
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, loaded with PySi... |
Plot the particle number distribution, scaled to the total volume of water sampled
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings
ax () :... | Plot the particle number distribution, scaled to the total volume of water sampled | [
"Plot",
"the",
"particle",
"number",
"distribution",
"scaled",
"to",
"the",
"total",
"volume",
"of",
"water",
"sampled"
] | def nd_scaled(stats, settings, ax, c='k'):
sv = sc_pp.get_sample_volume(settings.pix_size,
path_length=settings.path_length,
imx=2048, imy=2448)
sv_total = sv * sc_pp.count_images_in_stats(stats)
nd(stats, settings, ax, line=None, c='k', sample_volume=sv_total)
return | [
"def",
"nd_scaled",
"(",
"stats",
",",
"settings",
",",
"ax",
",",
"c",
"=",
"'k'",
")",
":",
"sv",
"=",
"sc_pp",
".",
"get_sample_volume",
"(",
"settings",
".",
"pix_size",
",",
"path_length",
"=",
"settings",
".",
"path_length",
",",
"imx",
"=",
"204... | Plot the particle number distribution, scaled to the total volume of water sampled | [
"Plot",
"the",
"particle",
"number",
"distribution",
"scaled",
"to",
"the",
"total",
"volume",
"of",
"water",
"sampled"
] | [
"'''\n Plot the particle number distribution, scaled to the total volume of water sampled\n \n Args:\n stats (DataFrame) : particle statistics from silcam process\n settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings\n ax () ... | [
{
"param": "stats",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "ax",
"type": null
},
{
"param": "c",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stats",
"type": null,
"docstring": "particle statistics from silcam process",
"docstring_tokens": [
"particle",
"statistics",
"from",
"silcam",
"process"
],
"default": null,
... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | nd | <not_specific> | def nd(stats, settings, ax, line=None, c='k', sample_volume=1.):
'''
Plot the particle number distribution, scaled to the given sample volume
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, load... |
Plot the particle number distribution, scaled to the given sample volume
Args:
stats (DataFrame) : particle statistics from silcam process
settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings
ax () : axis to p... | Plot the particle number distribution, scaled to the given sample volume | [
"Plot",
"the",
"particle",
"number",
"distribution",
"scaled",
"to",
"the",
"given",
"sample",
"volume"
] | def nd(stats, settings, ax, line=None, c='k', sample_volume=1.):
dias, nd = sc_pp.nd_from_stats(stats, settings)
nd = sc_pp.nd_rescale(dias, nd, sample_volume)
ind = np.argwhere(nd>0)
nd[ind[0]] = np.nan
ind = np.argwhere(nd == 0)
nd[ind] = np.nan
if line:
line.set_data(dias, nd)
... | [
"def",
"nd",
"(",
"stats",
",",
"settings",
",",
"ax",
",",
"line",
"=",
"None",
",",
"c",
"=",
"'k'",
",",
"sample_volume",
"=",
"1.",
")",
":",
"dias",
",",
"nd",
"=",
"sc_pp",
".",
"nd_from_stats",
"(",
"stats",
",",
"settings",
")",
"nd",
"="... | Plot the particle number distribution, scaled to the given sample volume | [
"Plot",
"the",
"particle",
"number",
"distribution",
"scaled",
"to",
"the",
"given",
"sample",
"volume"
] | [
"'''\n Plot the particle number distribution, scaled to the given sample volume\n \n Args:\n stats (DataFrame) : particle statistics from silcam process\n settings (PySilcamSettings) : settings associated with the data, loaded with PySilcamSettings\n ax () ... | [
{
"param": "stats",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "ax",
"type": null
},
{
"param": "line",
"type": null
},
{
"param": "c",
"type": null
},
{
"param": "sample_volume",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "stats",
"type": null,
"docstring": "particle statistics from silcam process",
"docstring_tokens": [
"partic... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | show_imc | <not_specific> | def show_imc(imc, mag=2):
'''
Plots a scaled figure of for s SilCam image for medium or low magnification systems
Args:
imc (uint8) : SilCam image (usually a corrected image, such as imc)
mag=2 (int) : mag=1 scales to the low mag SilCams; mag=2 (default) scales to the medium max SilCams... |
Plots a scaled figure of for s SilCam image for medium or low magnification systems
Args:
imc (uint8) : SilCam image (usually a corrected image, such as imc)
mag=2 (int) : mag=1 scales to the low mag SilCams; mag=2 (default) scales to the medium max SilCams
| Plots a scaled figure of for s SilCam image for medium or low magnification systems | [
"Plots",
"a",
"scaled",
"figure",
"of",
"for",
"s",
"SilCam",
"image",
"for",
"medium",
"or",
"low",
"magnification",
"systems"
] | def show_imc(imc, mag=2):
PIX_SIZE = 35.2 / 2448 * 1000
r, c = np.shape(imc[:,:,0])
if mag==1:
PIX_SIZE = 67.4 / 2448 * 1000
plt.imshow(np.uint8(imc),
extent=[0,c*PIX_SIZE/1000,0,r*PIX_SIZE/1000],
interpolation='nearest')
plt.xlabel('mm')
plt.ylabel('mm')
retu... | [
"def",
"show_imc",
"(",
"imc",
",",
"mag",
"=",
"2",
")",
":",
"PIX_SIZE",
"=",
"35.2",
"/",
"2448",
"*",
"1000",
"r",
",",
"c",
"=",
"np",
".",
"shape",
"(",
"imc",
"[",
":",
",",
":",
",",
"0",
"]",
")",
"if",
"mag",
"==",
"1",
":",
"PI... | Plots a scaled figure of for s SilCam image for medium or low magnification systems | [
"Plots",
"a",
"scaled",
"figure",
"of",
"for",
"s",
"SilCam",
"image",
"for",
"medium",
"or",
"low",
"magnification",
"systems"
] | [
"'''\n Plots a scaled figure of for s SilCam image for medium or low magnification systems\n \n Args:\n imc (uint8) : SilCam image (usually a corrected image, such as imc)\n mag=2 (int) : mag=1 scales to the low mag SilCams; mag=2 (default) scales to the medium max SilCams\n '''"
] | [
{
"param": "imc",
"type": null
},
{
"param": "mag",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "imc",
"type": null,
"docstring": "SilCam image (usually a corrected image, such as imc)",
"docstring_tokens": [
"SilCam",
"image",
"(",
"usually",
"a",
"corrected",
"imag... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | montage_plot | null | def montage_plot(montage, pixel_size):
'''
Plots a SilCam particle montage with a 1mm scale reference
Args:
montage (uint8) : a SilCam montage created with scpp.make_montage
pixel_size (float) : the pixel size of the SilCam used, obtained from settings.PostProcess.pix_size in the config... |
Plots a SilCam particle montage with a 1mm scale reference
Args:
montage (uint8) : a SilCam montage created with scpp.make_montage
pixel_size (float) : the pixel size of the SilCam used, obtained from settings.PostProcess.pix_size in the config ini file
| Plots a SilCam particle montage with a 1mm scale reference | [
"Plots",
"a",
"SilCam",
"particle",
"montage",
"with",
"a",
"1mm",
"scale",
"reference"
] | def montage_plot(montage, pixel_size):
msize = np.shape(montage[:,0,0])
ex = pixel_size * np.float64(msize)/1000.
ax = plt.gca()
ax.imshow(montage, extent=[0,ex,0,ex])
ax.set_xticks([1, 2],[])
ax.set_xticklabels([' 1mm',''])
ax.set_yticks([], [])
ax.xaxis.set_ticks_position('bottom') | [
"def",
"montage_plot",
"(",
"montage",
",",
"pixel_size",
")",
":",
"msize",
"=",
"np",
".",
"shape",
"(",
"montage",
"[",
":",
",",
"0",
",",
"0",
"]",
")",
"ex",
"=",
"pixel_size",
"*",
"np",
".",
"float64",
"(",
"msize",
")",
"/",
"1000.",
"ax... | Plots a SilCam particle montage with a 1mm scale reference | [
"Plots",
"a",
"SilCam",
"particle",
"montage",
"with",
"a",
"1mm",
"scale",
"reference"
] | [
"'''\n Plots a SilCam particle montage with a 1mm scale reference\n \n Args:\n montage (uint8) : a SilCam montage created with scpp.make_montage\n pixel_size (float) : the pixel size of the SilCam used, obtained from settings.PostProcess.pix_size in the config ini file\n '''"
] | [
{
"param": "montage",
"type": null
},
{
"param": "pixel_size",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "montage",
"type": null,
"docstring": "a SilCam montage created with scpp.make_montage",
"docstring_tokens": [
"a",
"SilCam",
"montage",
"created",
"with",
"scpp",
".",
... |
1ee636fe2c898eedbb753365e6595078c3bc8834 | emlynjdavies/PySilCam | pysilcam/plotting.py | [
"BSD-3-Clause"
] | Python | summarise_fancy_stats | null | def summarise_fancy_stats(stats_csv_file, config_file, monitor=False,
maxlength=100000, msize=2048, oilgas=sc_pp.outputPartType.all):
'''
Plots a summary figure of a dataset which shows
the volume distribution, number distribution and a montage of randomly selected particles
Args:
s... |
Plots a summary figure of a dataset which shows
the volume distribution, number distribution and a montage of randomly selected particles
Args:
stats_csv_file (str) : path of the *-STATS.csv file created by silcam process
config_file (str) : path of the config ... | Plots a summary figure of a dataset which shows
the volume distribution, number distribution and a montage of randomly selected particles | [
"Plots",
"a",
"summary",
"figure",
"of",
"a",
"dataset",
"which",
"shows",
"the",
"volume",
"distribution",
"number",
"distribution",
"and",
"a",
"montage",
"of",
"randomly",
"selected",
"particles"
] | def summarise_fancy_stats(stats_csv_file, config_file, monitor=False,
maxlength=100000, msize=2048, oilgas=sc_pp.outputPartType.all):
sns.set_style('ticks')
settings = PySilcamSettings(config_file)
min_length = settings.ExportParticles.min_length + 1
ax1 = plt.subplot2grid((2,2),(0, 0))
ax2 ... | [
"def",
"summarise_fancy_stats",
"(",
"stats_csv_file",
",",
"config_file",
",",
"monitor",
"=",
"False",
",",
"maxlength",
"=",
"100000",
",",
"msize",
"=",
"2048",
",",
"oilgas",
"=",
"sc_pp",
".",
"outputPartType",
".",
"all",
")",
":",
"sns",
".",
"set_... | Plots a summary figure of a dataset which shows
the volume distribution, number distribution and a montage of randomly selected particles | [
"Plots",
"a",
"summary",
"figure",
"of",
"a",
"dataset",
"which",
"shows",
"the",
"volume",
"distribution",
"number",
"distribution",
"and",
"a",
"montage",
"of",
"randomly",
"selected",
"particles"
] | [
"'''\n Plots a summary figure of a dataset which shows\n the volume distribution, number distribution and a montage of randomly selected particles\n \n Args:\n stats_csv_file (str) : path of the *-STATS.csv file created by silcam process\n config_file (str) : path ... | [
{
"param": "stats_csv_file",
"type": null
},
{
"param": "config_file",
"type": null
},
{
"param": "monitor",
"type": null
},
{
"param": "maxlength",
"type": null
},
{
"param": "msize",
"type": null
},
{
"param": "oilgas",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stats_csv_file",
"type": null,
"docstring": "path of the *-STATS.csv file created by silcam process",
"docstring_tokens": [
"path",
"of",
"the",
"*",
"-",
"STATS",
".",
... |
9709ba024e0d967107a430c08a213fd7c4f0f738 | emlynjdavies/PySilCam | pysilcam/acquisition.py | [
"BSD-3-Clause"
] | Python | _init_camera | <not_specific> | def _init_camera(vimba):
'''Initialize the camera system from vimba object
Args:
vimba (vimba object) : for example pymba.Vimba()
Returns:
camera (Camera) : The camera without settings from the config
'''
# get system object
system = vimba.getSystem()
# lis... | Initialize the camera system from vimba object
Args:
vimba (vimba object) : for example pymba.Vimba()
Returns:
camera (Camera) : The camera without settings from the config
| Initialize the camera system from vimba object | [
"Initialize",
"the",
"camera",
"system",
"from",
"vimba",
"object"
] | def _init_camera(vimba):
system = vimba.getSystem()
if system.GeVTLIsPresent:
system.runFeatureCommand("GeVDiscoveryAllOnce")
time.sleep(0.2)
cameraIds = vimba.getCameraIds()
for cameraId in cameraIds:
logger.debug('Camera ID: {0}'.format(cameraId))
if len(cameraIds) == 0:
... | [
"def",
"_init_camera",
"(",
"vimba",
")",
":",
"system",
"=",
"vimba",
".",
"getSystem",
"(",
")",
"if",
"system",
".",
"GeVTLIsPresent",
":",
"system",
".",
"runFeatureCommand",
"(",
"\"GeVDiscoveryAllOnce\"",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"... | Initialize the camera system from vimba object | [
"Initialize",
"the",
"camera",
"system",
"from",
"vimba",
"object"
] | [
"'''Initialize the camera system from vimba object\n Args:\n vimba (vimba object) : for example pymba.Vimba()\n \n Returns:\n camera (Camera) : The camera without settings from the config\n '''",
"# get system object",
"# list available cameras (after enabling discovery for... | [
{
"param": "vimba",
"type": null
}
] | {
"returns": [
{
"docstring": "camera (Camera) : The camera without settings from the config",
"docstring_tokens": [
"camera",
"(",
"Camera",
")",
":",
"The",
"camera",
"without",
"settings",
"from",
"the",
... |
9709ba024e0d967107a430c08a213fd7c4f0f738 | emlynjdavies/PySilCam | pysilcam/acquisition.py | [
"BSD-3-Clause"
] | Python | wait_for_camera | null | def wait_for_camera(self):
'''
Waiting function that will continue forever until a camera becomes connected
'''
camera = None
while not camera:
with self.pymba.Vimba() as vimba:
try:
camera = _init_camera(vimba)
exce... |
Waiting function that will continue forever until a camera becomes connected
| Waiting function that will continue forever until a camera becomes connected | [
"Waiting",
"function",
"that",
"will",
"continue",
"forever",
"until",
"a",
"camera",
"becomes",
"connected"
] | def wait_for_camera(self):
camera = None
while not camera:
with self.pymba.Vimba() as vimba:
try:
camera = _init_camera(vimba)
except RuntimeError:
msg = 'Could not connect to camera, sleeping five seconds and then retry... | [
"def",
"wait_for_camera",
"(",
"self",
")",
":",
"camera",
"=",
"None",
"while",
"not",
"camera",
":",
"with",
"self",
".",
"pymba",
".",
"Vimba",
"(",
")",
"as",
"vimba",
":",
"try",
":",
"camera",
"=",
"_init_camera",
"(",
"vimba",
")",
"except",
"... | Waiting function that will continue forever until a camera becomes connected | [
"Waiting",
"function",
"that",
"will",
"continue",
"forever",
"until",
"a",
"camera",
"becomes",
"connected"
] | [
"'''\n Waiting function that will continue forever until a camera becomes connected\n '''",
"# TODO: WHy is there a print here? warning should write to sys.stderr anyway"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
432f91ce7a08ecc369fd0f87a8cfb38c9b59c729 | emlynjdavies/PySilCam | pysilcam/tests/synthesizer.py | [
"BSD-3-Clause"
] | Python | synthesize | <not_specific> | def synthesize(diams, bin_limits_um, nd, imx, imy, PIX_SIZE):
'''synthesize an image and measure droplets
Args:
diams (array) : size bins of the number distribution
bin_limits_um (array) : limits of the size bins where dias are the mid-points
nd ... | synthesize an image and measure droplets
Args:
diams (array) : size bins of the number distribution
bin_limits_um (array) : limits of the size bins where dias are the mid-points
nd (array) : number of particles per size bin
... | synthesize an image and measure droplets | [
"synthesize",
"an",
"image",
"and",
"measure",
"droplets"
] | def synthesize(diams, bin_limits_um, nd, imx, imy, PIX_SIZE):
nc = int(sum(nd))
img = np.zeros((imy, imx, 3), dtype=np.uint8()) + 230
log_ecd = np.zeros(nc)
rad = np.random.choice(diams / 2, size=nc, p=nd / sum(nd)) / PIX_SIZE
log_ecd = rad * 2 * PIX_SIZE
for rad_ in rad:
col = np.... | [
"def",
"synthesize",
"(",
"diams",
",",
"bin_limits_um",
",",
"nd",
",",
"imx",
",",
"imy",
",",
"PIX_SIZE",
")",
":",
"nc",
"=",
"int",
"(",
"sum",
"(",
"nd",
")",
")",
"img",
"=",
"np",
".",
"zeros",
"(",
"(",
"imy",
",",
"imx",
",",
"3",
"... | synthesize an image and measure droplets | [
"synthesize",
"an",
"image",
"and",
"measure",
"droplets"
] | [
"'''synthesize an image and measure droplets\n\n Args:\n diams (array) : size bins of the number distribution\n bin_limits_um (array) : limits of the size bins where dias are the mid-points\n nd (array) : number of particles per... | [
{
"param": "diams",
"type": null
},
{
"param": "bin_limits_um",
"type": null
},
{
"param": "nd",
"type": null
},
{
"param": "imx",
"type": null
},
{
"param": "imy",
"type": null
},
{
"param": "PIX_SIZE",
"type": null
}
] | {
"returns": [
{
"docstring": "img (unit8) : segmented image from pysilcam\nlog_vd (array) : a volume distribution of the randomly selected particles put into the synthetic image",
"docstring_tokens": [
"img",
"(",
"unit8",
"... |
466ea5cf3282f61916ee8295a43855c1a67b572d | emlynjdavies/PySilCam | pysilcam/oilgas.py | [
"BSD-3-Clause"
] | Python | run | null | def run(self):
'''
Start the server on port 8000
'''
PORT = 8000
#address = '192.168.1.2'
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer((self.ip, PORT), Handler) as httpd:
logger.info("serving at port: {0}".format(PORT))
... |
Start the server on port 8000
| Start the server on port 8000 | [
"Start",
"the",
"server",
"on",
"port",
"8000"
] | def run(self):
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer((self.ip, PORT), Handler) as httpd:
logger.info("serving at port: {0}".format(PORT))
httpd.serve_forever() | [
"def",
"run",
"(",
"self",
")",
":",
"PORT",
"=",
"8000",
"Handler",
"=",
"http",
".",
"server",
".",
"SimpleHTTPRequestHandler",
"with",
"socketserver",
".",
"TCPServer",
"(",
"(",
"self",
".",
"ip",
",",
"PORT",
")",
",",
"Handler",
")",
"as",
"httpd... | Start the server on port 8000 | [
"Start",
"the",
"server",
"on",
"port",
"8000"
] | [
"'''\n Start the server on port 8000\n '''",
"#address = '192.168.1.2'"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
466ea5cf3282f61916ee8295a43855c1a67b572d | emlynjdavies/PySilCam | pysilcam/oilgas.py | [
"BSD-3-Clause"
] | Python | cat_data_pj | <not_specific> | def cat_data_pj(timestamp, vd, d50, nparts):
'''
cat data into PJ-readable format (readable by the old matlab SummaryPlot exe)
'''
timestamp = pd.to_datetime(timestamp)
data = [[timestamp.year, timestamp.month, timestamp.day,
timestamp.hour, timestamp.minute, timestamp.second + timestam... |
cat data into PJ-readable format (readable by the old matlab SummaryPlot exe)
| cat data into PJ-readable format (readable by the old matlab SummaryPlot exe) | [
"cat",
"data",
"into",
"PJ",
"-",
"readable",
"format",
"(",
"readable",
"by",
"the",
"old",
"matlab",
"SummaryPlot",
"exe",
")"
] | def cat_data_pj(timestamp, vd, d50, nparts):
timestamp = pd.to_datetime(timestamp)
data = [[timestamp.year, timestamp.month, timestamp.day,
timestamp.hour, timestamp.minute, timestamp.second + timestamp.microsecond /
1e6],
vd, [d50, nparts]]
data = list(itertools.chain.fr... | [
"def",
"cat_data_pj",
"(",
"timestamp",
",",
"vd",
",",
"d50",
",",
"nparts",
")",
":",
"timestamp",
"=",
"pd",
".",
"to_datetime",
"(",
"timestamp",
")",
"data",
"=",
"[",
"[",
"timestamp",
".",
"year",
",",
"timestamp",
".",
"month",
",",
"timestamp"... | cat data into PJ-readable format (readable by the old matlab SummaryPlot exe) | [
"cat",
"data",
"into",
"PJ",
"-",
"readable",
"format",
"(",
"readable",
"by",
"the",
"old",
"matlab",
"SummaryPlot",
"exe",
")"
] | [
"'''\n cat data into PJ-readable format (readable by the old matlab SummaryPlot exe)\n '''"
] | [
{
"param": "timestamp",
"type": null
},
{
"param": "vd",
"type": null
},
{
"param": "d50",
"type": null
},
{
"param": "nparts",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "timestamp",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vd",
"type": null,
"docstring": null,
"docstring_tokens"... |
466ea5cf3282f61916ee8295a43855c1a67b572d | emlynjdavies/PySilCam | pysilcam/oilgas.py | [
"BSD-3-Clause"
] | Python | convert_to_pj_format | null | def convert_to_pj_format(stats_csv_file, config_file):
'''converts stats files into a total, and gas-only time-series csvfile which can be read by the old matlab
SummaryPlot exe'''
settings = PySilcamSettings(config_file)
logger.info('Loading stats....')
stats = pd.read_csv(stats_csv_file)
bas... | converts stats files into a total, and gas-only time-series csvfile which can be read by the old matlab
SummaryPlot exe | converts stats files into a total, and gas-only time-series csvfile which can be read by the old matlab
SummaryPlot exe | [
"converts",
"stats",
"files",
"into",
"a",
"total",
"and",
"gas",
"-",
"only",
"time",
"-",
"series",
"csvfile",
"which",
"can",
"be",
"read",
"by",
"the",
"old",
"matlab",
"SummaryPlot",
"exe"
] | def convert_to_pj_format(stats_csv_file, config_file):
settings = PySilcamSettings(config_file)
logger.info('Loading stats....')
stats = pd.read_csv(stats_csv_file)
base_name = stats_csv_file.replace('-STATS.csv', '-PJ.csv')
gas_name = base_name.replace('-PJ.csv', '-PJ-GAS.csv')
ogdatafile = Dat... | [
"def",
"convert_to_pj_format",
"(",
"stats_csv_file",
",",
"config_file",
")",
":",
"settings",
"=",
"PySilcamSettings",
"(",
"config_file",
")",
"logger",
".",
"info",
"(",
"'Loading stats....'",
")",
"stats",
"=",
"pd",
".",
"read_csv",
"(",
"stats_csv_file",
... | converts stats files into a total, and gas-only time-series csvfile which can be read by the old matlab
SummaryPlot exe | [
"converts",
"stats",
"files",
"into",
"a",
"total",
"and",
"gas",
"-",
"only",
"time",
"-",
"series",
"csvfile",
"which",
"can",
"be",
"read",
"by",
"the",
"old",
"matlab",
"SummaryPlot",
"exe"
] | [
"'''converts stats files into a total, and gas-only time-series csvfile which can be read by the old matlab\n SummaryPlot exe'''"
] | [
{
"param": "stats_csv_file",
"type": null
},
{
"param": "config_file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stats_csv_file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "config_file",
"type": null,
"docstring": null,
"doc... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | montage_maker | <not_specific> | def montage_maker(roifiles, roidir, pixel_size, msize=2048, brightness=255,
tightpack=False, eyecandy=True):
'''
makes nice looking matages from a directory of extracted particle images
use make_montage to call this function
Args:
roifiles : list of roi files obtained fr... |
makes nice looking matages from a directory of extracted particle images
use make_montage to call this function
Args:
roifiles : list of roi files obtained from gen_roifiles(stats, auto_scaler=auto_scaler)
roidir : location of roifiles usually defined by se... | makes nice looking matages from a directory of extracted particle images
use make_montage to call this function | [
"makes",
"nice",
"looking",
"matages",
"from",
"a",
"directory",
"of",
"extracted",
"particle",
"images",
"use",
"make_montage",
"to",
"call",
"this",
"function"
] | def montage_maker(roifiles, roidir, pixel_size, msize=2048, brightness=255,
tightpack=False, eyecandy=True):
if tightpack:
import pysilcam.process as scpr
montage = np.zeros((msize,msize,3),dtype=np.uint8())
immap_test = np.zeros_like(montage[:,:,0])
logger.info('making a montage - this ... | [
"def",
"montage_maker",
"(",
"roifiles",
",",
"roidir",
",",
"pixel_size",
",",
"msize",
"=",
"2048",
",",
"brightness",
"=",
"255",
",",
"tightpack",
"=",
"False",
",",
"eyecandy",
"=",
"True",
")",
":",
"if",
"tightpack",
":",
"import",
"pysilcam",
"."... | makes nice looking matages from a directory of extracted particle images
use make_montage to call this function | [
"makes",
"nice",
"looking",
"matages",
"from",
"a",
"directory",
"of",
"extracted",
"particle",
"images",
"use",
"make_montage",
"to",
"call",
"this",
"function"
] | [
"'''\n makes nice looking matages from a directory of extracted particle images\n\n use make_montage to call this function\n\n Args:\n roifiles : list of roi files obtained from gen_roifiles(stats, auto_scaler=auto_scaler)\n roidir : location of roifiles usuall... | [
{
"param": "roifiles",
"type": null
},
{
"param": "roidir",
"type": null
},
{
"param": "pixel_size",
"type": null
},
{
"param": "msize",
"type": null
},
{
"param": "brightness",
"type": null
},
{
"param": "tightpack",
"type": null
},
{
"par... | {
"returns": [
{
"docstring": "montageplot : a nicely-made montage in the form of an image, which can be plotted using plotting.montage_plot(montage, settings.PostProcess.pix_size)",
"docstring_tokens": [
"montageplot",
":",
"a",
"nicely",
"-",
... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | gen_roifiles | <not_specific> | def gen_roifiles(stats, auto_scaler=500):
''' generates a list of filenames suitable for making montages with
Args:
stats (DataFrame) : particle statistics from silcam process
auto_scaler=500 : approximate number of particle that are attempted to be pack into montage
... | generates a list of filenames suitable for making montages with
Args:
stats (DataFrame) : particle statistics from silcam process
auto_scaler=500 : approximate number of particle that are attempted to be pack into montage
Returns:
roifiles : a ... | generates a list of filenames suitable for making montages with | [
"generates",
"a",
"list",
"of",
"filenames",
"suitable",
"for",
"making",
"montages",
"with"
] | def gen_roifiles(stats, auto_scaler=500):
roifiles = stats['export name'][stats['export name'] !=
'not_exported'].values
logger.info('rofiles: {0}'.format(len(roifiles)))
IMSTEP = np.max([np.int(np.round(len(roifiles)/auto_scaler)),1])
logger.info('reducing particles by factor of {0}'.format... | [
"def",
"gen_roifiles",
"(",
"stats",
",",
"auto_scaler",
"=",
"500",
")",
":",
"roifiles",
"=",
"stats",
"[",
"'export name'",
"]",
"[",
"stats",
"[",
"'export name'",
"]",
"!=",
"'not_exported'",
"]",
".",
"values",
"logger",
".",
"info",
"(",
"'rofiles: ... | generates a list of filenames suitable for making montages with | [
"generates",
"a",
"list",
"of",
"filenames",
"suitable",
"for",
"making",
"montages",
"with"
] | [
"''' generates a list of filenames suitable for making montages with\n\n Args:\n stats (DataFrame) : particle statistics from silcam process\n auto_scaler=500 : approximate number of particle that are attempted to be pack into montage\n\n Returns:\n roifiles ... | [
{
"param": "stats",
"type": null
},
{
"param": "auto_scaler",
"type": null
}
] | {
"returns": [
{
"docstring": "roifiles : a selection of filenames that can be passed to montage_maker() for making nice montages",
"docstring_tokens": [
"roifiles",
":",
"a",
"selection",
"of",
"filenames",
"that",
"ca... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | silc_to_bmp | null | def silc_to_bmp(directory):
'''Convert a directory of silc files to bmp images
Args:
directory : path of directory to convert
'''
files = [s for s in os.listdir(directory) if s.endswith('.silc')]
for f in files:
try:
with open(os.path.join(directory, ... | Convert a directory of silc files to bmp images
Args:
directory : path of directory to convert
| Convert a directory of silc files to bmp images | [
"Convert",
"a",
"directory",
"of",
"silc",
"files",
"to",
"bmp",
"images"
] | def silc_to_bmp(directory):
files = [s for s in os.listdir(directory) if s.endswith('.silc')]
for f in files:
try:
with open(os.path.join(directory, f), 'rb') as fh:
im = np.load(fh, allow_pickle=False)
fout = os.path.splitext(f)[0] + '.bmp'
outnam... | [
"def",
"silc_to_bmp",
"(",
"directory",
")",
":",
"files",
"=",
"[",
"s",
"for",
"s",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"s",
".",
"endswith",
"(",
"'.silc'",
")",
"]",
"for",
"f",
"in",
"files",
":",
"try",
":",
"with",
"op... | Convert a directory of silc files to bmp images | [
"Convert",
"a",
"directory",
"of",
"silc",
"files",
"to",
"bmp",
"images"
] | [
"'''Convert a directory of silc files to bmp images\n\n Args:\n directory : path of directory to convert\n\n '''"
] | [
{
"param": "directory",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "directory",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [
{
"identifier": "directory ",
"type": null,
... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | trim_stats | <not_specific> | def trim_stats(stats_csv_file, start_time, end_time, write_new=False, stats=[]):
'''Chops a STATS.csv file given a start and end time
Args:
stats_csv_file : filename of stats file
start_time : start time of interesting window
end_time : e... | Chops a STATS.csv file given a start and end time
Args:
stats_csv_file : filename of stats file
start_time : start time of interesting window
end_time : end time of interesting window
write_new=False : boolean if True will... | Chops a STATS.csv file given a start and end time | [
"Chops",
"a",
"STATS",
".",
"csv",
"file",
"given",
"a",
"start",
"and",
"end",
"time"
] | def trim_stats(stats_csv_file, start_time, end_time, write_new=False, stats=[]):
if len(stats)==0:
stats = pd.read_csv(stats_csv_file)
start_time = pd.to_datetime(start_time)
end_time = pd.to_datetime(end_time)
trimmed_stats = stats[
(pd.to_datetime(stats['timestamp']) > start_time) & (p... | [
"def",
"trim_stats",
"(",
"stats_csv_file",
",",
"start_time",
",",
"end_time",
",",
"write_new",
"=",
"False",
",",
"stats",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"stats",
")",
"==",
"0",
":",
"stats",
"=",
"pd",
".",
"read_csv",
"(",
"stats_cs... | Chops a STATS.csv file given a start and end time | [
"Chops",
"a",
"STATS",
".",
"csv",
"file",
"given",
"a",
"start",
"and",
"end",
"time"
] | [
"'''Chops a STATS.csv file given a start and end time\n\n Args:\n stats_csv_file : filename of stats file\n start_time : start time of interesting window\n end_time : end time of interesting window\n write_new=False : boolea... | [
{
"param": "stats_csv_file",
"type": null
},
{
"param": "start_time",
"type": null
},
{
"param": "end_time",
"type": null
},
{
"param": "write_new",
"type": null
},
{
"param": "stats",
"type": null
}
] | {
"returns": [
{
"docstring": "trimmed_stats : pandas DataFram of particle statistics\noutname : name of new stats csv file written to disc",
"docstring_tokens": [
"trimmed_stats",
":",
"pandas",
"DataFram",
"of",
"particle",
"s... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | show_h5_meta | null | def show_h5_meta(h5file):
'''
prints metadata from an exported hdf5 file created from silcam process
Args:
h5file : h5 filename from exported data from silcam process
'''
with h5py.File(h5file, 'r') as f:
keys = list(f['Meta'].attrs.keys())
for k in keys:
... |
prints metadata from an exported hdf5 file created from silcam process
Args:
h5file : h5 filename from exported data from silcam process
| prints metadata from an exported hdf5 file created from silcam process | [
"prints",
"metadata",
"from",
"an",
"exported",
"hdf5",
"file",
"created",
"from",
"silcam",
"process"
] | def show_h5_meta(h5file):
with h5py.File(h5file, 'r') as f:
keys = list(f['Meta'].attrs.keys())
for k in keys:
logger.info(k + ':')
logger.info(' ' + f['Meta'].attrs[k]) | [
"def",
"show_h5_meta",
"(",
"h5file",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"h5file",
",",
"'r'",
")",
"as",
"f",
":",
"keys",
"=",
"list",
"(",
"f",
"[",
"'Meta'",
"]",
".",
"attrs",
".",
"keys",
"(",
")",
")",
"for",
"k",
"in",
"keys",
... | prints metadata from an exported hdf5 file created from silcam process | [
"prints",
"metadata",
"from",
"an",
"exported",
"hdf5",
"file",
"created",
"from",
"silcam",
"process"
] | [
"'''\n prints metadata from an exported hdf5 file created from silcam process\n\n Args:\n h5file : h5 filename from exported data from silcam process\n '''"
] | [
{
"param": "h5file",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "h5file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [
{
"identifier": "h5file ",
"type": null,
"d... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | vd_to_nd | <not_specific> | def vd_to_nd(vd, dias):
'''convert volume distribution to number distribution
Args:
vd (array) : particle volume distribution calculated from vd_from_stats()
dias (array) : mid-points in the size classes corresponding the the volume distribution,
... | convert volume distribution to number distribution
Args:
vd (array) : particle volume distribution calculated from vd_from_stats()
dias (array) : mid-points in the size classes corresponding the the volume distribution,
returned from get_size_bins()
... | convert volume distribution to number distribution | [
"convert",
"volume",
"distribution",
"to",
"number",
"distribution"
] | def vd_to_nd(vd, dias):
DropletVolume=((4/3)*np.pi*((dias*1e-6)/2)**3)
nd=vd/(DropletVolume*1e9)
return nd | [
"def",
"vd_to_nd",
"(",
"vd",
",",
"dias",
")",
":",
"DropletVolume",
"=",
"(",
"(",
"4",
"/",
"3",
")",
"*",
"np",
".",
"pi",
"*",
"(",
"(",
"dias",
"*",
"1e-6",
")",
"/",
"2",
")",
"**",
"3",
")",
"nd",
"=",
"vd",
"/",
"(",
"DropletVolume... | convert volume distribution to number distribution | [
"convert",
"volume",
"distribution",
"to",
"number",
"distribution"
] | [
"'''convert volume distribution to number distribution\n\n Args:\n vd (array) : particle volume distribution calculated from vd_from_stats()\n dias (array) : mid-points in the size classes corresponding the the volume distribution,\n returned from get... | [
{
"param": "vd",
"type": null
},
{
"param": "dias",
"type": null
}
] | {
"returns": [
{
"docstring": "nd (array) : number distribution as number per micron per bin (scaling is the same unit as the input vd)",
"docstring_tokens": [
"nd",
"(",
"array",
")",
":",
"number",
"distribution",
"as",
... |
598433c306cd81f497e1a7de42e184aa442e9567 | emlynjdavies/PySilCam | pysilcam/postprocess.py | [
"BSD-3-Clause"
] | Python | vd_to_nc | <not_specific> | def vd_to_nc(vd, dias):
'''calculate number concentration from volume distribution
Args:
vd (array) : particle volume distribution calculated from vd_from_stats()
dias (array) : mid-points in the size classes corresponding the the volume distribution,
... | calculate number concentration from volume distribution
Args:
vd (array) : particle volume distribution calculated from vd_from_stats()
dias (array) : mid-points in the size classes corresponding the the volume distribution,
returned from get_size_bi... | calculate number concentration from volume distribution | [
"calculate",
"number",
"concentration",
"from",
"volume",
"distribution"
] | def vd_to_nc(vd, dias):
nd = vd_to_nd(dias, vd)
if np.ndim(nd)>1:
nc = np.sum(nd, axis=1)
else:
nc = np.sum(nd)
return nc | [
"def",
"vd_to_nc",
"(",
"vd",
",",
"dias",
")",
":",
"nd",
"=",
"vd_to_nd",
"(",
"dias",
",",
"vd",
")",
"if",
"np",
".",
"ndim",
"(",
"nd",
")",
">",
"1",
":",
"nc",
"=",
"np",
".",
"sum",
"(",
"nd",
",",
"axis",
"=",
"1",
")",
"else",
"... | calculate number concentration from volume distribution | [
"calculate",
"number",
"concentration",
"from",
"volume",
"distribution"
] | [
"'''calculate number concentration from volume distribution\n\n Args:\n vd (array) : particle volume distribution calculated from vd_from_stats()\n dias (array) : mid-points in the size classes corresponding the the volume distribution,\n returned fro... | [
{
"param": "vd",
"type": null
},
{
"param": "dias",
"type": null
}
] | {
"returns": [
{
"docstring": "nn (float) : number concentration (scaling is the same unit as the input vd).\nIf vd is a 2d array [time, vd_bins], nc will be the concentration for row",
"docstring_tokens": [
"nn",
"(",
"float",
")",
":",
"numbe... |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | silcam | null | def silcam():
'''Main entry point function to acquire/process images from the SilCam.
Use this function in command line arguments according to the below documentation.
Usage:
silcam acquire <configfile> <datapath>
silcam process <configfile> <datapath> [--nbimages=<number of images>] [--nomult... | Main entry point function to acquire/process images from the SilCam.
Use this function in command line arguments according to the below documentation.
Usage:
silcam acquire <configfile> <datapath>
silcam process <configfile> <datapath> [--nbimages=<number of images>] [--nomultiproc] [--appendstats... | Main entry point function to acquire/process images from the SilCam.
Use this function in command line arguments according to the below documentation.
acquire Acquire images
process Process images
realtime Acquire images from the camera and process them in real time
nbimages= Number of images to proc... | [
"Main",
"entry",
"point",
"function",
"to",
"acquire",
"/",
"process",
"images",
"from",
"the",
"SilCam",
".",
"Use",
"this",
"function",
"in",
"command",
"line",
"arguments",
"according",
"to",
"the",
"below",
"documentation",
".",
"acquire",
"Acquire",
"imag... | def silcam():
print(title)
print('')
args = docopt(silcam.__doc__, version='PySilCam {0}'.format(__version__))
overwriteSTATS = True
if args['<datapath>']:
datapath = os.path.normpath(args['<datapath>'].replace("'", ""))
while datapath[-1] == '"':
datapath = datapath[:-1]... | [
"def",
"silcam",
"(",
")",
":",
"print",
"(",
"title",
")",
"print",
"(",
"''",
")",
"args",
"=",
"docopt",
"(",
"silcam",
".",
"__doc__",
",",
"version",
"=",
"'PySilCam {0}'",
".",
"format",
"(",
"__version__",
")",
")",
"overwriteSTATS",
"=",
"True"... | Main entry point function to acquire/process images from the SilCam. | [
"Main",
"entry",
"point",
"function",
"to",
"acquire",
"/",
"process",
"images",
"from",
"the",
"SilCam",
"."
] | [
"'''Main entry point function to acquire/process images from the SilCam.\n\n Use this function in command line arguments according to the below documentation.\n\n Usage:\n silcam acquire <configfile> <datapath>\n silcam process <configfile> <datapath> [--nbimages=<number of images>] [--nomultiproc] ... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | loop | <not_specific> | def loop(config_filename, inputQueue, outputQueue, gui=None):
'''
Main processing loop, run for each image
Args:
config_filename (str) : path of the config ini file
inputQueue () : queue where the images are added for processing
initilised using... |
Main processing loop, run for each image
Args:
config_filename (str) : path of the config ini file
inputQueue () : queue where the images are added for processing
initilised using defineQueues()
outputQueue () : queue where informa... | Main processing loop, run for each image | [
"Main",
"processing",
"loop",
"run",
"for",
"each",
"image"
] | def loop(config_filename, inputQueue, outputQueue, gui=None):
settings = PySilcamSettings(config_filename)
configure_logger(settings.General)
logger = logging.getLogger(__name__ + '.silcam_process')
import tensorflow as tf
sess = tf.Session()
nnmodel = []
nnmodel, class_labels = sccl.load_mo... | [
"def",
"loop",
"(",
"config_filename",
",",
"inputQueue",
",",
"outputQueue",
",",
"gui",
"=",
"None",
")",
":",
"settings",
"=",
"PySilcamSettings",
"(",
"config_filename",
")",
"configure_logger",
"(",
"settings",
".",
"General",
")",
"logger",
"=",
"logging... | Main processing loop, run for each image | [
"Main",
"processing",
"loop",
"run",
"for",
"each",
"image"
] | [
"'''\n Main processing loop, run for each image\n\n Args:\n config_filename (str) : path of the config ini file\n inputQueue () : queue where the images are added for processing\n initilised using defineQueues()\n outputQueue () : queu... | [
{
"param": "config_filename",
"type": null
},
{
"param": "inputQueue",
"type": null
},
{
"param": "outputQueue",
"type": null
},
{
"param": "gui",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config_filename",
"type": null,
"docstring": "path of the config ini file",
"docstring_tokens": [
"path",
"of",
"the",
"config",
"ini",
"file"
],
"default": null,
... |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | collector | null | def collector(inputQueue, outputQueue, datafilename, proc_list, testInputQueue,
settings, rts=None):
'''
collects all the results and write them into the stats.csv file
Args:
inputQueue () : queue where the images are added for processing
... |
collects all the results and write them into the stats.csv file
Args:
inputQueue () : queue where the images are added for processing
initilised using defineQueues()
outputQueue () : queue where information is retrieved from proc... | collects all the results and write them into the stats.csv file | [
"collects",
"all",
"the",
"results",
"and",
"write",
"them",
"into",
"the",
"stats",
".",
"csv",
"file"
] | def collector(inputQueue, outputQueue, datafilename, proc_list, testInputQueue,
settings, rts=None):
countProcessFinished = 0
while ((outputQueue.qsize() > 0) or (testInputQueue and inputQueue.qsize() > 0)):
task = outputQueue.get()
if (task is None):
countProcessFinish... | [
"def",
"collector",
"(",
"inputQueue",
",",
"outputQueue",
",",
"datafilename",
",",
"proc_list",
",",
"testInputQueue",
",",
"settings",
",",
"rts",
"=",
"None",
")",
":",
"countProcessFinished",
"=",
"0",
"while",
"(",
"(",
"outputQueue",
".",
"qsize",
"("... | collects all the results and write them into the stats.csv file | [
"collects",
"all",
"the",
"results",
"and",
"write",
"them",
"into",
"the",
"stats",
".",
"csv",
"file"
] | [
"'''\n collects all the results and write them into the stats.csv file\n\n Args:\n inputQueue () : queue where the images are added for processing\n initilised using defineQueues()\n outputQueue () : queue where information is retri... | [
{
"param": "inputQueue",
"type": null
},
{
"param": "outputQueue",
"type": null
},
{
"param": "datafilename",
"type": null
},
{
"param": "proc_list",
"type": null
},
{
"param": "testInputQueue",
"type": null
},
{
"param": "settings",
"type": null
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "inputQueue",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outputQueue",
"type": null,
"docstring": null,
"docstri... |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | writeCSV | null | def writeCSV(datafilename, stats_all):
'''
Writes particle stats into the csv ouput file
Args:
datafilename (str): filame prefix for -STATS.csv file that may or may not include a path
stats_all (DataFrame): stats dataframe returned from processImage()
'''
# create or append pa... |
Writes particle stats into the csv ouput file
Args:
datafilename (str): filame prefix for -STATS.csv file that may or may not include a path
stats_all (DataFrame): stats dataframe returned from processImage()
| Writes particle stats into the csv ouput file | [
"Writes",
"particle",
"stats",
"into",
"the",
"csv",
"ouput",
"file"
] | def writeCSV(datafilename, stats_all):
if not os.path.isfile(datafilename + '-STATS.csv'):
stats_all.to_csv(datafilename +
'-STATS.csv', index_label='particle index')
else:
stats_all.to_csv(datafilename + '-STATS.csv',
mode='a', header=False) | [
"def",
"writeCSV",
"(",
"datafilename",
",",
"stats_all",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"datafilename",
"+",
"'-STATS.csv'",
")",
":",
"stats_all",
".",
"to_csv",
"(",
"datafilename",
"+",
"'-STATS.csv'",
",",
"index_label",
... | Writes particle stats into the csv ouput file | [
"Writes",
"particle",
"stats",
"into",
"the",
"csv",
"ouput",
"file"
] | [
"'''\n Writes particle stats into the csv ouput file\n\n Args:\n datafilename (str): filame prefix for -STATS.csv file that may or may not include a path\n stats_all (DataFrame): stats dataframe returned from processImage()\n '''",
"# create or append particle statistics to output file... | [
{
"param": "datafilename",
"type": null
},
{
"param": "stats_all",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "datafilename",
"type": null,
"docstring": "filame prefix for -STATS.csv file that may or may not include a path",
"docstring_tokens": [
"filame",
"prefix",
"for",
"-",
"STATS",
"... |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | check_path | null | def check_path(filename):
'''Check if a path exists, and create it if not
Args:
filename (str): filame that may or may not include a path
'''
file = os.path.normpath(filename)
path = os.path.dirname(file)
if path:
if not os.path.isdir(path):
try:
os.... | Check if a path exists, and create it if not
Args:
filename (str): filame that may or may not include a path
| Check if a path exists, and create it if not | [
"Check",
"if",
"a",
"path",
"exists",
"and",
"create",
"it",
"if",
"not"
] | def check_path(filename):
file = os.path.normpath(filename)
path = os.path.dirname(file)
if path:
if not os.path.isdir(path):
try:
os.makedirs(path)
except:
print('Could not create catalog:', path) | [
"def",
"check_path",
"(",
"filename",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"filename",
")",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
"if",
"path",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdi... | Check if a path exists, and create it if not | [
"Check",
"if",
"a",
"path",
"exists",
"and",
"create",
"it",
"if",
"not"
] | [
"'''Check if a path exists, and create it if not\n\n Args:\n filename (str): filame that may or may not include a path\n '''"
] | [
{
"param": "filename",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": "filame that may or may not include a path",
"docstring_tokens": [
"filame",
"that",
"may",
"or",
"may",
"not",
"include",
"... |
7c07f268a32176e2f3313b313ca5ad358fc3bc2f | emlynjdavies/PySilCam | pysilcam/__main__.py | [
"BSD-3-Clause"
] | Python | adminSTATS | null | def adminSTATS(logger, settings, overwriteSTATS, datafilename, datapath):
'''
Administration of the -STATS.csv file
Args:
logger (logger object) : logger object created using configure_logger()
datafilename (str) : name of the folder containing the -STATS.csv
d... |
Administration of the -STATS.csv file
Args:
logger (logger object) : logger object created using configure_logger()
datafilename (str) : name of the folder containing the -STATS.csv
datapath (str) : name of the path containing the data
| Administration of the -STATS.csv file | [
"Administration",
"of",
"the",
"-",
"STATS",
".",
"csv",
"file"
] | def adminSTATS(logger, settings, overwriteSTATS, datafilename, datapath):
if (os.path.isfile(datafilename + '-STATS.csv')):
if overwriteSTATS:
logger.info('removing: ' + datafilename + '-STATS.csv')
print('Overwriting ' + datafilename + '-STATS.csv')
os.remove(datafilenam... | [
"def",
"adminSTATS",
"(",
"logger",
",",
"settings",
",",
"overwriteSTATS",
",",
"datafilename",
",",
"datapath",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"datafilename",
"+",
"'-STATS.csv'",
")",
")",
":",
"if",
"overwriteSTATS",
":",
... | Administration of the -STATS.csv file | [
"Administration",
"of",
"the",
"-",
"STATS",
".",
"csv",
"file"
] | [
"'''\n Administration of the -STATS.csv file\n\n Args:\n logger (logger object) : logger object created using configure_logger()\n datafilename (str) : name of the folder containing the -STATS.csv\n datapath (str) : name of the path containing the da... | [
{
"param": "logger",
"type": null
},
{
"param": "settings",
"type": null
},
{
"param": "overwriteSTATS",
"type": null
},
{
"param": "datafilename",
"type": null
},
{
"param": "datapath",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "logger",
"type": null,
"docstring": "logger object created using configure_logger()",
"docstring_tokens": [
"logger",
"object",
"created",
"using",
"configure_logger",
"()"
... |
63e8c40a7b4083d6377b2a1439b2a06af759a96f | fztfztfztfzt/to_raf | to_raf.py | [
"Python-2.0",
"OLDAP-2.7"
] | Python | to_raf | null | def to_raf(signal,filename):
"""Convert the signal (already the correct length) to a RAF file."""
signal = np.array(signal,dtype=float)
# Shift and convert the signal
signal = signal - signal.min()
signal = ((signal/signal.max()) * int("3fff", 16)).astype('int16')
# Write the signal as binary.
... | Convert the signal (already the correct length) to a RAF file. | Convert the signal (already the correct length) to a RAF file. | [
"Convert",
"the",
"signal",
"(",
"already",
"the",
"correct",
"length",
")",
"to",
"a",
"RAF",
"file",
"."
] | def to_raf(signal,filename):
signal = np.array(signal,dtype=float)
signal = signal - signal.min()
signal = ((signal/signal.max()) * int("3fff", 16)).astype('int16')
fp = open(filename+".RAF", "wb")
draw(signal)
signal.tofile(fp) | [
"def",
"to_raf",
"(",
"signal",
",",
"filename",
")",
":",
"signal",
"=",
"np",
".",
"array",
"(",
"signal",
",",
"dtype",
"=",
"float",
")",
"signal",
"=",
"signal",
"-",
"signal",
".",
"min",
"(",
")",
"signal",
"=",
"(",
"(",
"signal",
"/",
"s... | Convert the signal (already the correct length) to a RAF file. | [
"Convert",
"the",
"signal",
"(",
"already",
"the",
"correct",
"length",
")",
"to",
"a",
"RAF",
"file",
"."
] | [
"\"\"\"Convert the signal (already the correct length) to a RAF file.\"\"\"",
"# Shift and convert the signal",
"# Write the signal as binary."
] | [
{
"param": "signal",
"type": null
},
{
"param": "filename",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "signal",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_toke... |
3afbe9508dd18bcdfc477d8051ff241ebfa294d1 | TilakD/Image-Classification-Desktop-Application | model_helper.py | [
"MIT"
] | Python | predict | <not_specific> | def predict(image_path, model, gpu_check,topk=5):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
model.eval()
image = Image.open(image_path)
np_array = utility.process_image(image)
tensor = torch.from_numpy(np_array)
if gpu_check:
var_inp... | Predict the class (or classes) of an image using a trained deep learning model.
| Predict the class (or classes) of an image using a trained deep learning model. | [
"Predict",
"the",
"class",
"(",
"or",
"classes",
")",
"of",
"an",
"image",
"using",
"a",
"trained",
"deep",
"learning",
"model",
"."
] | def predict(image_path, model, gpu_check,topk=5):
model.eval()
image = Image.open(image_path)
np_array = utility.process_image(image)
tensor = torch.from_numpy(np_array)
if gpu_check:
var_inputs = Variable(tensor.float().cuda(), volatile=True)
else:
var_inputs = Variable(t... | [
"def",
"predict",
"(",
"image_path",
",",
"model",
",",
"gpu_check",
",",
"topk",
"=",
"5",
")",
":",
"model",
".",
"eval",
"(",
")",
"image",
"=",
"Image",
".",
"open",
"(",
"image_path",
")",
"np_array",
"=",
"utility",
".",
"process_image",
"(",
"... | Predict the class (or classes) of an image using a trained deep learning model. | [
"Predict",
"the",
"class",
"(",
"or",
"classes",
")",
"of",
"an",
"image",
"using",
"a",
"trained",
"deep",
"learning",
"model",
"."
] | [
"''' Predict the class (or classes) of an image using a trained deep learning model.\n '''"
] | [
{
"param": "image_path",
"type": null
},
{
"param": "model",
"type": null
},
{
"param": "gpu_check",
"type": null
},
{
"param": "topk",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "image_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tok... |
ad215c15d56ea62bf94400c7807e711659229aa0 | TilakD/Image-Classification-Desktop-Application | utility.py | [
"MIT"
] | Python | process_image | <not_specific> | def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Resize image
ratio = image.size[1] / image.size[0]
image = image.resize((256, int(ratio * 256)))
half_width = image.size[0] / 2
half_height = image.si... | Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
| Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array | [
"Scales",
"crops",
"and",
"normalizes",
"a",
"PIL",
"image",
"for",
"a",
"PyTorch",
"model",
"returns",
"an",
"Numpy",
"array"
] | def process_image(image):
ratio = image.size[1] / image.size[0]
image = image.resize((256, int(ratio * 256)))
half_width = image.size[0] / 2
half_height = image.size[1] / 2
cropped_image = image.crop(
(
half_width - 112,
half_height - 112,
half_width + 112,
ha... | [
"def",
"process_image",
"(",
"image",
")",
":",
"ratio",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"/",
"image",
".",
"size",
"[",
"0",
"]",
"image",
"=",
"image",
".",
"resize",
"(",
"(",
"256",
",",
"int",
"(",
"ratio",
"*",
"256",
")",
")",
... | Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array | [
"Scales",
"crops",
"and",
"normalizes",
"a",
"PIL",
"image",
"for",
"a",
"PyTorch",
"model",
"returns",
"an",
"Numpy",
"array"
] | [
"''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''",
"# Resize image ",
"# Crop image"
] | [
{
"param": "image",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "image",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
175420f2c1193dbce82dd93599f43bde58e0cd55 | BenjaminSchaaf/PythonRaytracingVsRasterization | common/objects.py | [
"MIT"
] | Python | recalculate_normals | null | def recalculate_normals(self):
"""Recalculates the normals
according to the surface normals
of each connected triangle.
"""
normals = []
for index in xrange(len(self.vertices)):
vertex = self.vertices[index]
norms = self._calculate_normals(index)
... | Recalculates the normals
according to the surface normals
of each connected triangle.
| Recalculates the normals
according to the surface normals
of each connected triangle. | [
"Recalculates",
"the",
"normals",
"according",
"to",
"the",
"surface",
"normals",
"of",
"each",
"connected",
"triangle",
"."
] | def recalculate_normals(self):
normals = []
for index in xrange(len(self.vertices)):
vertex = self.vertices[index]
norms = self._calculate_normals(index)
average = Vector3.zero
for normal in norms:
average += normal
if average.m... | [
"def",
"recalculate_normals",
"(",
"self",
")",
":",
"normals",
"=",
"[",
"]",
"for",
"index",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"vertices",
")",
")",
":",
"vertex",
"=",
"self",
".",
"vertices",
"[",
"index",
"]",
"norms",
"=",
"self",
... | Recalculates the normals
according to the surface normals
of each connected triangle. | [
"Recalculates",
"the",
"normals",
"according",
"to",
"the",
"surface",
"normals",
"of",
"each",
"connected",
"triangle",
"."
] | [
"\"\"\"Recalculates the normals\n according to the surface normals\n of each connected triangle.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | magnitude | null | def magnitude(self, value):
"""Sets the magnitude of the Vector
Direction is maintained
"""
multi = float(value)/self.magnitude
self._value = tuple(val*multi for val in self) | Sets the magnitude of the Vector
Direction is maintained
| Sets the magnitude of the Vector
Direction is maintained | [
"Sets",
"the",
"magnitude",
"of",
"the",
"Vector",
"Direction",
"is",
"maintained"
] | def magnitude(self, value):
multi = float(value)/self.magnitude
self._value = tuple(val*multi for val in self) | [
"def",
"magnitude",
"(",
"self",
",",
"value",
")",
":",
"multi",
"=",
"float",
"(",
"value",
")",
"/",
"self",
".",
"magnitude",
"self",
".",
"_value",
"=",
"tuple",
"(",
"val",
"*",
"multi",
"for",
"val",
"in",
"self",
")"
] | Sets the magnitude of the Vector
Direction is maintained | [
"Sets",
"the",
"magnitude",
"of",
"the",
"Vector",
"Direction",
"is",
"maintained"
] | [
"\"\"\"Sets the magnitude of the Vector\n Direction is maintained\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": null,
"docstring_tokens": ... |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | magnitude2 | <not_specific> | def magnitude2(self):
"""Returns the magnitude squared of the Vector
Useful for comparing lengths
"""
return sum(value**2 for value in self) | Returns the magnitude squared of the Vector
Useful for comparing lengths
| Returns the magnitude squared of the Vector
Useful for comparing lengths | [
"Returns",
"the",
"magnitude",
"squared",
"of",
"the",
"Vector",
"Useful",
"for",
"comparing",
"lengths"
] | def magnitude2(self):
return sum(value**2 for value in self) | [
"def",
"magnitude2",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"value",
"**",
"2",
"for",
"value",
"in",
"self",
")"
] | Returns the magnitude squared of the Vector
Useful for comparing lengths | [
"Returns",
"the",
"magnitude",
"squared",
"of",
"the",
"Vector",
"Useful",
"for",
"comparing",
"lengths"
] | [
"\"\"\"Returns the magnitude squared of the Vector\n Useful for comparing lengths\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | normalized | null | def normalized(self, value):
"""Sets the normalized direction Vector
Magnitude is maintained
"""
if len(self) == len(value):
mag = self.magnitude
self._value = tuple(val*mag for val in value)
else:
raise DimentionMissmatchException() | Sets the normalized direction Vector
Magnitude is maintained
| Sets the normalized direction Vector
Magnitude is maintained | [
"Sets",
"the",
"normalized",
"direction",
"Vector",
"Magnitude",
"is",
"maintained"
] | def normalized(self, value):
if len(self) == len(value):
mag = self.magnitude
self._value = tuple(val*mag for val in value)
else:
raise DimentionMissmatchException() | [
"def",
"normalized",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"len",
"(",
"value",
")",
":",
"mag",
"=",
"self",
".",
"magnitude",
"self",
".",
"_value",
"=",
"tuple",
"(",
"val",
"*",
"mag",
"for",
"val",
"in",
... | Sets the normalized direction Vector
Magnitude is maintained | [
"Sets",
"the",
"normalized",
"direction",
"Vector",
"Magnitude",
"is",
"maintained"
] | [
"\"\"\"Sets the normalized direction Vector\n Magnitude is maintained\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": null,
"docstring_tokens": ... |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | dot | <not_specific> | def dot(cls, vect1, vect2):
"""Returns the dot product between two Vectors"""
if len(vect1) == len(vect2):
return sum(vect1[i]*vect2[i] for i in range((len(vect1))))
raise DimentionMissmatchException() | Returns the dot product between two Vectors | Returns the dot product between two Vectors | [
"Returns",
"the",
"dot",
"product",
"between",
"two",
"Vectors"
] | def dot(cls, vect1, vect2):
if len(vect1) == len(vect2):
return sum(vect1[i]*vect2[i] for i in range((len(vect1))))
raise DimentionMissmatchException() | [
"def",
"dot",
"(",
"cls",
",",
"vect1",
",",
"vect2",
")",
":",
"if",
"len",
"(",
"vect1",
")",
"==",
"len",
"(",
"vect2",
")",
":",
"return",
"sum",
"(",
"vect1",
"[",
"i",
"]",
"*",
"vect2",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
... | Returns the dot product between two Vectors | [
"Returns",
"the",
"dot",
"product",
"between",
"two",
"Vectors"
] | [
"\"\"\"Returns the dot product between two Vectors\"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "vect1",
"type": null
},
{
"param": "vect2",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vect1",
"type": null,
"docstring": null,
"docstring_tokens": [... |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | cross2 | <not_specific> | def cross2(cls, vect):
"""Returns the two dimensional cross product of a Vector.
Ignores other dimensions
"""
if len(vect) >= 2:
return Vector(-vect[1], vect[0])
raise DimentionMissmatchException() | Returns the two dimensional cross product of a Vector.
Ignores other dimensions
| Returns the two dimensional cross product of a Vector.
Ignores other dimensions | [
"Returns",
"the",
"two",
"dimensional",
"cross",
"product",
"of",
"a",
"Vector",
".",
"Ignores",
"other",
"dimensions"
] | def cross2(cls, vect):
if len(vect) >= 2:
return Vector(-vect[1], vect[0])
raise DimentionMissmatchException() | [
"def",
"cross2",
"(",
"cls",
",",
"vect",
")",
":",
"if",
"len",
"(",
"vect",
")",
">=",
"2",
":",
"return",
"Vector",
"(",
"-",
"vect",
"[",
"1",
"]",
",",
"vect",
"[",
"0",
"]",
")",
"raise",
"DimentionMissmatchException",
"(",
")"
] | Returns the two dimensional cross product of a Vector. | [
"Returns",
"the",
"two",
"dimensional",
"cross",
"product",
"of",
"a",
"Vector",
"."
] | [
"\"\"\"Returns the two dimensional cross product of a Vector.\n Ignores other dimensions\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "vect",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vect",
"type": null,
"docstring": null,
"docstring_tokens": []... |
0487d97fccc8cadf06d2c799a9e2c0023e55d05f | BenjaminSchaaf/PythonRaytracingVsRasterization | common/math3d.py | [
"MIT"
] | Python | cross3 | <not_specific> | def cross3(cls, v1, v2):
"""Returns the three dimensional cross product of two Vectors.
Ignores other dimensions
"""
if len(v1) == len(v2) >= 3:
return Vector(v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1]... | Returns the three dimensional cross product of two Vectors.
Ignores other dimensions
| Returns the three dimensional cross product of two Vectors.
Ignores other dimensions | [
"Returns",
"the",
"three",
"dimensional",
"cross",
"product",
"of",
"two",
"Vectors",
".",
"Ignores",
"other",
"dimensions"
] | def cross3(cls, v1, v2):
if len(v1) == len(v2) >= 3:
return Vector(v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0])
raise DimentionMissmatchException() | [
"def",
"cross3",
"(",
"cls",
",",
"v1",
",",
"v2",
")",
":",
"if",
"len",
"(",
"v1",
")",
"==",
"len",
"(",
"v2",
")",
">=",
"3",
":",
"return",
"Vector",
"(",
"v1",
"[",
"1",
"]",
"*",
"v2",
"[",
"2",
"]",
"-",
"v1",
"[",
"2",
"]",
"*"... | Returns the three dimensional cross product of two Vectors. | [
"Returns",
"the",
"three",
"dimensional",
"cross",
"product",
"of",
"two",
"Vectors",
"."
] | [
"\"\"\"Returns the three dimensional cross product of two Vectors.\n Ignores other dimensions\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "v1",
"type": null
},
{
"param": "v2",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "v1",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
590ba829c6435e57323a7dda2a5002997616df56 | MikeHart85/ophyd | scripts/collect_ad_boilerplate.py | [
"BSD-3-Clause"
] | Python | write_detector_class | null | def write_detector_class(boilerplate_file, dev_name, det_name, cam_name):
"""
Writes boilerplate 'Detector' class for ophyd/areadetector/detectors.
This script automates the creation of ophyd classes for areaDetector
drivers by scraping their *.template files. It is called by developers as
needed.
... |
Writes boilerplate 'Detector' class for ophyd/areadetector/detectors.
This script automates the creation of ophyd classes for areaDetector
drivers by scraping their *.template files. It is called by developers as
needed.
Parameters
----------
boilerplate_file : io.TextIOWrapper
Op... | Writes boilerplate 'Detector' class for ophyd/areadetector/detectors.
This script automates the creation of ophyd classes for areaDetector
drivers by scraping their *.template files. It is called by developers as
needed.
Parameters
boilerplate_file : io.TextIOWrapper
Open temporary file for writing boilerplate
dev_na... | [
"Writes",
"boilerplate",
"'",
"Detector",
"'",
"class",
"for",
"ophyd",
"/",
"areadetector",
"/",
"detectors",
".",
"This",
"script",
"automates",
"the",
"creation",
"of",
"ophyd",
"classes",
"for",
"areaDetector",
"drivers",
"by",
"scraping",
"their",
"*",
".... | def write_detector_class(boilerplate_file, dev_name, det_name, cam_name):
boilerplate_file.write(
f'''
class {det_name}(DetectorBase):
_html_docs = ['{dev_name}Doc.html']
cam = C(cam.{cam_name}, 'cam1:')
''') | [
"def",
"write_detector_class",
"(",
"boilerplate_file",
",",
"dev_name",
",",
"det_name",
",",
"cam_name",
")",
":",
"boilerplate_file",
".",
"write",
"(",
"f'''\nclass {det_name}(DetectorBase):\n _html_docs = ['{dev_name}Doc.html']\n cam = C(cam.{cam_name}, 'cam1:')\n'''",
"... | Writes boilerplate 'Detector' class for ophyd/areadetector/detectors. | [
"Writes",
"boilerplate",
"'",
"Detector",
"'",
"class",
"for",
"ophyd",
"/",
"areadetector",
"/",
"detectors",
"."
] | [
"\"\"\"\n Writes boilerplate 'Detector' class for ophyd/areadetector/detectors.\n\n This script automates the creation of ophyd classes for areaDetector\n drivers by scraping their *.template files. It is called by developers as\n needed.\n\n Parameters\n ----------\n boilerplate_file : io.Text... | [
{
"param": "boilerplate_file",
"type": null
},
{
"param": "dev_name",
"type": null
},
{
"param": "det_name",
"type": null
},
{
"param": "cam_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "boilerplate_file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dev_name",
"type": null,
"docstring": null,
"docs... |
590ba829c6435e57323a7dda2a5002997616df56 | MikeHart85/ophyd | scripts/collect_ad_boilerplate.py | [
"BSD-3-Clause"
] | Python | parse_pv_structure | <not_specific> | def parse_pv_structure(driver_dir):
"""
Reads all .template files in the specified driver directory and maps them
to the appropriate EPICS signal class in ophyd
Also determines if the Cam class should extend the FileBase class as well.
Parameters
----------
driver_dir : PathLike
Pa... |
Reads all .template files in the specified driver directory and maps them
to the appropriate EPICS signal class in ophyd
Also determines if the Cam class should extend the FileBase class as well.
Parameters
----------
driver_dir : PathLike
Path to the areaDetector driver
Returns
... | Reads all .template files in the specified driver directory and maps them
to the appropriate EPICS signal class in ophyd
Also determines if the Cam class should extend the FileBase class as well.
Parameters
driver_dir : PathLike
Path to the areaDetector driver
Returns
pv_to_signal_mapping : dict
Dict mapping PVs t... | [
"Reads",
"all",
".",
"template",
"files",
"in",
"the",
"specified",
"driver",
"directory",
"and",
"maps",
"them",
"to",
"the",
"appropriate",
"EPICS",
"signal",
"class",
"in",
"ophyd",
"Also",
"determines",
"if",
"the",
"Cam",
"class",
"should",
"extend",
"t... | def parse_pv_structure(driver_dir):
template_dir = driver_dir
for dir in os.listdir(driver_dir):
if os.path.isdir(os.path.join(driver_dir, dir)) and dir.endswith('App'):
template_dir = os.path.join(template_dir, dir, 'Db')
break
logging.debug(f'Found template dir: {template_d... | [
"def",
"parse_pv_structure",
"(",
"driver_dir",
")",
":",
"template_dir",
"=",
"driver_dir",
"for",
"dir",
"in",
"os",
".",
"listdir",
"(",
"driver_dir",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"driver... | Reads all .template files in the specified driver directory and maps them
to the appropriate EPICS signal class in ophyd | [
"Reads",
"all",
".",
"template",
"files",
"in",
"the",
"specified",
"driver",
"directory",
"and",
"maps",
"them",
"to",
"the",
"appropriate",
"EPICS",
"signal",
"class",
"in",
"ophyd"
] | [
"\"\"\"\n Reads all .template files in the specified driver directory and maps them\n to the appropriate EPICS signal class in ophyd\n\n Also determines if the Cam class should extend the FileBase class as well.\n\n Parameters\n ----------\n driver_dir : PathLike\n Path to the areaDetector ... | [
{
"param": "driver_dir",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "driver_dir",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
590ba829c6435e57323a7dda2a5002997616df56 | MikeHart85/ophyd | scripts/collect_ad_boilerplate.py | [
"BSD-3-Clause"
] | Python | write_cam_class | null | def write_cam_class(boilerplate_file, pv_to_signal_mapping, include_file_base, dev_name, det_name, cam_name):
"""
Function that writes the boilerplate cam class. This includes the default configuration
attributes, along with all the attributes extracted from the template file.
This function uses the in... |
Function that writes the boilerplate cam class. This includes the default configuration
attributes, along with all the attributes extracted from the template file.
This function uses the inflection library's `underscore` function to convert a PV name
into an attribute name
Examples:
EnableCa... | Function that writes the boilerplate cam class. This includes the default configuration
attributes, along with all the attributes extracted from the template file.
This function uses the inflection library's `underscore` function to convert a PV name
into an attribute name | [
"Function",
"that",
"writes",
"the",
"boilerplate",
"cam",
"class",
".",
"This",
"includes",
"the",
"default",
"configuration",
"attributes",
"along",
"with",
"all",
"the",
"attributes",
"extracted",
"from",
"the",
"template",
"file",
".",
"This",
"function",
"u... | def write_cam_class(boilerplate_file, pv_to_signal_mapping, include_file_base, dev_name, det_name, cam_name):
file_base = ''
if include_file_base:
file_base = ', FileBase'
boilerplate_file.write(
f'''
class {cam_name}(CamBase{file_base}):
_html_docs = ['{dev_name}Doc.html']
_default_... | [
"def",
"write_cam_class",
"(",
"boilerplate_file",
",",
"pv_to_signal_mapping",
",",
"include_file_base",
",",
"dev_name",
",",
"det_name",
",",
"cam_name",
")",
":",
"file_base",
"=",
"''",
"if",
"include_file_base",
":",
"file_base",
"=",
"', FileBase'",
"boilerpl... | Function that writes the boilerplate cam class. | [
"Function",
"that",
"writes",
"the",
"boilerplate",
"cam",
"class",
"."
] | [
"\"\"\"\n Function that writes the boilerplate cam class. This includes the default configuration\n attributes, along with all the attributes extracted from the template file.\n\n This function uses the inflection library's `underscore` function to convert a PV name\n into an attribute name\n\n Examp... | [
{
"param": "boilerplate_file",
"type": null
},
{
"param": "pv_to_signal_mapping",
"type": null
},
{
"param": "include_file_base",
"type": null
},
{
"param": "dev_name",
"type": null
},
{
"param": "det_name",
"type": null
},
{
"param": "cam_name",
"... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "boilerplate_file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pv_to_signal_mapping",
"type": null,
"docstring": null,... |
99ecaeb58a0f896053a5be7774d1db155b0315d7 | Pagliacii/langton-ant | langton.py | [
"MIT"
] | Python | _new_plane | list[list[int]] | def _new_plane(self) -> list[list[int]]:
"""Creates a new empty plane."""
return [
[self._default_cell for _ in range(self._column)] for _ in range(self._row)
] | Creates a new empty plane. | Creates a new empty plane. | [
"Creates",
"a",
"new",
"empty",
"plane",
"."
] | def _new_plane(self) -> list[list[int]]:
return [
[self._default_cell for _ in range(self._column)] for _ in range(self._row)
] | [
"def",
"_new_plane",
"(",
"self",
")",
"->",
"list",
"[",
"list",
"[",
"int",
"]",
"]",
":",
"return",
"[",
"[",
"self",
".",
"_default_cell",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_column",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"self... | Creates a new empty plane. | [
"Creates",
"a",
"new",
"empty",
"plane",
"."
] | [
"\"\"\"Creates a new empty plane.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
99ecaeb58a0f896053a5be7774d1db155b0315d7 | Pagliacii/langton-ant | langton.py | [
"MIT"
] | Python | _next_plane | None | def _next_plane(self) -> None:
"""Generates the next plane based on two simple rules."""
row, column = self._ant_pos
rule = self._rules[self._plane[row][column]]
self._plane[row][column] = rule["flip"]
if rule["turn"] == "left":
self._ant_direction = (self._ant_direct... | Generates the next plane based on two simple rules. | Generates the next plane based on two simple rules. | [
"Generates",
"the",
"next",
"plane",
"based",
"on",
"two",
"simple",
"rules",
"."
] | def _next_plane(self) -> None:
row, column = self._ant_pos
rule = self._rules[self._plane[row][column]]
self._plane[row][column] = rule["flip"]
if rule["turn"] == "left":
self._ant_direction = (self._ant_direction + 1) % 4
else:
self._ant_direction = (self... | [
"def",
"_next_plane",
"(",
"self",
")",
"->",
"None",
":",
"row",
",",
"column",
"=",
"self",
".",
"_ant_pos",
"rule",
"=",
"self",
".",
"_rules",
"[",
"self",
".",
"_plane",
"[",
"row",
"]",
"[",
"column",
"]",
"]",
"self",
".",
"_plane",
"[",
"... | Generates the next plane based on two simple rules. | [
"Generates",
"the",
"next",
"plane",
"based",
"on",
"two",
"simple",
"rules",
"."
] | [
"\"\"\"Generates the next plane based on two simple rules.\"\"\"",
"# Move forward one unit"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
32fb527f5420e5304b013bf74655812e1edce974 | richardsonlima/amonone | amonone/web/template.py | [
"MIT"
] | Python | age | <not_specific> | def age(from_date, since_date = None, target_tz=None, include_seconds=False):
'''
Returns the age as a string
'''
if since_date is None:
since_date = datetime.now(target_tz)
distance_in_time = since_date - from_date
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))... |
Returns the age as a string
| Returns the age as a string | [
"Returns",
"the",
"age",
"as",
"a",
"string"
] | def age(from_date, since_date = None, target_tz=None, include_seconds=False):
if since_date is None:
since_date = datetime.now(target_tz)
distance_in_time = since_date - from_date
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
distance_in_minutes = int(round(distan... | [
"def",
"age",
"(",
"from_date",
",",
"since_date",
"=",
"None",
",",
"target_tz",
"=",
"None",
",",
"include_seconds",
"=",
"False",
")",
":",
"if",
"since_date",
"is",
"None",
":",
"since_date",
"=",
"datetime",
".",
"now",
"(",
"target_tz",
")",
"dista... | Returns the age as a string | [
"Returns",
"the",
"age",
"as",
"a",
"string"
] | [
"'''\n\tReturns the age as a string\n\t'''"
] | [
{
"param": "from_date",
"type": null
},
{
"param": "since_date",
"type": null
},
{
"param": "target_tz",
"type": null
},
{
"param": "include_seconds",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "from_date",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "since_date",
"type": null,
"docstring": null,
"docstring... |
6eda3920f8d01d9e184d5cfb5479584bf2890a0f | punchagan/yamole | yamole.py | [
"MIT"
] | Python | merge | <not_specific> | def merge(self, a, b, path=None):
"""Merge a dict into another. Both may have nested dicts in them.
The destination dict is modified.
Args:
a: Destination dict, which will contain all the keys.
b: Source dict, which will be merged into "a".
Returns
... | Merge a dict into another. Both may have nested dicts in them.
The destination dict is modified.
Args:
a: Destination dict, which will contain all the keys.
b: Source dict, which will be merged into "a".
Returns
The destination dict, now including the conte... | Merge a dict into another. Both may have nested dicts in them.
The destination dict is modified. | [
"Merge",
"a",
"dict",
"into",
"another",
".",
"Both",
"may",
"have",
"nested",
"dicts",
"in",
"them",
".",
"The",
"destination",
"dict",
"is",
"modified",
"."
] | def merge(self, a, b, path=None):
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
if key == 'example' and self.openapi_mode:
a[key] = b[key]
... | [
"def",
"merge",
"(",
"self",
",",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key"... | Merge a dict into another. | [
"Merge",
"a",
"dict",
"into",
"another",
"."
] | [
"\"\"\"Merge a dict into another. Both may have nested dicts in them.\n\n The destination dict is modified.\n\n Args:\n a: Destination dict, which will contain all the keys.\n b: Source dict, which will be merged into \"a\".\n\n Returns\n The destination dict, n... | [
{
"param": "self",
"type": null
},
{
"param": "a",
"type": null
},
{
"param": "b",
"type": null
},
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a",
"type": null,
"docstring": "Destination dict, which will contai... |
6eda3920f8d01d9e184d5cfb5479584bf2890a0f | punchagan/yamole | yamole.py | [
"MIT"
] | Python | expand | <not_specific> | def expand(self, obj, parent, parent_dir=None, depth=0):
"""Recursively expand an object, considering any potential JSON
references it may contain.
See https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for a
brief description of what a JSON reference is.
Args:
... | Recursively expand an object, considering any potential JSON
references it may contain.
See https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for a
brief description of what a JSON reference is.
Args:
obj: The object to expand, which may contain JSON references.
... | Recursively expand an object, considering any potential JSON
references it may contain.
| [
"Recursively",
"expand",
"an",
"object",
"considering",
"any",
"potential",
"JSON",
"references",
"it",
"may",
"contain",
"."
] | def expand(self, obj, parent, parent_dir=None, depth=0):
parent_dir = parent_dir or self.data_dir
if depth > self.max_depth:
raise RuntimeError('The object has a depth higher than the '
'current limit ({}). Maybe the document has '
... | [
"def",
"expand",
"(",
"self",
",",
"obj",
",",
"parent",
",",
"parent_dir",
"=",
"None",
",",
"depth",
"=",
"0",
")",
":",
"parent_dir",
"=",
"parent_dir",
"or",
"self",
".",
"data_dir",
"if",
"depth",
">",
"self",
".",
"max_depth",
":",
"raise",
"Ru... | Recursively expand an object, considering any potential JSON
references it may contain. | [
"Recursively",
"expand",
"an",
"object",
"considering",
"any",
"potential",
"JSON",
"references",
"it",
"may",
"contain",
"."
] | [
"\"\"\"Recursively expand an object, considering any potential JSON\n references it may contain.\n\n See https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for a\n brief description of what a JSON reference is.\n\n Args:\n obj: The object to expand, which may contain JSO... | [
{
"param": "self",
"type": null
},
{
"param": "obj",
"type": null
},
{
"param": "parent",
"type": null
},
{
"param": "parent_dir",
"type": null
},
{
"param": "depth",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "obj",
"type": null,
"docstring": "The object to expand, which may c... |
6eda3920f8d01d9e184d5cfb5479584bf2890a0f | punchagan/yamole | yamole.py | [
"MIT"
] | Python | dumps | <not_specific> | def dumps(self, no_alias=True, full_expansion=True):
"""Dump the parsed object as a YAML-compliant string, using a
customized PyYAML dumper.
Args:
no_alias: Don't use any alias in the result.
full_expansion: Fully expand objects into YAML format (the default
... | Dump the parsed object as a YAML-compliant string, using a
customized PyYAML dumper.
Args:
no_alias: Don't use any alias in the result.
full_expansion: Fully expand objects into YAML format (the default
PyYAML dumper shows some nested objects as dicts).
... | Dump the parsed object as a YAML-compliant string, using a
customized PyYAML dumper. | [
"Dump",
"the",
"parsed",
"object",
"as",
"a",
"YAML",
"-",
"compliant",
"string",
"using",
"a",
"customized",
"PyYAML",
"dumper",
"."
] | def dumps(self, no_alias=True, full_expansion=True):
dumper = yaml.dumper.SafeDumper
if no_alias:
dumper.ignore_aliases = lambda self, data: True
return yaml.dump(self.data, default_flow_style=not full_expansion,
Dumper=dumper) | [
"def",
"dumps",
"(",
"self",
",",
"no_alias",
"=",
"True",
",",
"full_expansion",
"=",
"True",
")",
":",
"dumper",
"=",
"yaml",
".",
"dumper",
".",
"SafeDumper",
"if",
"no_alias",
":",
"dumper",
".",
"ignore_aliases",
"=",
"lambda",
"self",
",",
"data",
... | Dump the parsed object as a YAML-compliant string, using a
customized PyYAML dumper. | [
"Dump",
"the",
"parsed",
"object",
"as",
"a",
"YAML",
"-",
"compliant",
"string",
"using",
"a",
"customized",
"PyYAML",
"dumper",
"."
] | [
"\"\"\"Dump the parsed object as a YAML-compliant string, using a\n customized PyYAML dumper.\n\n Args:\n no_alias: Don't use any alias in the result.\n full_expansion: Fully expand objects into YAML format (the default\n PyYAML dumper shows some nested objects as ... | [
{
"param": "self",
"type": null
},
{
"param": "no_alias",
"type": null
},
{
"param": "full_expansion",
"type": null
}
] | {
"returns": [
{
"docstring": "A string with the parsed YAML object.",
"docstring_tokens": [
"A",
"string",
"with",
"the",
"parsed",
"YAML",
"object",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"i... |
35481bd12e27425867f876837cac17604d3a97cf | AurelienNioche/alphazero_singleplayer | alphazero_separate_net.py | [
"MIT"
] | Python | select | <not_specific> | def select(self, c=1.5):
""" Select one of the child actions based on UCT rule """
n = len(self.child_actions)
uct = np.zeros(n)
for i in range(n):
ca, prior = self.child_actions[i], self.priors[i]
uct[i] = ca.Q + prior * c * (np.sqrt(self.n)/(ca.n + 1))
w... | Select one of the child actions based on UCT rule | Select one of the child actions based on UCT rule | [
"Select",
"one",
"of",
"the",
"child",
"actions",
"based",
"on",
"UCT",
"rule"
] | def select(self, c=1.5):
n = len(self.child_actions)
uct = np.zeros(n)
for i in range(n):
ca, prior = self.child_actions[i], self.priors[i]
uct[i] = ca.Q + prior * c * (np.sqrt(self.n)/(ca.n + 1))
winner = np.nanargmax(uct)
return self.child_actions[win... | [
"def",
"select",
"(",
"self",
",",
"c",
"=",
"1.5",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"child_actions",
")",
"uct",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"ca",
",",
"prior",
"=",
"s... | Select one of the child actions based on UCT rule | [
"Select",
"one",
"of",
"the",
"child",
"actions",
"based",
"on",
"UCT",
"rule"
] | [
"\"\"\" Select one of the child actions based on UCT rule \"\"\"",
"# is is possible to have nan here?"
] | [
{
"param": "self",
"type": null
},
{
"param": "c",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "c",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
35481bd12e27425867f876837cac17604d3a97cf | AurelienNioche/alphazero_singleplayer | alphazero_separate_net.py | [
"MIT"
] | Python | search | null | def search(self, n_mcts, c, env, mcts_env):
"""
Perform the MCTS search from the root
"""
if self.root is None:
self.root = State(
self.root_index, r=0.0, terminal=False,
parent_action=None, na=self.na,
bootstrap_last_state_valu... |
Perform the MCTS search from the root
| Perform the MCTS search from the root | [
"Perform",
"the",
"MCTS",
"search",
"from",
"the",
"root"
] | def search(self, n_mcts, c, env, mcts_env):
if self.root is None:
self.root = State(
self.root_index, r=0.0, terminal=False,
parent_action=None, na=self.na,
bootstrap_last_state_value=self.bootstrap_last_state_value,
model=self.model) ... | [
"def",
"search",
"(",
"self",
",",
"n_mcts",
",",
"c",
",",
"env",
",",
"mcts_env",
")",
":",
"if",
"self",
".",
"root",
"is",
"None",
":",
"self",
".",
"root",
"=",
"State",
"(",
"self",
".",
"root_index",
",",
"r",
"=",
"0.0",
",",
"terminal",
... | Perform the MCTS search from the root | [
"Perform",
"the",
"MCTS",
"search",
"from",
"the",
"root"
] | [
"\"\"\"\n Perform the MCTS search from the root\n \"\"\"",
"# initialize new root",
"# continue from current root",
"# for Atari: snapshot the root at the beginning",
"# reset to root for new trace",
"# copy original Env to rollout from",
"# select",
"# expand",
"# Back-up ",
"# loop... | [
{
"param": "self",
"type": null
},
{
"param": "n_mcts",
"type": null
},
{
"param": "c",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "mcts_env",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "n_mcts",
"type": null,
"docstring": null,
"docstring_tokens":... |
35481bd12e27425867f876837cac17604d3a97cf | AurelienNioche/alphazero_singleplayer | alphazero_separate_net.py | [
"MIT"
] | Python | return_results | <not_specific> | def return_results(self, temp):
""" Process the output at the root node """
n = len(self.root.child_actions)
counts = np.zeros(n)
Q = np.zeros(n)
for i in range(n):
ca = self.root.child_actions[i]
counts[i] = ca.n
Q[i] = ca.Q
pi_target... | Process the output at the root node | Process the output at the root node | [
"Process",
"the",
"output",
"at",
"the",
"root",
"node"
] | def return_results(self, temp):
n = len(self.root.child_actions)
counts = np.zeros(n)
Q = np.zeros(n)
for i in range(n):
ca = self.root.child_actions[i]
counts[i] = ca.n
Q[i] = ca.Q
pi_target = self.stable_normalizer(counts, temp)
v_tar... | [
"def",
"return_results",
"(",
"self",
",",
"temp",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"root",
".",
"child_actions",
")",
"counts",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"Q",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"for",
"i",
"in",
... | Process the output at the root node | [
"Process",
"the",
"output",
"at",
"the",
"root",
"node"
] | [
"\"\"\" Process the output at the root node \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "temp",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "temp",
"type": null,
"docstring": null,
"docstring_tokens": [... |
d90f1a6dddcb378f2a80c9c8f48ffef763e22efc | AurelienNioche/alphazero_singleplayer | helpers.py | [
"MIT"
] | Python | check_space | <not_specific> | def check_space(space):
""" Check the properties of an environment state or action space """
if isinstance(space, spaces.Box):
dim = space.shape
discrete = False
elif isinstance(space, spaces.Discrete):
dim = space.n
discrete = True
else:
raise NotImplementedE... | Check the properties of an environment state or action space | Check the properties of an environment state or action space | [
"Check",
"the",
"properties",
"of",
"an",
"environment",
"state",
"or",
"action",
"space"
] | def check_space(space):
if isinstance(space, spaces.Box):
dim = space.shape
discrete = False
elif isinstance(space, spaces.Discrete):
dim = space.n
discrete = True
else:
raise NotImplementedError('This type of space is not supported')
return dim, discrete | [
"def",
"check_space",
"(",
"space",
")",
":",
"if",
"isinstance",
"(",
"space",
",",
"spaces",
".",
"Box",
")",
":",
"dim",
"=",
"space",
".",
"shape",
"discrete",
"=",
"False",
"elif",
"isinstance",
"(",
"space",
",",
"spaces",
".",
"Discrete",
")",
... | Check the properties of an environment state or action space | [
"Check",
"the",
"properties",
"of",
"an",
"environment",
"state",
"or",
"action",
"space"
] | [
"\"\"\" Check the properties of an environment state or action space \"\"\""
] | [
{
"param": "space",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "space",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d90f1a6dddcb378f2a80c9c8f48ffef763e22efc | AurelienNioche/alphazero_singleplayer | helpers.py | [
"MIT"
] | Python | symmetric_remove | <not_specific> | def symmetric_remove(x, n):
''' removes n items from beginning and end '''
odd = is_odd(n)
half = int(n/2)
if half > 0:
x = x[half:-half]
if odd:
x = x[1:]
return x | removes n items from beginning and end | removes n items from beginning and end | [
"removes",
"n",
"items",
"from",
"beginning",
"and",
"end"
] | def symmetric_remove(x, n):
odd = is_odd(n)
half = int(n/2)
if half > 0:
x = x[half:-half]
if odd:
x = x[1:]
return x | [
"def",
"symmetric_remove",
"(",
"x",
",",
"n",
")",
":",
"odd",
"=",
"is_odd",
"(",
"n",
")",
"half",
"=",
"int",
"(",
"n",
"/",
"2",
")",
"if",
"half",
">",
"0",
":",
"x",
"=",
"x",
"[",
"half",
":",
"-",
"half",
"]",
"if",
"odd",
":",
"... | removes n items from beginning and end | [
"removes",
"n",
"items",
"from",
"beginning",
"and",
"end"
] | [
"''' removes n items from beginning and end '''"
] | [
{
"param": "x",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
90ac92a0ea2abf60aadbdcad5054e843a5d90530 | philipjung164/ranger | security-admin/src/bin/ranger_install.py | [
"Apache-2.0"
] | Python | ModConfig | <not_specific> | def ModConfig(File, Variable, Setting):
"""
Modify Config file variable with new setting
"""
VarFound = False
AlreadySet = False
V=str(Variable)
S=str(Setting)
# use quotes if setting has spaces #
if ' ' in S:
S = '"%s"' % S
for line in fileinput.input(File, inplace = 1)... |
Modify Config file variable with new setting
| Modify Config file variable with new setting | [
"Modify",
"Config",
"file",
"variable",
"with",
"new",
"setting"
] | def ModConfig(File, Variable, Setting):
VarFound = False
AlreadySet = False
V=str(Variable)
S=str(Setting)
if ' ' in S:
S = '"%s"' % S
for line in fileinput.input(File, inplace = 1):
if not line.lstrip(' ').startswith('#') and '=' in line:
_infile_var = str(line.split... | [
"def",
"ModConfig",
"(",
"File",
",",
"Variable",
",",
"Setting",
")",
":",
"VarFound",
"=",
"False",
"AlreadySet",
"=",
"False",
"V",
"=",
"str",
"(",
"Variable",
")",
"S",
"=",
"str",
"(",
"Setting",
")",
"if",
"' '",
"in",
"S",
":",
"S",
"=",
... | Modify Config file variable with new setting | [
"Modify",
"Config",
"file",
"variable",
"with",
"new",
"setting"
] | [
"\"\"\"\n Modify Config file variable with new setting\n \"\"\"",
"# use quotes if setting has spaces #",
"# process lines that look like config settings #",
"# only change the first matching occurrence #",
"# don't change it if it is already set #",
"# Append the variable if it wasn't found #"
] | [
{
"param": "File",
"type": null
},
{
"param": "Variable",
"type": null
},
{
"param": "Setting",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "File",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "Variable",
"type": null,
"docstring": null,
"docstring_tokens... |
7d7ddfc5deca5e26e56f3fde23817160be21fafb | chumleyj/Brick-Breaking-Game | ball.py | [
"CC-BY-4.0",
"AAL"
] | Python | update | null | def update(self):
"""
Updates the position of the sprite
"""
self.center_x += self.change_x
self.center_y += self.change_y |
Updates the position of the sprite
| Updates the position of the sprite | [
"Updates",
"the",
"position",
"of",
"the",
"sprite"
] | def update(self):
self.center_x += self.change_x
self.center_y += self.change_y | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"center_x",
"+=",
"self",
".",
"change_x",
"self",
".",
"center_y",
"+=",
"self",
".",
"change_y"
] | Updates the position of the sprite | [
"Updates",
"the",
"position",
"of",
"the",
"sprite"
] | [
"\"\"\"\n Updates the position of the sprite\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | init_sounds | null | def init_sounds(self):
"""
This function sets up the background music for the game
"""
self.bg_music = arcade.load_sound('music-short.wav')
self.bg_music.play(loop=True) |
This function sets up the background music for the game
| This function sets up the background music for the game | [
"This",
"function",
"sets",
"up",
"the",
"background",
"music",
"for",
"the",
"game"
] | def init_sounds(self):
self.bg_music = arcade.load_sound('music-short.wav')
self.bg_music.play(loop=True) | [
"def",
"init_sounds",
"(",
"self",
")",
":",
"self",
".",
"bg_music",
"=",
"arcade",
".",
"load_sound",
"(",
"'music-short.wav'",
")",
"self",
".",
"bg_music",
".",
"play",
"(",
"loop",
"=",
"True",
")"
] | This function sets up the background music for the game | [
"This",
"function",
"sets",
"up",
"the",
"background",
"music",
"for",
"the",
"game"
] | [
"\"\"\"\n This function sets up the background music for the game\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | populate_bricks | null | def populate_bricks(self, image='images/brick.png'):
"""
This function sets up the bricks for the current level of the game
"""
# create bricks at each coordinate from layout for current level and add to brick_list
for loc in layouts.brick_layouts[self.level]:
brick =... |
This function sets up the bricks for the current level of the game
| This function sets up the bricks for the current level of the game | [
"This",
"function",
"sets",
"up",
"the",
"bricks",
"for",
"the",
"current",
"level",
"of",
"the",
"game"
] | def populate_bricks(self, image='images/brick.png'):
for loc in layouts.brick_layouts[self.level]:
brick = arcade.Sprite(filename=image,
center_x=loc[0],
center_y=loc[1],
scale=1,
... | [
"def",
"populate_bricks",
"(",
"self",
",",
"image",
"=",
"'images/brick.png'",
")",
":",
"for",
"loc",
"in",
"layouts",
".",
"brick_layouts",
"[",
"self",
".",
"level",
"]",
":",
"brick",
"=",
"arcade",
".",
"Sprite",
"(",
"filename",
"=",
"image",
",",... | This function sets up the bricks for the current level of the game | [
"This",
"function",
"sets",
"up",
"the",
"bricks",
"for",
"the",
"current",
"level",
"of",
"the",
"game"
] | [
"\"\"\"\n This function sets up the bricks for the current level of the game\n \"\"\"",
"# create bricks at each coordinate from layout for current level and add to brick_list"
] | [
{
"param": "self",
"type": null
},
{
"param": "image",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "image",
"type": null,
"docstring": null,
"docstring_tokens": ... |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | reset_ball | null | def reset_ball(self):
"""
This function places the ball at rest on top of the paddle
"""
# reposition the ball on the paddle and stop its movement
self.ball_sprite.bottom = self.paddle_sprite.top + 1
self.ball_sprite.center_x = self.paddle_sprite.center_x
self.bal... |
This function places the ball at rest on top of the paddle
| This function places the ball at rest on top of the paddle | [
"This",
"function",
"places",
"the",
"ball",
"at",
"rest",
"on",
"top",
"of",
"the",
"paddle"
] | def reset_ball(self):
self.ball_sprite.bottom = self.paddle_sprite.top + 1
self.ball_sprite.center_x = self.paddle_sprite.center_x
self.ball_sprite.change_x = 0
self.ball_sprite.change_y = 0 | [
"def",
"reset_ball",
"(",
"self",
")",
":",
"self",
".",
"ball_sprite",
".",
"bottom",
"=",
"self",
".",
"paddle_sprite",
".",
"top",
"+",
"1",
"self",
".",
"ball_sprite",
".",
"center_x",
"=",
"self",
".",
"paddle_sprite",
".",
"center_x",
"self",
".",
... | This function places the ball at rest on top of the paddle | [
"This",
"function",
"places",
"the",
"ball",
"at",
"rest",
"on",
"top",
"of",
"the",
"paddle"
] | [
"\"\"\"\n This function places the ball at rest on top of the paddle\n \"\"\"",
"# reposition the ball on the paddle and stop its movement"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | advance_levels | null | def advance_levels(self):
"""
Advances the level, including setting up the next brick layout
and setting the ball back on the paddle
"""
self.level += 1
# setup next level's brick layout
self.populate_bricks(BRICK_IMAGES[self.level - 1])
# reset ball's sp... |
Advances the level, including setting up the next brick layout
and setting the ball back on the paddle
| Advances the level, including setting up the next brick layout
and setting the ball back on the paddle | [
"Advances",
"the",
"level",
"including",
"setting",
"up",
"the",
"next",
"brick",
"layout",
"and",
"setting",
"the",
"ball",
"back",
"on",
"the",
"paddle"
] | def advance_levels(self):
self.level += 1
self.populate_bricks(BRICK_IMAGES[self.level - 1])
self.reset_ball() | [
"def",
"advance_levels",
"(",
"self",
")",
":",
"self",
".",
"level",
"+=",
"1",
"self",
".",
"populate_bricks",
"(",
"BRICK_IMAGES",
"[",
"self",
".",
"level",
"-",
"1",
"]",
")",
"self",
".",
"reset_ball",
"(",
")"
] | Advances the level, including setting up the next brick layout
and setting the ball back on the paddle | [
"Advances",
"the",
"level",
"including",
"setting",
"up",
"the",
"next",
"brick",
"layout",
"and",
"setting",
"the",
"ball",
"back",
"on",
"the",
"paddle"
] | [
"\"\"\"\n Advances the level, including setting up the next brick layout\n and setting the ball back on the paddle\n \"\"\"",
"# setup next level's brick layout",
"# reset ball's speed to 0 and place on paddle"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | wall_collisions | null | def wall_collisions(self):
"""
This function updates the ball's speed in the x,y directions
based on collisions with the wall
"""
# update ball's speed in x,y directions based on contact with the walls or ceiling
if self.ball_sprite.left < WALL_THICKNESS:
self... |
This function updates the ball's speed in the x,y directions
based on collisions with the wall
| This function updates the ball's speed in the x,y directions
based on collisions with the wall | [
"This",
"function",
"updates",
"the",
"ball",
"'",
"s",
"speed",
"in",
"the",
"x",
"y",
"directions",
"based",
"on",
"collisions",
"with",
"the",
"wall"
] | def wall_collisions(self):
if self.ball_sprite.left < WALL_THICKNESS:
self.ball_sprite.left = WALL_THICKNESS
self.ball_sprite.change_x *= -1
elif self.ball_sprite.right > SCREEN_WIDTH - WALL_THICKNESS:
self.ball_sprite.right = SCREEN_WIDTH - WALL_THICKNESS
... | [
"def",
"wall_collisions",
"(",
"self",
")",
":",
"if",
"self",
".",
"ball_sprite",
".",
"left",
"<",
"WALL_THICKNESS",
":",
"self",
".",
"ball_sprite",
".",
"left",
"=",
"WALL_THICKNESS",
"self",
".",
"ball_sprite",
".",
"change_x",
"*=",
"-",
"1",
"elif",... | This function updates the ball's speed in the x,y directions
based on collisions with the wall | [
"This",
"function",
"updates",
"the",
"ball",
"'",
"s",
"speed",
"in",
"the",
"x",
"y",
"directions",
"based",
"on",
"collisions",
"with",
"the",
"wall"
] | [
"\"\"\"\n This function updates the ball's speed in the x,y directions\n based on collisions with the wall\n \"\"\"",
"# update ball's speed in x,y directions based on contact with the walls or ceiling"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | paddle_collisions | null | def paddle_collisions(self):
"""
This function updates the ball's speed in the x,y directions
based on collisions with the paddle
"""
# change the ball's y direction if it collides with the paddle
if arcade.check_for_collision(self.ball_sprite, self.paddle_sprite) and sel... |
This function updates the ball's speed in the x,y directions
based on collisions with the paddle
| This function updates the ball's speed in the x,y directions
based on collisions with the paddle | [
"This",
"function",
"updates",
"the",
"ball",
"'",
"s",
"speed",
"in",
"the",
"x",
"y",
"directions",
"based",
"on",
"collisions",
"with",
"the",
"paddle"
] | def paddle_collisions(self):
if arcade.check_for_collision(self.ball_sprite, self.paddle_sprite) and self.ball_sprite.center_y > self.paddle_sprite.top:
self.ball_sprite.change_y *= -1
self.ball_sprite.bottom = self.paddle_sprite.top
self.ball_sprite.change_x += self.paddle_s... | [
"def",
"paddle_collisions",
"(",
"self",
")",
":",
"if",
"arcade",
".",
"check_for_collision",
"(",
"self",
".",
"ball_sprite",
",",
"self",
".",
"paddle_sprite",
")",
"and",
"self",
".",
"ball_sprite",
".",
"center_y",
">",
"self",
".",
"paddle_sprite",
"."... | This function updates the ball's speed in the x,y directions
based on collisions with the paddle | [
"This",
"function",
"updates",
"the",
"ball",
"'",
"s",
"speed",
"in",
"the",
"x",
"y",
"directions",
"based",
"on",
"collisions",
"with",
"the",
"paddle"
] | [
"\"\"\"\n This function updates the ball's speed in the x,y directions\n based on collisions with the paddle\n \"\"\"",
"# change the ball's y direction if it collides with the paddle",
"# update magnitude of ball's speed in x direction based on paddle's x speed at contact, capping at BALL_... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | brick_collisions | null | def brick_collisions(self):
"""
This function identifies bricks that the ball has collided with and determines the
side the ball impacted first. Based on the side first impacted, the ball's direction
is updated.
"""
# get list of collisions between ball and bricks
... |
This function identifies bricks that the ball has collided with and determines the
side the ball impacted first. Based on the side first impacted, the ball's direction
is updated.
| This function identifies bricks that the ball has collided with and determines the
side the ball impacted first. Based on the side first impacted, the ball's direction
is updated. | [
"This",
"function",
"identifies",
"bricks",
"that",
"the",
"ball",
"has",
"collided",
"with",
"and",
"determines",
"the",
"side",
"the",
"ball",
"impacted",
"first",
".",
"Based",
"on",
"the",
"side",
"first",
"impacted",
"the",
"ball",
"'",
"s",
"direction"... | def brick_collisions(self):
brick_collisions = arcade.check_for_collision_with_list(self.ball_sprite, self.brick_list)
change_y = False
change_x = False
for brick in brick_collisions:
if self.ball_sprite.center_y > brick.top and self.ball_sprite.center_x < brick.left:
... | [
"def",
"brick_collisions",
"(",
"self",
")",
":",
"brick_collisions",
"=",
"arcade",
".",
"check_for_collision_with_list",
"(",
"self",
".",
"ball_sprite",
",",
"self",
".",
"brick_list",
")",
"change_y",
"=",
"False",
"change_x",
"=",
"False",
"for",
"brick",
... | This function identifies bricks that the ball has collided with and determines the
side the ball impacted first. | [
"This",
"function",
"identifies",
"bricks",
"that",
"the",
"ball",
"has",
"collided",
"with",
"and",
"determines",
"the",
"side",
"the",
"ball",
"impacted",
"first",
"."
] | [
"\"\"\"\n This function identifies bricks that the ball has collided with and determines the\n side the ball impacted first. Based on the side first impacted, the ball's direction\n is updated.\n \"\"\"",
"# get list of collisions between ball and bricks",
"# variables to track wheth... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | on_update | null | def on_update(self, delta_time):
"""
Update sprites movement and collisions if the game has started
"""
# if ball has started movement
if self.ball_sprite.change_y != 0:
# update the ball's position
self.ball_list.update()
# update ball's spee... |
Update sprites movement and collisions if the game has started
| Update sprites movement and collisions if the game has started | [
"Update",
"sprites",
"movement",
"and",
"collisions",
"if",
"the",
"game",
"has",
"started"
] | def on_update(self, delta_time):
if self.ball_sprite.change_y != 0:
self.ball_list.update()
self.wall_collisions()
self.paddle_collisions()
self.brick_collisions()
if len(self.brick_list) == 0 and self.level < MAX_LEVEL:
self.advance_le... | [
"def",
"on_update",
"(",
"self",
",",
"delta_time",
")",
":",
"if",
"self",
".",
"ball_sprite",
".",
"change_y",
"!=",
"0",
":",
"self",
".",
"ball_list",
".",
"update",
"(",
")",
"self",
".",
"wall_collisions",
"(",
")",
"self",
".",
"paddle_collisions"... | Update sprites movement and collisions if the game has started | [
"Update",
"sprites",
"movement",
"and",
"collisions",
"if",
"the",
"game",
"has",
"started"
] | [
"\"\"\"\n Update sprites movement and collisions if the game has started\n \"\"\"",
"# if ball has started movement",
"# update the ball's position",
"# update ball's speed in x,y directions based on collision with the walls or ceiling",
"# update the ball's speed in the x,y directions based o... | [
{
"param": "self",
"type": null
},
{
"param": "delta_time",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "delta_time",
"type": null,
"docstring": null,
"docstring_toke... |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | on_draw | null | def on_draw(self):
"""
Clears the screen and draws sprites
"""
# clear the window
arcade.start_render()
# draw all sprites
self.paddle_list.draw()
self.brick_list.draw()
self.ball_list.draw()
self.wall_list.draw()
arcade.d... |
Clears the screen and draws sprites
| Clears the screen and draws sprites | [
"Clears",
"the",
"screen",
"and",
"draws",
"sprites"
] | def on_draw(self):
arcade.start_render()
self.paddle_list.draw()
self.brick_list.draw()
self.ball_list.draw()
self.wall_list.draw()
arcade.draw_text(f'Score: {self.score}', 30, 15, arcade.color.BLACK, 12, font_name='arial')
arcade.draw_text(f'Lives: {self.lives}',... | [
"def",
"on_draw",
"(",
"self",
")",
":",
"arcade",
".",
"start_render",
"(",
")",
"self",
".",
"paddle_list",
".",
"draw",
"(",
")",
"self",
".",
"brick_list",
".",
"draw",
"(",
")",
"self",
".",
"ball_list",
".",
"draw",
"(",
")",
"self",
".",
"wa... | Clears the screen and draws sprites | [
"Clears",
"the",
"screen",
"and",
"draws",
"sprites"
] | [
"\"\"\"\n Clears the screen and draws sprites\n \"\"\"",
"# clear the window",
"# draw all sprites"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | on_mouse_press | null | def on_mouse_press(self, x, y, button, modifiers):
"""
Click left mouse button to start the ball moving if it is at rest
"""
if (button == arcade.MOUSE_BUTTON_LEFT and self.ball_sprite.change_y == 0):
self.ball_sprite.change_y = BALL_SPEED
self.ball_sprite.change_... |
Click left mouse button to start the ball moving if it is at rest
| Click left mouse button to start the ball moving if it is at rest | [
"Click",
"left",
"mouse",
"button",
"to",
"start",
"the",
"ball",
"moving",
"if",
"it",
"is",
"at",
"rest"
] | def on_mouse_press(self, x, y, button, modifiers):
if (button == arcade.MOUSE_BUTTON_LEFT and self.ball_sprite.change_y == 0):
self.ball_sprite.change_y = BALL_SPEED
self.ball_sprite.change_x = 0 | [
"def",
"on_mouse_press",
"(",
"self",
",",
"x",
",",
"y",
",",
"button",
",",
"modifiers",
")",
":",
"if",
"(",
"button",
"==",
"arcade",
".",
"MOUSE_BUTTON_LEFT",
"and",
"self",
".",
"ball_sprite",
".",
"change_y",
"==",
"0",
")",
":",
"self",
".",
... | Click left mouse button to start the ball moving if it is at rest | [
"Click",
"left",
"mouse",
"button",
"to",
"start",
"the",
"ball",
"moving",
"if",
"it",
"is",
"at",
"rest"
] | [
"\"\"\"\n Click left mouse button to start the ball moving if it is at rest\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "button",
"type": null
},
{
"param": "modifiers",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | on_mouse_motion | null | def on_mouse_motion(self, x, y, dx, dy):
"""
Move the paddle based on the position of the mouse
"""
# align paddle with the mouse and get x-axis rate of change
self.paddle_sprite.center_x = x
self.paddle_sprite.change_x = dx
# prevent paddle from overlapp... |
Move the paddle based on the position of the mouse
| Move the paddle based on the position of the mouse | [
"Move",
"the",
"paddle",
"based",
"on",
"the",
"position",
"of",
"the",
"mouse"
] | def on_mouse_motion(self, x, y, dx, dy):
self.paddle_sprite.center_x = x
self.paddle_sprite.change_x = dx
if self.paddle_sprite.left < WALL_THICKNESS:
self.paddle_sprite.left = WALL_THICKNESS
elif self.paddle_sprite.right > SCREEN_WIDTH - WALL_THICKNESS:
self.padd... | [
"def",
"on_mouse_motion",
"(",
"self",
",",
"x",
",",
"y",
",",
"dx",
",",
"dy",
")",
":",
"self",
".",
"paddle_sprite",
".",
"center_x",
"=",
"x",
"self",
".",
"paddle_sprite",
".",
"change_x",
"=",
"dx",
"if",
"self",
".",
"paddle_sprite",
".",
"le... | Move the paddle based on the position of the mouse | [
"Move",
"the",
"paddle",
"based",
"on",
"the",
"position",
"of",
"the",
"mouse"
] | [
"\"\"\"\n Move the paddle based on the position of the mouse\n \"\"\"",
"# align paddle with the mouse and get x-axis rate of change",
"# prevent paddle from overlapping left or right wall",
"# if the ball hasn't started moving yet, match it's position to just above the center of the paddle"
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "dx",
"type": null
},
{
"param": "dy",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
7bf8d87f12d677ab4d471054f483d8cde0cfc494 | chumleyj/Brick-Breaking-Game | main.py | [
"CC-BY-4.0",
"AAL"
] | Python | main | null | def main():
"""
Create the game window and run the game
"""
window = BrickBraker()
window.setup()
arcade.run() |
Create the game window and run the game
| Create the game window and run the game | [
"Create",
"the",
"game",
"window",
"and",
"run",
"the",
"game"
] | def main():
window = BrickBraker()
window.setup()
arcade.run() | [
"def",
"main",
"(",
")",
":",
"window",
"=",
"BrickBraker",
"(",
")",
"window",
".",
"setup",
"(",
")",
"arcade",
".",
"run",
"(",
")"
] | Create the game window and run the game | [
"Create",
"the",
"game",
"window",
"and",
"run",
"the",
"game"
] | [
"\"\"\"\n Create the game window and run the game\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
0b4f3412d9830d0d13752974c8ffa01c893b79ae | louisdem/IMKit | utils/gimicq-import/GimICQ2IM.py | [
"BSD-3-Clause"
] | Python | extract | <not_specific> | def extract(line):
"""Return a tuple (uin, nick) from 'O11111111 nickname'"""
line = line.replace("\n", "")
uin = line[1:line.find("\t")]
# fix uin
uin2 = ""
for c in uin:
if c.isdigit():
uin2 += c
uin = uin2
nick = line[1+line.find("\t"):]
nick = nick.replace("/", "_")
nick = nick.replace(":", "_... | Return a tuple (uin, nick) from 'O11111111 nickname | Return a tuple (uin, nick) from 'O11111111 nickname | [
"Return",
"a",
"tuple",
"(",
"uin",
"nick",
")",
"from",
"'",
"O11111111",
"nickname"
] | def extract(line):
line = line.replace("\n", "")
uin = line[1:line.find("\t")]
uin2 = ""
for c in uin:
if c.isdigit():
uin2 += c
uin = uin2
nick = line[1+line.find("\t"):]
nick = nick.replace("/", "_")
nick = nick.replace(":", "_")
return (uin, nick) | [
"def",
"extract",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"uin",
"=",
"line",
"[",
"1",
":",
"line",
".",
"find",
"(",
"\"\\t\"",
")",
"]",
"uin2",
"=",
"\"\"",
"for",
"c",
"in",
"uin",
":",... | Return a tuple (uin, nick) from 'O11111111 nickname | [
"Return",
"a",
"tuple",
"(",
"uin",
"nick",
")",
"from",
"'",
"O11111111",
"nickname"
] | [
"\"\"\"Return a tuple (uin, nick) from 'O11111111\tnickname'\"\"\"",
"# fix uin"
] | [
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
1ab9e510ad6120cecdbd41ec57910e5cbe793f85 | thetianshuhuang/print | printtools/putil.py | [
"MIT"
] | Python | span | <not_specific> | def span(left, right, *args, width=get_terminal_size().columns, char=' '):
"""Set up left and right alignment.
Parameters
----------
left : str
Left string; to be left aligned
right : str
Right string; to be right aligned
*args : list
Additional arguments to render the s... | Set up left and right alignment.
Parameters
----------
left : str
Left string; to be left aligned
right : str
Right string; to be right aligned
*args : list
Additional arguments to render the span with
Keyword Args
------------
width : int
Width of the s... | Set up left and right alignment.
Parameters
left : str
Left string; to be left aligned
right : str
Right string; to be right aligned
args : list
Additional arguments to render the span with
Keyword Args
width : int
Width of the span; defaults to terminal width
char : str
Character to fill the span with; defaults to ... | [
"Set",
"up",
"left",
"and",
"right",
"alignment",
".",
"Parameters",
"left",
":",
"str",
"Left",
"string",
";",
"to",
"be",
"left",
"aligned",
"right",
":",
"str",
"Right",
"string",
";",
"to",
"be",
"right",
"aligned",
"args",
":",
"list",
"Additional",... | def span(left, right, *args, width=get_terminal_size().columns, char=' '):
slen = width - len(clear_fmt(left)) - len(clear_fmt(right))
return left + render(char * slen, *args) + right | [
"def",
"span",
"(",
"left",
",",
"right",
",",
"*",
"args",
",",
"width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
",",
"char",
"=",
"' '",
")",
":",
"slen",
"=",
"width",
"-",
"len",
"(",
"clear_fmt",
"(",
"left",
")",
")",
"-",
"len"... | Set up left and right alignment. | [
"Set",
"up",
"left",
"and",
"right",
"alignment",
"."
] | [
"\"\"\"Set up left and right alignment.\n\n Parameters\n ----------\n left : str\n Left string; to be left aligned\n right : str\n Right string; to be right aligned\n *args : list\n Additional arguments to render the span with\n\n Keyword Args\n ------------\n width : in... | [
{
"param": "left",
"type": null
},
{
"param": "right",
"type": null
},
{
"param": "width",
"type": null
},
{
"param": "char",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "left",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "right",
"type": null,
"docstring": null,
"docstring_tokens": ... |
1ab9e510ad6120cecdbd41ec57910e5cbe793f85 | thetianshuhuang/print | printtools/putil.py | [
"MIT"
] | Python | pad | <not_specific> | def pad(string, *args, width=get_terminal_size().columns, char=' '):
"""Pad a possibly multi-line string to the desired width."""
return '\n'.join([
span(s, '', *args, width=width, char=char)
for s in string.split('\n')
]) | Pad a possibly multi-line string to the desired width. | Pad a possibly multi-line string to the desired width. | [
"Pad",
"a",
"possibly",
"multi",
"-",
"line",
"string",
"to",
"the",
"desired",
"width",
"."
] | def pad(string, *args, width=get_terminal_size().columns, char=' '):
return '\n'.join([
span(s, '', *args, width=width, char=char)
for s in string.split('\n')
]) | [
"def",
"pad",
"(",
"string",
",",
"*",
"args",
",",
"width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
",",
"char",
"=",
"' '",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"span",
"(",
"s",
",",
"''",
",",
"*",
"args",
",",
"w... | Pad a possibly multi-line string to the desired width. | [
"Pad",
"a",
"possibly",
"multi",
"-",
"line",
"string",
"to",
"the",
"desired",
"width",
"."
] | [
"\"\"\"Pad a possibly multi-line string to the desired width.\"\"\""
] | [
{
"param": "string",
"type": null
},
{
"param": "width",
"type": null
},
{
"param": "char",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "string",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "width",
"type": null,
"docstring": null,
"docstring_tokens"... |
ac7409267204e7db8d2325ff9969a2610951583a | thetianshuhuang/print | printtools/print.py | [
"MIT"
] | Python | render | <not_specific> | def render(s, *args):
"""Render text with color and font."""
mods = "".join([__esc(i) for i in args if type(i) == int])
s = mods + __pf_render(s, __get_font(args))
# Remove trailing newline
if len(s) > 0 and s[-1] == '\n':
s = s[:-1]
# Add escape
return s + __esc(0) | Render text with color and font. | Render text with color and font. | [
"Render",
"text",
"with",
"color",
"and",
"font",
"."
] | def render(s, *args):
mods = "".join([__esc(i) for i in args if type(i) == int])
s = mods + __pf_render(s, __get_font(args))
if len(s) > 0 and s[-1] == '\n':
s = s[:-1]
return s + __esc(0) | [
"def",
"render",
"(",
"s",
",",
"*",
"args",
")",
":",
"mods",
"=",
"\"\"",
".",
"join",
"(",
"[",
"__esc",
"(",
"i",
")",
"for",
"i",
"in",
"args",
"if",
"type",
"(",
"i",
")",
"==",
"int",
"]",
")",
"s",
"=",
"mods",
"+",
"__pf_render",
"... | Render text with color and font. | [
"Render",
"text",
"with",
"color",
"and",
"font",
"."
] | [
"\"\"\"Render text with color and font.\"\"\"",
"# Remove trailing newline",
"# Add escape"
] | [
{
"param": "s",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "s",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
54800ef64b90c058b4fa87d6e0e2b40125f5a333 | thetianshuhuang/print | printtools/table.py | [
"MIT"
] | Python | __table_standard | <not_specific> | def __table_standard(t, padding=' ', indent='', hline=True, heading=False):
"""Print table with vertical dividers."""
t = [[padding + cell + padding for cell in row] for row in t]
widths = __get_widths(t)
# Make horizontal divider
hdiv = "{indent}+{content}+\n".format(
indent=indent,
... | Print table with vertical dividers. | Print table with vertical dividers. | [
"Print",
"table",
"with",
"vertical",
"dividers",
"."
] | def __table_standard(t, padding=' ', indent='', hline=True, heading=False):
t = [[padding + cell + padding for cell in row] for row in t]
widths = __get_widths(t)
hdiv = "{indent}+{content}+\n".format(
indent=indent,
content='+'.join(['-' * width for width in widths]))
tout = ''
if h... | [
"def",
"__table_standard",
"(",
"t",
",",
"padding",
"=",
"' '",
",",
"indent",
"=",
"''",
",",
"hline",
"=",
"True",
",",
"heading",
"=",
"False",
")",
":",
"t",
"=",
"[",
"[",
"padding",
"+",
"cell",
"+",
"padding",
"for",
"cell",
"in",
"row",
... | Print table with vertical dividers. | [
"Print",
"table",
"with",
"vertical",
"dividers",
"."
] | [
"\"\"\"Print table with vertical dividers.\"\"\"",
"# Make horizontal divider"
] | [
{
"param": "t",
"type": null
},
{
"param": "padding",
"type": null
},
{
"param": "indent",
"type": null
},
{
"param": "hline",
"type": null
},
{
"param": "heading",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "t",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "padding",
"type": null,
"docstring": null,
"docstring_tokens": [... |
54800ef64b90c058b4fa87d6e0e2b40125f5a333 | thetianshuhuang/print | printtools/table.py | [
"MIT"
] | Python | __table_nosep | <not_specific> | def __table_nosep(t, indent='', spacing=' ', hline=False, heading=False):
"""Table with no vertical dividers."""
widths = __get_widths(t)
hdiv = "-" * (sum(widths) + len(spacing) * (len(widths) - 1)) + "\n"
tout = ''
if hline:
tout = hdiv
for i, row in enumerate(t):
row_conten... | Table with no vertical dividers. | Table with no vertical dividers. | [
"Table",
"with",
"no",
"vertical",
"dividers",
"."
] | def __table_nosep(t, indent='', spacing=' ', hline=False, heading=False):
widths = __get_widths(t)
hdiv = "-" * (sum(widths) + len(spacing) * (len(widths) - 1)) + "\n"
tout = ''
if hline:
tout = hdiv
for i, row in enumerate(t):
row_contents = [
cell + ' ' * (width - len(... | [
"def",
"__table_nosep",
"(",
"t",
",",
"indent",
"=",
"''",
",",
"spacing",
"=",
"' '",
",",
"hline",
"=",
"False",
",",
"heading",
"=",
"False",
")",
":",
"widths",
"=",
"__get_widths",
"(",
"t",
")",
"hdiv",
"=",
"\"-\"",
"*",
"(",
"sum",
"(",
... | Table with no vertical dividers. | [
"Table",
"with",
"no",
"vertical",
"dividers",
"."
] | [
"\"\"\"Table with no vertical dividers.\"\"\""
] | [
{
"param": "t",
"type": null
},
{
"param": "indent",
"type": null
},
{
"param": "spacing",
"type": null
},
{
"param": "hline",
"type": null
},
{
"param": "heading",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "t",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "indent",
"type": null,
"docstring": null,
"docstring_tokens": []... |
54800ef64b90c058b4fa87d6e0e2b40125f5a333 | thetianshuhuang/print | printtools/table.py | [
"MIT"
] | Python | table | <not_specific> | def table(t, vline=True, render=False, **kwargs):
"""Print or render an ASCII table."""
# Ensure table has same dimensions
for row in t:
assert len(row) == len(t[0])
t = [[str(cell) for cell in row] for row in t]
tout = (__table_standard if vline else __table_nosep)(t, **kwargs)
if ren... | Print or render an ASCII table. | Print or render an ASCII table. | [
"Print",
"or",
"render",
"an",
"ASCII",
"table",
"."
] | def table(t, vline=True, render=False, **kwargs):
for row in t:
assert len(row) == len(t[0])
t = [[str(cell) for cell in row] for row in t]
tout = (__table_standard if vline else __table_nosep)(t, **kwargs)
if render:
return tout
else:
print(tout) | [
"def",
"table",
"(",
"t",
",",
"vline",
"=",
"True",
",",
"render",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"for",
"row",
"in",
"t",
":",
"assert",
"len",
"(",
"row",
")",
"==",
"len",
"(",
"t",
"[",
"0",
"]",
")",
"t",
"=",
"[",
"[",
... | Print or render an ASCII table. | [
"Print",
"or",
"render",
"an",
"ASCII",
"table",
"."
] | [
"\"\"\"Print or render an ASCII table.\"\"\"",
"# Ensure table has same dimensions"
] | [
{
"param": "t",
"type": null
},
{
"param": "vline",
"type": null
},
{
"param": "render",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "t",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vline",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
1de82e633ef8f47570acb8b5a724ef7517c864da | acuencadev/Motivational-Puppy-Meme-Generator | src/QuoteEngine/IngestorInterface.py | [
"MIT"
] | Python | can_ingest | bool | def can_ingest(cls, path: str) -> bool:
"""
Check if the file can be parsed
:param path: Path of the file.
:return: Whether or not the file can be parsed.
"""
extension = path.split('.')[-1]
return extension in cls.allowed_extensions |
Check if the file can be parsed
:param path: Path of the file.
:return: Whether or not the file can be parsed.
| Check if the file can be parsed | [
"Check",
"if",
"the",
"file",
"can",
"be",
"parsed"
] | def can_ingest(cls, path: str) -> bool:
extension = path.split('.')[-1]
return extension in cls.allowed_extensions | [
"def",
"can_ingest",
"(",
"cls",
",",
"path",
":",
"str",
")",
"->",
"bool",
":",
"extension",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"return",
"extension",
"in",
"cls",
".",
"allowed_extensions"
] | Check if the file can be parsed | [
"Check",
"if",
"the",
"file",
"can",
"be",
"parsed"
] | [
"\"\"\"\n Check if the file can be parsed\n \n :param path: Path of the file.\n :return: Whether or not the file can be parsed.\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "path",
"type": "str"
}
] | {
"returns": [
{
"docstring": "Whether or not the file can be parsed.",
"docstring_tokens": [
"Whether",
"or",
"not",
"the",
"file",
"can",
"be",
"parsed",
"."
],
"type": null
}
],
"raises": [],
"params": [
... |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | init_args | <not_specific> | def init_args(args_tuple: tuple, names=None):
''' converts tuple of arguments to a list of dicts
Params
------
names: optional, list-like
gives names for each of the arguments in the tuple
'''
if names is None:
names = ['start'] * len(args_tuple)
else:
assert len(name... | converts tuple of arguments to a list of dicts
Params
------
names: optional, list-like
gives names for each of the arguments in the tuple
| converts tuple of arguments to a list of dicts
Params
optional, list-like
gives names for each of the arguments in the tuple | [
"converts",
"tuple",
"of",
"arguments",
"to",
"a",
"list",
"of",
"dicts",
"Params",
"optional",
"list",
"-",
"like",
"gives",
"names",
"for",
"each",
"of",
"the",
"arguments",
"in",
"the",
"tuple"
] | def init_args(args_tuple: tuple, names=None):
if names is None:
names = ['start'] * len(args_tuple)
else:
assert len(names) == len(args_tuple), 'names should be same length as args_tuple'
output_dicts = []
for (i, ele) in enumerate(args_tuple):
output_dicts.append({
(... | [
"def",
"init_args",
"(",
"args_tuple",
":",
"tuple",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"[",
"'start'",
"]",
"*",
"len",
"(",
"args_tuple",
")",
"else",
":",
"assert",
"len",
"(",
"names",
")",
"=="... | converts tuple of arguments to a list of dicts
Params | [
"converts",
"tuple",
"of",
"arguments",
"to",
"a",
"list",
"of",
"dicts",
"Params"
] | [
"''' converts tuple of arguments to a list of dicts\n Params\n ------\n names: optional, list-like\n gives names for each of the arguments in the tuple\n '''"
] | [
{
"param": "args_tuple",
"type": "tuple"
},
{
"param": "names",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args_tuple",
"type": "tuple",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "names",
"type": null,
"docstring": null,
"docstring_... |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | s | <not_specific> | def s(x):
'''Gets shape of a list/tuple/ndarray
'''
if type(x) in [list, tuple]:
return len(x)
else:
return x.shape | Gets shape of a list/tuple/ndarray
| Gets shape of a list/tuple/ndarray | [
"Gets",
"shape",
"of",
"a",
"list",
"/",
"tuple",
"/",
"ndarray"
] | def s(x):
if type(x) in [list, tuple]:
return len(x)
else:
return x.shape | [
"def",
"s",
"(",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"return",
"len",
"(",
"x",
")",
"else",
":",
"return",
"x",
".",
"shape"
] | Gets shape of a list/tuple/ndarray | [
"Gets",
"shape",
"of",
"a",
"list",
"/",
"tuple",
"/",
"ndarray"
] | [
"'''Gets shape of a list/tuple/ndarray\n '''"
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | dict_to_df | <not_specific> | def dict_to_df(d: dict):
'''Converts a dictionary with tuple keys
into a pandas DataFrame
'''
d_copy = {k:d[k] for k in d if k != PREV_KEY}
df = pd.Series(d_copy).reset_index()
if len(d_copy.keys()) > 0:
cols = [sk.origin for sk in list(d_copy.keys())[0]] + ['out']
# set each ini... | Converts a dictionary with tuple keys
into a pandas DataFrame
| Converts a dictionary with tuple keys
into a pandas DataFrame | [
"Converts",
"a",
"dictionary",
"with",
"tuple",
"keys",
"into",
"a",
"pandas",
"DataFrame"
] | def dict_to_df(d: dict):
d_copy = {k:d[k] for k in d if k != PREV_KEY}
df = pd.Series(d_copy).reset_index()
if len(d_copy.keys()) > 0:
cols = [sk.origin for sk in list(d_copy.keys())[0]] + ['out']
cols = [c if c != 'init' else init_step(idx, cols) for idx, c in enumerate(cols) ]
df.s... | [
"def",
"dict_to_df",
"(",
"d",
":",
"dict",
")",
":",
"d_copy",
"=",
"{",
"k",
":",
"d",
"[",
"k",
"]",
"for",
"k",
"in",
"d",
"if",
"k",
"!=",
"PREV_KEY",
"}",
"df",
"=",
"pd",
".",
"Series",
"(",
"d_copy",
")",
".",
"reset_index",
"(",
")",... | Converts a dictionary with tuple keys
into a pandas DataFrame | [
"Converts",
"a",
"dictionary",
"with",
"tuple",
"keys",
"into",
"a",
"pandas",
"DataFrame"
] | [
"'''Converts a dictionary with tuple keys\n into a pandas DataFrame\n '''",
"# set each init col to init-{next_module_set}"
] | [
{
"param": "d",
"type": "dict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "d",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | compute_interval | <not_specific> | def compute_interval(df: DataFrame, d_label, wrt_label, accum: list=['std']):
'''Compute an interval (std. dev) of d_label column with
respect to pertubations in the wrt_label column
'''
df = df.astype({wrt_label: str})
return df[[wrt_label, d_label]].groupby(wrt_label).agg(accum) | Compute an interval (std. dev) of d_label column with
respect to pertubations in the wrt_label column
| Compute an interval (std. dev) of d_label column with
respect to pertubations in the wrt_label column | [
"Compute",
"an",
"interval",
"(",
"std",
".",
"dev",
")",
"of",
"d_label",
"column",
"with",
"respect",
"to",
"pertubations",
"in",
"the",
"wrt_label",
"column"
] | def compute_interval(df: DataFrame, d_label, wrt_label, accum: list=['std']):
df = df.astype({wrt_label: str})
return df[[wrt_label, d_label]].groupby(wrt_label).agg(accum) | [
"def",
"compute_interval",
"(",
"df",
":",
"DataFrame",
",",
"d_label",
",",
"wrt_label",
",",
"accum",
":",
"list",
"=",
"[",
"'std'",
"]",
")",
":",
"df",
"=",
"df",
".",
"astype",
"(",
"{",
"wrt_label",
":",
"str",
"}",
")",
"return",
"df",
"[",... | Compute an interval (std. | [
"Compute",
"an",
"interval",
"(",
"std",
"."
] | [
"'''Compute an interval (std. dev) of d_label column with \n respect to pertubations in the wrt_label column\n '''"
] | [
{
"param": "df",
"type": "DataFrame"
},
{
"param": "d_label",
"type": null
},
{
"param": "wrt_label",
"type": null
},
{
"param": "accum",
"type": "list"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "DataFrame",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "d_label",
"type": null,
"docstring": null,
"docstring_to... |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | to_tuple | <not_specific> | def to_tuple(lists: list):
'''Convert from lists to unpacked tuple
Ex. [[x1, y1], [x2, y2], [x3, y3]] -> ([x1, x2, x3], [y1, y2, y3])
Ex. [[x1, y1]] -> ([x1], [y1])
Ex. [m1, m2, m3] -> [m1, m2, m3]
Allows us to write X, y = ([x1, x2, x3], [y1, y2, y3])
'''
n_mods = len(lists)
if n_mods ... | Convert from lists to unpacked tuple
Ex. [[x1, y1], [x2, y2], [x3, y3]] -> ([x1, x2, x3], [y1, y2, y3])
Ex. [[x1, y1]] -> ([x1], [y1])
Ex. [m1, m2, m3] -> [m1, m2, m3]
Allows us to write X, y = ([x1, x2, x3], [y1, y2, y3])
| Convert from lists to unpacked tuple
Ex. | [
"Convert",
"from",
"lists",
"to",
"unpacked",
"tuple",
"Ex",
"."
] | def to_tuple(lists: list):
n_mods = len(lists)
if n_mods <= 1:
return lists
if not type(lists[0]) == list:
return lists
n_tup = len(lists[0])
tup = [[] for _ in range(n_tup)]
for i in range(n_mods):
for j in range(n_tup):
tup[j].append(lists[i][j])
return ... | [
"def",
"to_tuple",
"(",
"lists",
":",
"list",
")",
":",
"n_mods",
"=",
"len",
"(",
"lists",
")",
"if",
"n_mods",
"<=",
"1",
":",
"return",
"lists",
"if",
"not",
"type",
"(",
"lists",
"[",
"0",
"]",
")",
"==",
"list",
":",
"return",
"lists",
"n_tu... | Convert from lists to unpacked tuple
Ex. | [
"Convert",
"from",
"lists",
"to",
"unpacked",
"tuple",
"Ex",
"."
] | [
"'''Convert from lists to unpacked tuple\n Ex. [[x1, y1], [x2, y2], [x3, y3]] -> ([x1, x2, x3], [y1, y2, y3])\n Ex. [[x1, y1]] -> ([x1], [y1])\n Ex. [m1, m2, m3] -> [m1, m2, m3]\n Allows us to write X, y = ([x1, x2, x3], [y1, y2, y3])\n '''"
] | [
{
"param": "lists",
"type": "list"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "lists",
"type": "list",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | to_list | <not_specific> | def to_list(tup: tuple):
'''Convert from tuple to packed list
Ex. ([x1, x2, x3], [y1, y2, y3]) -> [[x1, y1], [x2, y2], [x3, y3]]
Ex. ([x1], [y1]) -> [[x1, y1]]
Ex. ([x1, x2, x3]) -> [[x1], [x2], [x3]]
Ex. (x1) -> [[x1]]
Ex. (x1, y1) -> [[x1, y1]]
Ex. (x1, x2, x3, y1, y2, y3) -> [[x1, y1], [x... | Convert from tuple to packed list
Ex. ([x1, x2, x3], [y1, y2, y3]) -> [[x1, y1], [x2, y2], [x3, y3]]
Ex. ([x1], [y1]) -> [[x1, y1]]
Ex. ([x1, x2, x3]) -> [[x1], [x2], [x3]]
Ex. (x1) -> [[x1]]
Ex. (x1, y1) -> [[x1, y1]]
Ex. (x1, x2, x3, y1, y2, y3) -> [[x1, y1], [x2, y2], [x3, y3]]
Ex. (x1, x... | Convert from tuple to packed list
Ex. | [
"Convert",
"from",
"tuple",
"to",
"packed",
"list",
"Ex",
"."
] | def to_list(tup: tuple):
n_tup = len(tup)
if n_tup == 0:
return []
elif not isinstance(tup[0], list):
if n_tup == 1:
return list(tup)
if n_tup % 2 != 0:
raise ValueError('Don\'t know how to handle uneven number of args '
'without a... | [
"def",
"to_list",
"(",
"tup",
":",
"tuple",
")",
":",
"n_tup",
"=",
"len",
"(",
"tup",
")",
"if",
"n_tup",
"==",
"0",
":",
"return",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"tup",
"[",
"0",
"]",
",",
"list",
")",
":",
"if",
"n_tup",
"==",
... | Convert from tuple to packed list
Ex. | [
"Convert",
"from",
"tuple",
"to",
"packed",
"list",
"Ex",
"."
] | [
"'''Convert from tuple to packed list\n Ex. ([x1, x2, x3], [y1, y2, y3]) -> [[x1, y1], [x2, y2], [x3, y3]]\n Ex. ([x1], [y1]) -> [[x1, y1]]\n Ex. ([x1, x2, x3]) -> [[x1], [x2], [x3]]\n Ex. (x1) -> [[x1]]\n Ex. (x1, y1) -> [[x1, y1]]\n Ex. (x1, x2, x3, y1, y2, y3) -> [[x1, y1], [x2, y2], [x3, y3]]\... | [
{
"param": "tup",
"type": "tuple"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tup",
"type": "tuple",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | sep_dicts | <not_specific> | def sep_dicts(d: dict, n_out: int = 1):
'''converts dictionary with value being saved as an iterable into multiple dictionaries
Assumes every value has same length n_out
Params
------
d: {k1: (x1, y1), k2: (x2, y2), ..., '__prev__': p}
n_out: the number of dictionaries to separate d into
... | converts dictionary with value being saved as an iterable into multiple dictionaries
Assumes every value has same length n_out
Params
------
d: {k1: (x1, y1), k2: (x2, y2), ..., '__prev__': p}
n_out: the number of dictionaries to separate d into
Returns
-------
sep_dicts: [{k1: x1, k2... | converts dictionary with value being saved as an iterable into multiple dictionaries
Assumes every value has same length n_out
Params
Returns
| [
"converts",
"dictionary",
"with",
"value",
"being",
"saved",
"as",
"an",
"iterable",
"into",
"multiple",
"dictionaries",
"Assumes",
"every",
"value",
"has",
"same",
"length",
"n_out",
"Params",
"Returns"
] | def sep_dicts(d: dict, n_out: int = 1):
if n_out == 1:
return d
else:
sep_dicts_id = str(uuid4())
sep_dicts = [dict() for x in range(n_out)]
for key, value in d.items():
if key != PREV_KEY:
for i in range(n_out):
new_key = (key[i],... | [
"def",
"sep_dicts",
"(",
"d",
":",
"dict",
",",
"n_out",
":",
"int",
"=",
"1",
")",
":",
"if",
"n_out",
"==",
"1",
":",
"return",
"d",
"else",
":",
"sep_dicts_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"sep_dicts",
"=",
"[",
"dict",
"(",
")"... | converts dictionary with value being saved as an iterable into multiple dictionaries
Assumes every value has same length n_out | [
"converts",
"dictionary",
"with",
"value",
"being",
"saved",
"as",
"an",
"iterable",
"into",
"multiple",
"dictionaries",
"Assumes",
"every",
"value",
"has",
"same",
"length",
"n_out"
] | [
"'''converts dictionary with value being saved as an iterable into multiple dictionaries\n Assumes every value has same length n_out\n\n Params\n ------\n d: {k1: (x1, y1), k2: (x2, y2), ..., '__prev__': p}\n n_out: the number of dictionaries to separate d into\n\n Returns\n -------\n sep_d... | [
{
"param": "d",
"type": "dict"
},
{
"param": "n_out",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "d",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "n_out",
"type": "int",
"docstring": null,
"docstring_tokens": ... |
41ee3c12be377a9bf70ddb845d9f138eea3a1a90 | Yu-Group/pcs-pipeline | vflow/convert.py | [
"MIT"
] | Python | combine_dicts | <not_specific> | def combine_dicts(*args: dict, base_case=True):
'''Combines any number of dictionaries into a single dictionary. Dictionaries
are combined left to right, matching on the subkeys of the arg that has
fewer matching requirements.
'''
n_args = len(args)
combined_dict = {}
if n_args == 0:
... | Combines any number of dictionaries into a single dictionary. Dictionaries
are combined left to right, matching on the subkeys of the arg that has
fewer matching requirements.
| Combines any number of dictionaries into a single dictionary. Dictionaries
are combined left to right, matching on the subkeys of the arg that has
fewer matching requirements. | [
"Combines",
"any",
"number",
"of",
"dictionaries",
"into",
"a",
"single",
"dictionary",
".",
"Dictionaries",
"are",
"combined",
"left",
"to",
"right",
"matching",
"on",
"the",
"subkeys",
"of",
"the",
"arg",
"that",
"has",
"fewer",
"matching",
"requirements",
"... | def combine_dicts(*args: dict, base_case=True):
n_args = len(args)
combined_dict = {}
if n_args == 0:
return combined_dict
elif n_args == 1:
for k in args[0]:
if k != PREV_KEY:
combined_dict[k] = (args[0][k],)
else:
combined_dict[k]... | [
"def",
"combine_dicts",
"(",
"*",
"args",
":",
"dict",
",",
"base_case",
"=",
"True",
")",
":",
"n_args",
"=",
"len",
"(",
"args",
")",
"combined_dict",
"=",
"{",
"}",
"if",
"n_args",
"==",
"0",
":",
"return",
"combined_dict",
"elif",
"n_args",
"==",
... | Combines any number of dictionaries into a single dictionary. | [
"Combines",
"any",
"number",
"of",
"dictionaries",
"into",
"a",
"single",
"dictionary",
"."
] | [
"'''Combines any number of dictionaries into a single dictionary. Dictionaries\n are combined left to right, matching on the subkeys of the arg that has\n fewer matching requirements.\n '''",
"# wrap the dict values in tuples; this is helpful so that when we",
"# pass the values to a module fun in we c... | [
{
"param": "args",
"type": "dict"
},
{
"param": "base_case",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "base_case",
"type": null,
"docstring": null,
"docstring_tok... |
0cb2d2dc9bb3f5911d2979d8565421bf43afcc33 | Yu-Group/pcs-pipeline | vflow/vfunc.py | [
"MIT"
] | Python | fit | <not_specific> | def fit(self, *args, **kwargs):
'''This function fits params for this module
'''
if hasattr(self.module, 'fit'):
return self.module.fit(*args, **kwargs)
else:
return self.module(*args, **kwargs) | This function fits params for this module
| This function fits params for this module | [
"This",
"function",
"fits",
"params",
"for",
"this",
"module"
] | def fit(self, *args, **kwargs):
if hasattr(self.module, 'fit'):
return self.module.fit(*args, **kwargs)
else:
return self.module(*args, **kwargs) | [
"def",
"fit",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"'fit'",
")",
":",
"return",
"self",
".",
"module",
".",
"fit",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"else",
":... | This function fits params for this module | [
"This",
"function",
"fits",
"params",
"for",
"this",
"module"
] | [
"'''This function fits params for this module\n '''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0cb2d2dc9bb3f5911d2979d8565421bf43afcc33 | Yu-Group/pcs-pipeline | vflow/vfunc.py | [
"MIT"
] | Python | fit | <not_specific> | def fit(self, *args, **kwargs):
'''This function fits params for this module
'''
if hasattr(self.module, 'fit'):
return _remote_fun.remote(self.module.fit, *args, **kwargs)
else:
return _remote_fun.remote(self.module, *args, **kwargs) | This function fits params for this module
| This function fits params for this module | [
"This",
"function",
"fits",
"params",
"for",
"this",
"module"
] | def fit(self, *args, **kwargs):
if hasattr(self.module, 'fit'):
return _remote_fun.remote(self.module.fit, *args, **kwargs)
else:
return _remote_fun.remote(self.module, *args, **kwargs) | [
"def",
"fit",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"'fit'",
")",
":",
"return",
"_remote_fun",
".",
"remote",
"(",
"self",
".",
"module",
".",
"fit",
",",
"*",
"args",
","... | This function fits params for this module | [
"This",
"function",
"fits",
"params",
"for",
"this",
"module"
] | [
"'''This function fits params for this module\n '''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
500eeba93a592798bfa443972dc651c49d9df038 | Yu-Group/pcs-pipeline | vflow/vset.py | [
"MIT"
] | Python | _apply_func_cached | <not_specific> | def _apply_func_cached(out_dict: dict, is_async: bool, *args):
'''
Params
------
*args: List[Dict]: takes multiple dicts and combines them into one.
Then runs modules on each item in combined dict.
out_dict: the dictionary to pass to the matching function. If None, defaults to self.modul... |
Params
------
*args: List[Dict]: takes multiple dicts and combines them into one.
Then runs modules on each item in combined dict.
out_dict: the dictionary to pass to the matching function. If None, defaults to self.modules.
Returns
-------
results: dict
with items bein... | Params
args: List[Dict]: takes multiple dicts and combines them into one.
Then runs modules on each item in combined dict.
out_dict: the dictionary to pass to the matching function. If None, defaults to self.modules.
Returns
dict
with items being determined by functions in module set.
Functions and input dictionaries... | [
"Params",
"args",
":",
"List",
"[",
"Dict",
"]",
":",
"takes",
"multiple",
"dicts",
"and",
"combines",
"them",
"into",
"one",
".",
"Then",
"runs",
"modules",
"on",
"each",
"item",
"in",
"combined",
"dict",
".",
"out_dict",
":",
"the",
"dictionary",
"to",... | def _apply_func_cached(out_dict: dict, is_async: bool, *args):
args = deepcopy(args)
for ele in args:
if not isinstance(ele, dict):
raise Exception('Need to run init_args before calling module_set!')
if is_async:
for k, v in ele.items():
if k != PREV_KEY:
... | [
"def",
"_apply_func_cached",
"(",
"out_dict",
":",
"dict",
",",
"is_async",
":",
"bool",
",",
"*",
"args",
")",
":",
"args",
"=",
"deepcopy",
"(",
"args",
")",
"for",
"ele",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"ele",
",",
"dict",
")",
... | Params
args: List[Dict]: takes multiple dicts and combines them into one. | [
"Params",
"args",
":",
"List",
"[",
"Dict",
"]",
":",
"takes",
"multiple",
"dicts",
"and",
"combines",
"them",
"into",
"one",
"."
] | [
"'''\n Params\n ------\n *args: List[Dict]: takes multiple dicts and combines them into one.\n Then runs modules on each item in combined dict.\n out_dict: the dictionary to pass to the matching function. If None, defaults to self.modules.\n\n Returns\n -------\n results: dict\n ... | [
{
"param": "out_dict",
"type": "dict"
},
{
"param": "is_async",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "out_dict",
"type": "dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "is_async",
"type": "bool",
"docstring": null,
"docstrin... |
647c16028a51e048cc5db5f3318be7418504b889 | Yu-Group/pcs-pipeline | vflow/subkey.py | [
"MIT"
] | Python | matches | <not_specific> | def matches(self, o: object):
'''When Subkey matching is required, determines if this Subkey is compatible
with another, meaning that the origins and values match, and either the
_sep_dicts_ids match or both Subkeys have _output_matching True.
'''
if isinstance(o, self.__class__... | When Subkey matching is required, determines if this Subkey is compatible
with another, meaning that the origins and values match, and either the
_sep_dicts_ids match or both Subkeys have _output_matching True.
| When Subkey matching is required, determines if this Subkey is compatible
with another, meaning that the origins and values match, and either the
_sep_dicts_ids match or both Subkeys have _output_matching True. | [
"When",
"Subkey",
"matching",
"is",
"required",
"determines",
"if",
"this",
"Subkey",
"is",
"compatible",
"with",
"another",
"meaning",
"that",
"the",
"origins",
"and",
"values",
"match",
"and",
"either",
"the",
"_sep_dicts_ids",
"match",
"or",
"both",
"Subkeys"... | def matches(self, o: object):
if isinstance(o, self.__class__):
cond0 = self.is_matching() and o.is_matching()
cond1 = self.value == o.value and self.origin == o.origin
cond2 = self._sep_dicts_id == o._sep_dicts_id \
or (self._output_matching and o._output_mat... | [
"def",
"matches",
"(",
"self",
",",
"o",
":",
"object",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"self",
".",
"__class__",
")",
":",
"cond0",
"=",
"self",
".",
"is_matching",
"(",
")",
"and",
"o",
".",
"is_matching",
"(",
")",
"cond1",
"=",
"... | When Subkey matching is required, determines if this Subkey is compatible
with another, meaning that the origins and values match, and either the
_sep_dicts_ids match or both Subkeys have _output_matching True. | [
"When",
"Subkey",
"matching",
"is",
"required",
"determines",
"if",
"this",
"Subkey",
"is",
"compatible",
"with",
"another",
"meaning",
"that",
"the",
"origins",
"and",
"values",
"match",
"and",
"either",
"the",
"_sep_dicts_ids",
"match",
"or",
"both",
"Subkeys"... | [
"'''When Subkey matching is required, determines if this Subkey is compatible\n with another, meaning that the origins and values match, and either the\n _sep_dicts_ids match or both Subkeys have _output_matching True.\n\n '''",
"# they're both matching",
"# value and origins match",
"# _... | [
{
"param": "self",
"type": null
},
{
"param": "o",
"type": "object"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "o",
"type": "object",
"docstring": null,
"docstring_tokens": ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.