repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
openstax/cnx-epub
cnxepub/models.py
Reference.bind
def bind(self, model, template="{}"): """Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed. """ self._bound_model = model self._uri_template = template self._set_uri_from_bound_model()
python
def bind(self, model, template="{}"): """Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed. """ self._bound_model = model self._uri_template = template self._set_uri_from_bound_model()
[ "def", "bind", "(", "self", ",", "model", ",", "template", "=", "\"{}\"", ")", ":", "self", ".", "_bound_model", "=", "model", "self", ".", "_uri_template", "=", "template", "self", ".", "_set_uri_from_bound_model", "(", ")" ]
Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed.
[ "Bind", "the", "model", "to", "the", "reference", ".", "This", "uses", "the", "model", "s", "id", "attribute", "and", "the", "given", "template", "to", "dynamically", "produce", "a", "uri", "when", "accessed", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/models.py#L263-L270
train
41,200
jepegit/cellpy
cellpy/utils/ica.py
index_bounds
def index_bounds(x): """returns tuple with first and last item""" if isinstance(x, (pd.DataFrame, pd.Series)): return x.iloc[0], x.iloc[-1] else: return x[0], x[-1]
python
def index_bounds(x): """returns tuple with first and last item""" if isinstance(x, (pd.DataFrame, pd.Series)): return x.iloc[0], x.iloc[-1] else: return x[0], x[-1]
[ "def", "index_bounds", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "(", "pd", ".", "DataFrame", ",", "pd", ".", "Series", ")", ")", ":", "return", "x", ".", "iloc", "[", "0", "]", ",", "x", ".", "iloc", "[", "-", "1", "]", "else", ...
returns tuple with first and last item
[ "returns", "tuple", "with", "first", "and", "last", "item" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L367-L372
train
41,201
jepegit/cellpy
cellpy/utils/ica.py
dqdv_cycle
def dqdv_cycle(cycle, splitter=True, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity', 'direction' (1 or -1)). splitter (bool): insert a np.NaN row between charge and discharge. Returns: List of step numbers corresponding to the selected steptype. Returns a pandas.DataFrame instead of a list if pdtype is set to True. Example: >>> cycle_df = my_data.get_cap( >>> ... 1, >>> ... categorical_column=True, >>> ... method = "forth-and-forth" >>> ... ) >>> voltage, incremental = ica.dqdv_cycle(cycle_df) """ c_first = cycle.loc[cycle["direction"] == -1] c_last = cycle.loc[cycle["direction"] == 1] converter = Converter(**kwargs) converter.set_data(c_first["capacity"], c_first["voltage"]) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() voltage_first = converter.voltage_processed incremental_capacity_first = converter.incremental_capacity if splitter: voltage_first = np.append(voltage_first, np.NaN) incremental_capacity_first = np.append(incremental_capacity_first, np.NaN) converter = Converter(**kwargs) converter.set_data(c_last["capacity"], c_last["voltage"]) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() voltage_last = converter.voltage_processed[::-1] incremental_capacity_last = converter.incremental_capacity[::-1] voltage = np.concatenate((voltage_first, voltage_last)) incremental_capacity = np.concatenate((incremental_capacity_first, incremental_capacity_last)) return voltage, incremental_capacity
python
def dqdv_cycle(cycle, splitter=True, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity', 'direction' (1 or -1)). splitter (bool): insert a np.NaN row between charge and discharge. Returns: List of step numbers corresponding to the selected steptype. Returns a pandas.DataFrame instead of a list if pdtype is set to True. Example: >>> cycle_df = my_data.get_cap( >>> ... 1, >>> ... categorical_column=True, >>> ... method = "forth-and-forth" >>> ... ) >>> voltage, incremental = ica.dqdv_cycle(cycle_df) """ c_first = cycle.loc[cycle["direction"] == -1] c_last = cycle.loc[cycle["direction"] == 1] converter = Converter(**kwargs) converter.set_data(c_first["capacity"], c_first["voltage"]) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() voltage_first = converter.voltage_processed incremental_capacity_first = converter.incremental_capacity if splitter: voltage_first = np.append(voltage_first, np.NaN) incremental_capacity_first = np.append(incremental_capacity_first, np.NaN) converter = Converter(**kwargs) converter.set_data(c_last["capacity"], c_last["voltage"]) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() voltage_last = converter.voltage_processed[::-1] incremental_capacity_last = converter.incremental_capacity[::-1] voltage = np.concatenate((voltage_first, voltage_last)) incremental_capacity = np.concatenate((incremental_capacity_first, incremental_capacity_last)) return voltage, incremental_capacity
[ "def", "dqdv_cycle", "(", "cycle", ",", "splitter", "=", "True", ",", "*", "*", "kwargs", ")", ":", "c_first", "=", "cycle", ".", "loc", "[", "cycle", "[", "\"direction\"", "]", "==", "-", "1", "]", "c_last", "=", "cycle", ".", "loc", "[", "cycle",...
Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity', 'direction' (1 or -1)). splitter (bool): insert a np.NaN row between charge and discharge. Returns: List of step numbers corresponding to the selected steptype. Returns a pandas.DataFrame instead of a list if pdtype is set to True. Example: >>> cycle_df = my_data.get_cap( >>> ... 1, >>> ... categorical_column=True, >>> ... method = "forth-and-forth" >>> ... ) >>> voltage, incremental = ica.dqdv_cycle(cycle_df)
[ "Convenience", "functions", "for", "creating", "dq", "-", "dv", "data", "from", "given", "capacity", "and", "voltage", "cycle", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L375-L432
train
41,202
jepegit/cellpy
cellpy/utils/ica.py
dqdv_cycles
def dqdv_cycles(cycles, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage cycles. Returns a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage', 'capacity', 'direction' (1 or -1)). Returns: pandas.DataFrame with columns 'cycle', 'voltage', 'dq'. Example: >>> cycles_df = my_data.get_cap( >>> ... categorical_column=True, >>> ... method = "forth-and-forth", >>> ... label_cycle_number=True, >>> ... ) >>> ica_df = ica.dqdv_cycles(cycles_df) """ # TODO: should add option for normalising based on first cycle capacity # this is e.g. done by first finding the first cycle capacity (nom_cap) # (or use nominal capacity given as input) and then propagating this to # Converter using the key-word arguments # normalize=True, normalization_factor=1.0, normalization_roof=nom_cap ica_dfs = list() cycle_group = cycles.groupby("cycle") for cycle_number, cycle in cycle_group: v, dq = dqdv_cycle(cycle, splitter=True, **kwargs) _ica_df = pd.DataFrame( { "voltage": v, "dq": dq, } ) _ica_df["cycle"] = cycle_number _ica_df = _ica_df[['cycle', 'voltage', 'dq']] ica_dfs.append(_ica_df) ica_df = pd.concat(ica_dfs) return ica_df
python
def dqdv_cycles(cycles, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage cycles. Returns a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage', 'capacity', 'direction' (1 or -1)). Returns: pandas.DataFrame with columns 'cycle', 'voltage', 'dq'. Example: >>> cycles_df = my_data.get_cap( >>> ... categorical_column=True, >>> ... method = "forth-and-forth", >>> ... label_cycle_number=True, >>> ... ) >>> ica_df = ica.dqdv_cycles(cycles_df) """ # TODO: should add option for normalising based on first cycle capacity # this is e.g. done by first finding the first cycle capacity (nom_cap) # (or use nominal capacity given as input) and then propagating this to # Converter using the key-word arguments # normalize=True, normalization_factor=1.0, normalization_roof=nom_cap ica_dfs = list() cycle_group = cycles.groupby("cycle") for cycle_number, cycle in cycle_group: v, dq = dqdv_cycle(cycle, splitter=True, **kwargs) _ica_df = pd.DataFrame( { "voltage": v, "dq": dq, } ) _ica_df["cycle"] = cycle_number _ica_df = _ica_df[['cycle', 'voltage', 'dq']] ica_dfs.append(_ica_df) ica_df = pd.concat(ica_dfs) return ica_df
[ "def", "dqdv_cycles", "(", "cycles", ",", "*", "*", "kwargs", ")", ":", "# TODO: should add option for normalising based on first cycle capacity", "# this is e.g. done by first finding the first cycle capacity (nom_cap)", "# (or use nominal capacity given as input) and then propagating this ...
Convenience functions for creating dq-dv data from given capacity and voltage cycles. Returns a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycles (pandas.DataFrame): the cycle data ('cycle', 'voltage', 'capacity', 'direction' (1 or -1)). Returns: pandas.DataFrame with columns 'cycle', 'voltage', 'dq'. Example: >>> cycles_df = my_data.get_cap( >>> ... categorical_column=True, >>> ... method = "forth-and-forth", >>> ... label_cycle_number=True, >>> ... ) >>> ica_df = ica.dqdv_cycles(cycles_df)
[ "Convenience", "functions", "for", "creating", "dq", "-", "dv", "data", "from", "given", "capacity", "and", "voltage", "cycles", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L435-L481
train
41,203
jepegit/cellpy
cellpy/utils/ica.py
dqdv
def dqdv(voltage, capacity, voltage_resolution=None, capacity_resolution=None, voltage_fwhm=0.01, pre_smoothing=True, diff_smoothing=False, post_smoothing=True, post_normalization=True, interpolation_method=None, gaussian_order=None, gaussian_mode=None, gaussian_cval=None, gaussian_truncate=None, points_pr_split=None, savgol_filter_window_divisor_default=None, savgol_filter_window_order=None, max_points=None, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.005) capacity_resolution: used for interpolating capacity data voltage_fwhm: used for setting the post-processing gaussian sigma pre_smoothing: set to True for pre-smoothing (window) diff_smoothing: set to True for smoothing during differentiation (window) post_smoothing: set to True for post-smoothing (gaussian) post_normalization: set to True for normalising to capacity interpolation_method: scipy interpolation method gaussian_order: int gaussian_mode: mode gaussian_cval: gaussian_truncate: points_pr_split: only used when investigating data using splits savgol_filter_window_divisor_default: used for window smoothing savgol_filter_window_order: used for window smoothing max_points: restricting to max points in vector (capacity-selected) Returns: voltage, dqdv Notes: PEC data (Helge) pre_smoothing = False diff_smoothing = False pos_smoothing = False voltage_resolution = 0.005 PEC data (Preben) ... Arbin data (IFE) ... """ converter = Converter(**kwargs) logging.debug("dqdv - starting") logging.debug("dqdv - created Converter obj") converter.pre_smoothing = pre_smoothing converter.post_smoothing = post_smoothing converter.smoothing = diff_smoothing converter.normalize = post_normalization converter.voltage_fwhm = voltage_fwhm logging.debug(f"converter.pre_smoothing: {converter.pre_smoothing}") logging.debug(f"converter.post_smoothing: {converter.post_smoothing}") logging.debug(f"converter.smoothing: {converter.smoothing}") logging.debug(f"converter.normalise: {converter.normalize}") logging.debug(f"converter.voltage_fwhm: {converter.voltage_fwhm}") if voltage_resolution is not None: converter.voltage_resolution = voltage_resolution if capacity_resolution is not None: converter.capacity_resolution = capacity_resolution if savgol_filter_window_divisor_default is not None: converter.savgol_filter_window_divisor_default = savgol_filter_window_divisor_default logging.debug(f"converter.savgol_filter_window_divisor_default: " f"{converter.savgol_filter_window_divisor_default}") if savgol_filter_window_order is not None: converter.savgol_filter_window_order = savgol_filter_window_order logging.debug(f"converter.savgol_filter_window_order: " f"{converter.savgol_filter_window_order}") if gaussian_mode is not None: converter.gaussian_mode = gaussian_mode if gaussian_order is not None: converter.gaussian_order = gaussian_order if gaussian_truncate is not None: converter.gaussian_truncate = gaussian_truncate if gaussian_cval is not None: converter.gaussian_cval = gaussian_cval if interpolation_method is not None: converter.interpolation_method = interpolation_method if points_pr_split is not None: converter.points_pr_split = points_pr_split if max_points is not None: converter.max_points = max_points converter.set_data(capacity, voltage) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() return converter.voltage_processed, converter.incremental_capacity
python
def dqdv(voltage, capacity, voltage_resolution=None, capacity_resolution=None, voltage_fwhm=0.01, pre_smoothing=True, diff_smoothing=False, post_smoothing=True, post_normalization=True, interpolation_method=None, gaussian_order=None, gaussian_mode=None, gaussian_cval=None, gaussian_truncate=None, points_pr_split=None, savgol_filter_window_divisor_default=None, savgol_filter_window_order=None, max_points=None, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.005) capacity_resolution: used for interpolating capacity data voltage_fwhm: used for setting the post-processing gaussian sigma pre_smoothing: set to True for pre-smoothing (window) diff_smoothing: set to True for smoothing during differentiation (window) post_smoothing: set to True for post-smoothing (gaussian) post_normalization: set to True for normalising to capacity interpolation_method: scipy interpolation method gaussian_order: int gaussian_mode: mode gaussian_cval: gaussian_truncate: points_pr_split: only used when investigating data using splits savgol_filter_window_divisor_default: used for window smoothing savgol_filter_window_order: used for window smoothing max_points: restricting to max points in vector (capacity-selected) Returns: voltage, dqdv Notes: PEC data (Helge) pre_smoothing = False diff_smoothing = False pos_smoothing = False voltage_resolution = 0.005 PEC data (Preben) ... Arbin data (IFE) ... """ converter = Converter(**kwargs) logging.debug("dqdv - starting") logging.debug("dqdv - created Converter obj") converter.pre_smoothing = pre_smoothing converter.post_smoothing = post_smoothing converter.smoothing = diff_smoothing converter.normalize = post_normalization converter.voltage_fwhm = voltage_fwhm logging.debug(f"converter.pre_smoothing: {converter.pre_smoothing}") logging.debug(f"converter.post_smoothing: {converter.post_smoothing}") logging.debug(f"converter.smoothing: {converter.smoothing}") logging.debug(f"converter.normalise: {converter.normalize}") logging.debug(f"converter.voltage_fwhm: {converter.voltage_fwhm}") if voltage_resolution is not None: converter.voltage_resolution = voltage_resolution if capacity_resolution is not None: converter.capacity_resolution = capacity_resolution if savgol_filter_window_divisor_default is not None: converter.savgol_filter_window_divisor_default = savgol_filter_window_divisor_default logging.debug(f"converter.savgol_filter_window_divisor_default: " f"{converter.savgol_filter_window_divisor_default}") if savgol_filter_window_order is not None: converter.savgol_filter_window_order = savgol_filter_window_order logging.debug(f"converter.savgol_filter_window_order: " f"{converter.savgol_filter_window_order}") if gaussian_mode is not None: converter.gaussian_mode = gaussian_mode if gaussian_order is not None: converter.gaussian_order = gaussian_order if gaussian_truncate is not None: converter.gaussian_truncate = gaussian_truncate if gaussian_cval is not None: converter.gaussian_cval = gaussian_cval if interpolation_method is not None: converter.interpolation_method = interpolation_method if points_pr_split is not None: converter.points_pr_split = points_pr_split if max_points is not None: converter.max_points = max_points converter.set_data(capacity, voltage) converter.inspect_data() converter.pre_process_data() converter.increment_data() converter.post_process_data() return converter.voltage_processed, converter.incremental_capacity
[ "def", "dqdv", "(", "voltage", ",", "capacity", ",", "voltage_resolution", "=", "None", ",", "capacity_resolution", "=", "None", ",", "voltage_fwhm", "=", "0.01", ",", "pre_smoothing", "=", "True", ",", "diff_smoothing", "=", "False", ",", "post_smoothing", "=...
Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.005) capacity_resolution: used for interpolating capacity data voltage_fwhm: used for setting the post-processing gaussian sigma pre_smoothing: set to True for pre-smoothing (window) diff_smoothing: set to True for smoothing during differentiation (window) post_smoothing: set to True for post-smoothing (gaussian) post_normalization: set to True for normalising to capacity interpolation_method: scipy interpolation method gaussian_order: int gaussian_mode: mode gaussian_cval: gaussian_truncate: points_pr_split: only used when investigating data using splits savgol_filter_window_divisor_default: used for window smoothing savgol_filter_window_order: used for window smoothing max_points: restricting to max points in vector (capacity-selected) Returns: voltage, dqdv Notes: PEC data (Helge) pre_smoothing = False diff_smoothing = False pos_smoothing = False voltage_resolution = 0.005 PEC data (Preben) ... Arbin data (IFE) ...
[ "Convenience", "functions", "for", "creating", "dq", "-", "dv", "data", "from", "given", "capacity", "and", "voltage", "data", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L484-L587
train
41,204
jepegit/cellpy
cellpy/utils/ica.py
_dqdv_combinded_frame
def _dqdv_combinded_frame(cell, **kwargs): """Returns full cycle dqdv data for all cycles as one pd.DataFrame. Args: cell: CellpyData-object Returns: pandas.DataFrame with the following columns: cycle: cycle number voltage: voltage dq: the incremental capacity """ cycles = cell.get_cap( method="forth-and-forth", categorical_column=True, label_cycle_number=True, ) ica_df = dqdv_cycles(cycles, **kwargs) assert isinstance(ica_df, pd.DataFrame) return ica_df
python
def _dqdv_combinded_frame(cell, **kwargs): """Returns full cycle dqdv data for all cycles as one pd.DataFrame. Args: cell: CellpyData-object Returns: pandas.DataFrame with the following columns: cycle: cycle number voltage: voltage dq: the incremental capacity """ cycles = cell.get_cap( method="forth-and-forth", categorical_column=True, label_cycle_number=True, ) ica_df = dqdv_cycles(cycles, **kwargs) assert isinstance(ica_df, pd.DataFrame) return ica_df
[ "def", "_dqdv_combinded_frame", "(", "cell", ",", "*", "*", "kwargs", ")", ":", "cycles", "=", "cell", ".", "get_cap", "(", "method", "=", "\"forth-and-forth\"", ",", "categorical_column", "=", "True", ",", "label_cycle_number", "=", "True", ",", ")", "ica_d...
Returns full cycle dqdv data for all cycles as one pd.DataFrame. Args: cell: CellpyData-object Returns: pandas.DataFrame with the following columns: cycle: cycle number voltage: voltage dq: the incremental capacity
[ "Returns", "full", "cycle", "dqdv", "data", "for", "all", "cycles", "as", "one", "pd", ".", "DataFrame", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L629-L649
train
41,205
jepegit/cellpy
cellpy/utils/ica.py
_dqdv_split_frames
def _dqdv_split_frames(cell, tidy=False, **kwargs): """Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are pandas.DataFrames where the first column is voltage ('v') and the following columns are the incremental capcaity for each cycle (multi-indexed, where cycle number is on the top level). Example: >>> from cellpy.utils import ica >>> charge_ica_df, dcharge_ica_df = ica.ica_frames(my_cell) >>> charge_ica_df.plot(x=("voltage", "v")) """ charge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves( cell, direction="charge" ) # charge_df = pd.concat( # charge_dfs, axis=1, keys=[k.name for k in charge_dfs]) ica_charge_dfs = _make_ica_charge_curves( charge_dfs, cycles, minimum_v, maximum_v, **kwargs, ) ica_charge_df = pd.concat( ica_charge_dfs, axis=1, keys=[k.name for k in ica_charge_dfs] ) dcharge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves( cell, direction="discharge" ) ica_dcharge_dfs = _make_ica_charge_curves( dcharge_dfs, cycles, minimum_v, maximum_v, **kwargs, ) ica_discharge_df = pd.concat( ica_dcharge_dfs, axis=1, keys=[k.name for k in ica_dcharge_dfs] ) ica_charge_df.columns.names = ["cycle", "value"] ica_discharge_df.columns.names = ["cycle", "value"] if tidy: ica_charge_df = ica_charge_df.melt( "voltage", var_name="cycle", value_name="dq", col_level=0 ) ica_discharge_df = ica_discharge_df.melt( "voltage", var_name="cycle", value_name="dq", col_level=0 ) return ica_charge_df, ica_discharge_df
python
def _dqdv_split_frames(cell, tidy=False, **kwargs): """Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are pandas.DataFrames where the first column is voltage ('v') and the following columns are the incremental capcaity for each cycle (multi-indexed, where cycle number is on the top level). Example: >>> from cellpy.utils import ica >>> charge_ica_df, dcharge_ica_df = ica.ica_frames(my_cell) >>> charge_ica_df.plot(x=("voltage", "v")) """ charge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves( cell, direction="charge" ) # charge_df = pd.concat( # charge_dfs, axis=1, keys=[k.name for k in charge_dfs]) ica_charge_dfs = _make_ica_charge_curves( charge_dfs, cycles, minimum_v, maximum_v, **kwargs, ) ica_charge_df = pd.concat( ica_charge_dfs, axis=1, keys=[k.name for k in ica_charge_dfs] ) dcharge_dfs, cycles, minimum_v, maximum_v = _collect_capacity_curves( cell, direction="discharge" ) ica_dcharge_dfs = _make_ica_charge_curves( dcharge_dfs, cycles, minimum_v, maximum_v, **kwargs, ) ica_discharge_df = pd.concat( ica_dcharge_dfs, axis=1, keys=[k.name for k in ica_dcharge_dfs] ) ica_charge_df.columns.names = ["cycle", "value"] ica_discharge_df.columns.names = ["cycle", "value"] if tidy: ica_charge_df = ica_charge_df.melt( "voltage", var_name="cycle", value_name="dq", col_level=0 ) ica_discharge_df = ica_discharge_df.melt( "voltage", var_name="cycle", value_name="dq", col_level=0 ) return ica_charge_df, ica_discharge_df
[ "def", "_dqdv_split_frames", "(", "cell", ",", "tidy", "=", "False", ",", "*", "*", "kwargs", ")", ":", "charge_dfs", ",", "cycles", ",", "minimum_v", ",", "maximum_v", "=", "_collect_capacity_curves", "(", "cell", ",", "direction", "=", "\"charge\"", ")", ...
Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are pandas.DataFrames where the first column is voltage ('v') and the following columns are the incremental capcaity for each cycle (multi-indexed, where cycle number is on the top level). Example: >>> from cellpy.utils import ica >>> charge_ica_df, dcharge_ica_df = ica.ica_frames(my_cell) >>> charge_ica_df.plot(x=("voltage", "v"))
[ "Returns", "dqdv", "data", "as", "pandas", ".", "DataFrames", "for", "all", "cycles", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L683-L750
train
41,206
jepegit/cellpy
cellpy/utils/ica.py
Converter.inspect_data
def inspect_data(self, capacity=None, voltage=None, err_est=False, diff_est=False): """check and inspect the data""" logging.debug("inspecting the data") if capacity is None: capacity = self.capacity if voltage is None: voltage = self.voltage if capacity is None or voltage is None: raise NullData self.len_capacity = len(capacity) self.len_voltage = len(voltage) if self.len_capacity <= 1: raise NullData if self.len_voltage <= 1: raise NullData self.min_capacity, self.max_capacity = value_bounds(capacity) self.start_capacity, self.end_capacity = index_bounds(capacity) self.number_of_points = len(capacity) if diff_est: d_capacity = np.diff(capacity) d_voltage = np.diff(voltage) self.d_capacity_mean = np.mean(d_capacity) self.d_voltage_mean = np.mean(d_voltage) if err_est: splits = int(self.number_of_points / self.points_pr_split) rest = self.number_of_points % self.points_pr_split if splits < self.minimum_splits: txt = "no point in splitting, too little data" logging.debug(txt) self.errors.append("splitting: to few points") else: if rest > 0: _cap = capacity[:-rest] _vol = voltage[:-rest] else: _cap = capacity _vol = voltage c_pieces = np.split(_cap, splits) v_pieces = np.split(_vol, splits) # c_middle = int(np.amax(c_pieces) / 2) std_err = [] c_pieces_avg = [] for c, v in zip(c_pieces, v_pieces): _slope, _intercept, _r_value, _p_value, _std_err = stats.linregress(c, v) std_err.append(_std_err) c_pieces_avg.append(np.mean(c)) self.std_err_median = np.median(std_err) self.std_err_mean = np.mean(std_err) if not self.start_capacity == self.min_capacity: self.errors.append("capacity: start<>min") if not self.end_capacity == self.max_capacity: self.errors.append("capacity: end<>max") if self.normalizing_factor is None: self.normalizing_factor = self.end_capacity if self.normalizing_roof is not None: self.normalizing_factor = self.normalizing_factor * \ self.end_capacity / self.normalizing_roof
python
def inspect_data(self, capacity=None, voltage=None, err_est=False, diff_est=False): """check and inspect the data""" logging.debug("inspecting the data") if capacity is None: capacity = self.capacity if voltage is None: voltage = self.voltage if capacity is None or voltage is None: raise NullData self.len_capacity = len(capacity) self.len_voltage = len(voltage) if self.len_capacity <= 1: raise NullData if self.len_voltage <= 1: raise NullData self.min_capacity, self.max_capacity = value_bounds(capacity) self.start_capacity, self.end_capacity = index_bounds(capacity) self.number_of_points = len(capacity) if diff_est: d_capacity = np.diff(capacity) d_voltage = np.diff(voltage) self.d_capacity_mean = np.mean(d_capacity) self.d_voltage_mean = np.mean(d_voltage) if err_est: splits = int(self.number_of_points / self.points_pr_split) rest = self.number_of_points % self.points_pr_split if splits < self.minimum_splits: txt = "no point in splitting, too little data" logging.debug(txt) self.errors.append("splitting: to few points") else: if rest > 0: _cap = capacity[:-rest] _vol = voltage[:-rest] else: _cap = capacity _vol = voltage c_pieces = np.split(_cap, splits) v_pieces = np.split(_vol, splits) # c_middle = int(np.amax(c_pieces) / 2) std_err = [] c_pieces_avg = [] for c, v in zip(c_pieces, v_pieces): _slope, _intercept, _r_value, _p_value, _std_err = stats.linregress(c, v) std_err.append(_std_err) c_pieces_avg.append(np.mean(c)) self.std_err_median = np.median(std_err) self.std_err_mean = np.mean(std_err) if not self.start_capacity == self.min_capacity: self.errors.append("capacity: start<>min") if not self.end_capacity == self.max_capacity: self.errors.append("capacity: end<>max") if self.normalizing_factor is None: self.normalizing_factor = self.end_capacity if self.normalizing_roof is not None: self.normalizing_factor = self.normalizing_factor * \ self.end_capacity / self.normalizing_roof
[ "def", "inspect_data", "(", "self", ",", "capacity", "=", "None", ",", "voltage", "=", "None", ",", "err_est", "=", "False", ",", "diff_est", "=", "False", ")", ":", "logging", ".", "debug", "(", "\"inspecting the data\"", ")", "if", "capacity", "is", "N...
check and inspect the data
[ "check", "and", "inspect", "the", "data" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L129-L205
train
41,207
jepegit/cellpy
cellpy/utils/ica.py
Converter.increment_data
def increment_data(self): """perform the dq-dv transform""" # NOTE TO ASBJOERN: Probably insert method for "binning" instead of # differentiating here # (use self.increment_method as the variable for selecting method for) logging.debug("incrementing data") # ---- shifting to y-x ---------------------------------------- v1, v2 = value_bounds(self.voltage_preprocessed) if self.voltage_resolution is not None: len_voltage = round(abs(v2 - v1) / self.voltage_resolution, 0) else: len_voltage = len(self.voltage_preprocessed) # ---- interpolating ------------------------------------------ logging.debug(" - interpolating capacity(voltage)") f = interp1d( self.voltage_preprocessed, self.capacity_preprocessed, kind=self.interpolation_method ) self.voltage_inverted = np.linspace(v1, v2, len_voltage) self.voltage_inverted_step = (v2 - v1) / (len_voltage - 1) self.capacity_inverted = f(self.voltage_inverted) if self.smoothing: logging.debug(" - smoothing (savgol filter window)") savgol_filter_window_divisor = np.amin( (self.savgol_filter_window_divisor_default, len_voltage / 5) ) savgol_filter_window_length = int( len(self.voltage_inverted) / savgol_filter_window_divisor ) if savgol_filter_window_length % 2 == 0: savgol_filter_window_length -= 1 self.capacity_inverted = savgol_filter( self.capacity_inverted, np.amax([3, savgol_filter_window_length]), self.savgol_filter_window_order ) # --- diff -------------------- if self.increment_method == "diff": logging.debug(" - diff using DIFF") self.incremental_capacity = np.ediff1d(self.capacity_inverted) / self.voltage_inverted_step self._incremental_capacity = self.incremental_capacity # --- need to adjust voltage --- self._voltage_processed = self.voltage_inverted[1:] self.voltage_processed = self.voltage_inverted[1:] - 0.5 * self.voltage_inverted_step # centering elif self.increment_method == "hist": logging.debug(" - diff using HIST") # TODO: Asbjoern, maybe you can put your method here? raise NotImplementedError
python
def increment_data(self): """perform the dq-dv transform""" # NOTE TO ASBJOERN: Probably insert method for "binning" instead of # differentiating here # (use self.increment_method as the variable for selecting method for) logging.debug("incrementing data") # ---- shifting to y-x ---------------------------------------- v1, v2 = value_bounds(self.voltage_preprocessed) if self.voltage_resolution is not None: len_voltage = round(abs(v2 - v1) / self.voltage_resolution, 0) else: len_voltage = len(self.voltage_preprocessed) # ---- interpolating ------------------------------------------ logging.debug(" - interpolating capacity(voltage)") f = interp1d( self.voltage_preprocessed, self.capacity_preprocessed, kind=self.interpolation_method ) self.voltage_inverted = np.linspace(v1, v2, len_voltage) self.voltage_inverted_step = (v2 - v1) / (len_voltage - 1) self.capacity_inverted = f(self.voltage_inverted) if self.smoothing: logging.debug(" - smoothing (savgol filter window)") savgol_filter_window_divisor = np.amin( (self.savgol_filter_window_divisor_default, len_voltage / 5) ) savgol_filter_window_length = int( len(self.voltage_inverted) / savgol_filter_window_divisor ) if savgol_filter_window_length % 2 == 0: savgol_filter_window_length -= 1 self.capacity_inverted = savgol_filter( self.capacity_inverted, np.amax([3, savgol_filter_window_length]), self.savgol_filter_window_order ) # --- diff -------------------- if self.increment_method == "diff": logging.debug(" - diff using DIFF") self.incremental_capacity = np.ediff1d(self.capacity_inverted) / self.voltage_inverted_step self._incremental_capacity = self.incremental_capacity # --- need to adjust voltage --- self._voltage_processed = self.voltage_inverted[1:] self.voltage_processed = self.voltage_inverted[1:] - 0.5 * self.voltage_inverted_step # centering elif self.increment_method == "hist": logging.debug(" - diff using HIST") # TODO: Asbjoern, maybe you can put your method here? raise NotImplementedError
[ "def", "increment_data", "(", "self", ")", ":", "# NOTE TO ASBJOERN: Probably insert method for \"binning\" instead of", "# differentiating here", "# (use self.increment_method as the variable for selecting method for)", "logging", ".", "debug", "(", "\"incrementing data\"", ")", "# --...
perform the dq-dv transform
[ "perform", "the", "dq", "-", "dv", "transform" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ica.py#L252-L311
train
41,208
openstax/cnx-epub
cnxepub/collation.py
easybake
def easybake(ruleset, in_html, out_html): """This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability. """ html = etree.parse(in_html) oven = Oven(ruleset) oven.bake(html) out_html.write(etree.tostring(html))
python
def easybake(ruleset, in_html, out_html): """This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability. """ html = etree.parse(in_html) oven = Oven(ruleset) oven.bake(html) out_html.write(etree.tostring(html))
[ "def", "easybake", "(", "ruleset", ",", "in_html", ",", "out_html", ")", ":", "html", "=", "etree", ".", "parse", "(", "in_html", ")", "oven", "=", "Oven", "(", "ruleset", ")", "oven", ".", "bake", "(", "html", ")", "out_html", ".", "write", "(", "...
This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability.
[ "This", "adheres", "to", "the", "same", "interface", "as", "cnxeasybake", ".", "scripts", ".", "main", ".", "easyback", ".", "ruleset", "is", "a", "string", "containing", "the", "ruleset", "CSS", "while", "in_html", "and", "out_html", "are", "file", "-", "...
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/collation.py#L28-L39
train
41,209
openstax/cnx-epub
cnxepub/collation.py
reconstitute
def reconstitute(html): """Given a file-like object as ``html``, reconstruct it into models.""" try: htree = etree.parse(html) except etree.XMLSyntaxError: html.seek(0) htree = etree.HTML(html.read()) xhtml = etree.tostring(htree, encoding='utf-8') return adapt_single_html(xhtml)
python
def reconstitute(html): """Given a file-like object as ``html``, reconstruct it into models.""" try: htree = etree.parse(html) except etree.XMLSyntaxError: html.seek(0) htree = etree.HTML(html.read()) xhtml = etree.tostring(htree, encoding='utf-8') return adapt_single_html(xhtml)
[ "def", "reconstitute", "(", "html", ")", ":", "try", ":", "htree", "=", "etree", ".", "parse", "(", "html", ")", "except", "etree", ".", "XMLSyntaxError", ":", "html", ".", "seek", "(", "0", ")", "htree", "=", "etree", ".", "HTML", "(", "html", "."...
Given a file-like object as ``html``, reconstruct it into models.
[ "Given", "a", "file", "-", "like", "object", "as", "html", "reconstruct", "it", "into", "models", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/collation.py#L42-L51
train
41,210
openstax/cnx-epub
cnxepub/collation.py
collate
def collate(binder, ruleset=None, includes=None): """Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder. """ html_formatter = SingleHTMLFormatter(binder, includes) raw_html = io.BytesIO(bytes(html_formatter)) collated_html = io.BytesIO() if ruleset is None: # No ruleset found, so no cooking necessary. return binder easybake(ruleset, raw_html, collated_html) collated_html.seek(0) collated_binder = reconstitute(collated_html) return collated_binder
python
def collate(binder, ruleset=None, includes=None): """Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder. """ html_formatter = SingleHTMLFormatter(binder, includes) raw_html = io.BytesIO(bytes(html_formatter)) collated_html = io.BytesIO() if ruleset is None: # No ruleset found, so no cooking necessary. return binder easybake(ruleset, raw_html, collated_html) collated_html.seek(0) collated_binder = reconstitute(collated_html) return collated_binder
[ "def", "collate", "(", "binder", ",", "ruleset", "=", "None", ",", "includes", "=", "None", ")", ":", "html_formatter", "=", "SingleHTMLFormatter", "(", "binder", ",", "includes", ")", "raw_html", "=", "io", ".", "BytesIO", "(", "bytes", "(", "html_formatt...
Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder.
[ "Given", "a", "Binder", "as", "binder", "collate", "the", "content", "into", "a", "new", "set", "of", "models", ".", "Returns", "the", "collated", "binder", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/collation.py#L54-L73
train
41,211
openstax/cnx-epub
cnxepub/adapters.py
adapt_package
def adapt_package(package): """Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``. """ navigation_item = package.navigation html = etree.parse(navigation_item.data) tree = parse_navigation_html_to_tree(html, navigation_item.name) return _node_to_model(tree, package)
python
def adapt_package(package): """Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``. """ navigation_item = package.navigation html = etree.parse(navigation_item.data) tree = parse_navigation_html_to_tree(html, navigation_item.name) return _node_to_model(tree, package)
[ "def", "adapt_package", "(", "package", ")", ":", "navigation_item", "=", "package", ".", "navigation", "html", "=", "etree", ".", "parse", "(", "navigation_item", ".", "data", ")", "tree", "=", "parse_navigation_html_to_tree", "(", "html", ",", "navigation_item...
Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``.
[ "Adapts", ".", "epub", ".", "Package", "to", "a", "BinderItem", "and", "cascades", "the", "adaptation", "downward", "to", "DocumentItem", "and", "ResourceItem", ".", "The", "results", "of", "this", "process", "provide", "the", "same", "interface", "as", ".", ...
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L58-L68
train
41,212
openstax/cnx-epub
cnxepub/adapters.py
adapt_item
def adapt_item(item, package, filename=None): """Adapts ``.epub.Item`` to a ``DocumentItem``. """ if item.media_type == 'application/xhtml+xml': try: html = etree.parse(item.data) except Exception as exc: logger.error("failed parsing {}".format(item.name)) raise metadata = DocumentPointerMetadataParser( html, raise_value_error=False)() item.data.seek(0) if metadata.get('is_document_pointer'): model = DocumentPointerItem(item, package) else: model = DocumentItem(item, package) else: model = Resource(item.name, item.data, item.media_type, filename or item.name) return model
python
def adapt_item(item, package, filename=None): """Adapts ``.epub.Item`` to a ``DocumentItem``. """ if item.media_type == 'application/xhtml+xml': try: html = etree.parse(item.data) except Exception as exc: logger.error("failed parsing {}".format(item.name)) raise metadata = DocumentPointerMetadataParser( html, raise_value_error=False)() item.data.seek(0) if metadata.get('is_document_pointer'): model = DocumentPointerItem(item, package) else: model = DocumentItem(item, package) else: model = Resource(item.name, item.data, item.media_type, filename or item.name) return model
[ "def", "adapt_item", "(", "item", ",", "package", ",", "filename", "=", "None", ")", ":", "if", "item", ".", "media_type", "==", "'application/xhtml+xml'", ":", "try", ":", "html", "=", "etree", ".", "parse", "(", "item", ".", "data", ")", "except", "E...
Adapts ``.epub.Item`` to a ``DocumentItem``.
[ "Adapts", ".", "epub", ".", "Item", "to", "a", "DocumentItem", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L71-L91
train
41,213
openstax/cnx-epub
cnxepub/adapters.py
_make_package
def _make_package(binder): """Makes an ``.epub.Package`` from a Binder'ish instance.""" package_id = binder.id if package_id is None: package_id = hash(binder) package_name = "{}.opf".format(package_id) extensions = get_model_extensions(binder) template_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) # Build the package item list. items = [] # Build the binder as an item, specifically a navigation item. navigation_document = bytes(HTMLFormatter(binder, extensions)) navigation_document_name = "{}{}".format( package_id, mimetypes.guess_extension('application/xhtml+xml', strict=False)) item = Item(str(navigation_document_name), io.BytesIO(navigation_document), 'application/xhtml+xml', is_navigation=True, properties=['nav']) items.append(item) resources = {} # Roll through the model list again, making each one an item. for model in flatten_model(binder): for resource in getattr(model, 'resources', []): resources[resource.id] = resource with resource.open() as data: item = Item(resource.id, data, resource.media_type) items.append(item) if isinstance(model, (Binder, TranslucentBinder,)): continue if isinstance(model, DocumentPointer): content = bytes(HTMLFormatter(model)) item = Item(''.join([model.ident_hash, extensions[model.id]]), io.BytesIO(content), model.media_type) items.append(item) continue for reference in model.references: if reference.remote_type == INLINE_REFERENCE_TYPE: # has side effects - converts ref type to INTERNAL w/ # appropriate uri, so need to replicate resource treatment from # above resource = _make_resource_from_inline(reference) model.resources.append(resource) resources[resource.id] = resource with resource.open() as data: item = Item(resource.id, data, resource.media_type) items.append(item) reference.bind(resource, '../resources/{}') elif reference.remote_type == INTERNAL_REFERENCE_TYPE: filename = os.path.basename(reference.uri) resource = resources.get(filename) if resource: reference.bind(resource, '../resources/{}') complete_content = bytes(HTMLFormatter(model)) item = Item(''.join([model.ident_hash, extensions[model.id]]), io.BytesIO(complete_content), model.media_type) items.append(item) # Build the package. package = Package(package_name, items, binder.metadata) return package
python
def _make_package(binder): """Makes an ``.epub.Package`` from a Binder'ish instance.""" package_id = binder.id if package_id is None: package_id = hash(binder) package_name = "{}.opf".format(package_id) extensions = get_model_extensions(binder) template_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) # Build the package item list. items = [] # Build the binder as an item, specifically a navigation item. navigation_document = bytes(HTMLFormatter(binder, extensions)) navigation_document_name = "{}{}".format( package_id, mimetypes.guess_extension('application/xhtml+xml', strict=False)) item = Item(str(navigation_document_name), io.BytesIO(navigation_document), 'application/xhtml+xml', is_navigation=True, properties=['nav']) items.append(item) resources = {} # Roll through the model list again, making each one an item. for model in flatten_model(binder): for resource in getattr(model, 'resources', []): resources[resource.id] = resource with resource.open() as data: item = Item(resource.id, data, resource.media_type) items.append(item) if isinstance(model, (Binder, TranslucentBinder,)): continue if isinstance(model, DocumentPointer): content = bytes(HTMLFormatter(model)) item = Item(''.join([model.ident_hash, extensions[model.id]]), io.BytesIO(content), model.media_type) items.append(item) continue for reference in model.references: if reference.remote_type == INLINE_REFERENCE_TYPE: # has side effects - converts ref type to INTERNAL w/ # appropriate uri, so need to replicate resource treatment from # above resource = _make_resource_from_inline(reference) model.resources.append(resource) resources[resource.id] = resource with resource.open() as data: item = Item(resource.id, data, resource.media_type) items.append(item) reference.bind(resource, '../resources/{}') elif reference.remote_type == INTERNAL_REFERENCE_TYPE: filename = os.path.basename(reference.uri) resource = resources.get(filename) if resource: reference.bind(resource, '../resources/{}') complete_content = bytes(HTMLFormatter(model)) item = Item(''.join([model.ident_hash, extensions[model.id]]), io.BytesIO(complete_content), model.media_type) items.append(item) # Build the package. package = Package(package_name, items, binder.metadata) return package
[ "def", "_make_package", "(", "binder", ")", ":", "package_id", "=", "binder", ".", "id", "if", "package_id", "is", "None", ":", "package_id", "=", "hash", "(", "binder", ")", "package_name", "=", "\"{}.opf\"", ".", "format", "(", "package_id", ")", "extens...
Makes an ``.epub.Package`` from a Binder'ish instance.
[ "Makes", "an", ".", "epub", ".", "Package", "from", "a", "Binder", "ish", "instance", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L136-L205
train
41,214
openstax/cnx-epub
cnxepub/adapters.py
_make_item
def _make_item(model): """Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource`` """ item = Item(model.id, model.content, model.media_type) return item
python
def _make_item(model): """Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource`` """ item = Item(model.id, model.content, model.media_type) return item
[ "def", "_make_item", "(", "model", ")", ":", "item", "=", "Item", "(", "model", ".", "id", ",", "model", ".", "content", ",", "model", ".", "media_type", ")", "return", "item" ]
Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource``
[ "Makes", "an", ".", "epub", ".", "Item", "from", "a", ".", "models", ".", "Document", "or", ".", "models", ".", "Resource" ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L219-L224
train
41,215
openstax/cnx-epub
cnxepub/adapters.py
_node_to_model
def _node_to_model(tree_or_item, package, parent=None, lucent_id=TRANSLUCENT_BINDER_ID): """Given a tree, parse to a set of models""" if 'contents' in tree_or_item: # It is a binder. tree = tree_or_item # Grab the package metadata, so we have required license info metadata = package.metadata.copy() if tree['id'] == lucent_id: metadata['title'] = tree['title'] binder = TranslucentBinder(metadata=metadata) else: try: package_item = package.grab_by_name(tree['id']) binder = BinderItem(package_item, package) except KeyError: # Translucent w/ id metadata.update({ 'title': tree['title'], 'cnx-archive-uri': tree['id'], 'cnx-archive-shortid': tree['shortId']}) binder = Binder(tree['id'], metadata=metadata) for item in tree['contents']: node = _node_to_model(item, package, parent=binder, lucent_id=lucent_id) if node.metadata['title'] != item['title']: binder.set_title_for_node(node, item['title']) result = binder else: # It is a document. item = tree_or_item package_item = package.grab_by_name(item['id']) result = adapt_item(package_item, package) if parent is not None: parent.append(result) return result
python
def _node_to_model(tree_or_item, package, parent=None, lucent_id=TRANSLUCENT_BINDER_ID): """Given a tree, parse to a set of models""" if 'contents' in tree_or_item: # It is a binder. tree = tree_or_item # Grab the package metadata, so we have required license info metadata = package.metadata.copy() if tree['id'] == lucent_id: metadata['title'] = tree['title'] binder = TranslucentBinder(metadata=metadata) else: try: package_item = package.grab_by_name(tree['id']) binder = BinderItem(package_item, package) except KeyError: # Translucent w/ id metadata.update({ 'title': tree['title'], 'cnx-archive-uri': tree['id'], 'cnx-archive-shortid': tree['shortId']}) binder = Binder(tree['id'], metadata=metadata) for item in tree['contents']: node = _node_to_model(item, package, parent=binder, lucent_id=lucent_id) if node.metadata['title'] != item['title']: binder.set_title_for_node(node, item['title']) result = binder else: # It is a document. item = tree_or_item package_item = package.grab_by_name(item['id']) result = adapt_item(package_item, package) if parent is not None: parent.append(result) return result
[ "def", "_node_to_model", "(", "tree_or_item", ",", "package", ",", "parent", "=", "None", ",", "lucent_id", "=", "TRANSLUCENT_BINDER_ID", ")", ":", "if", "'contents'", "in", "tree_or_item", ":", "# It is a binder.", "tree", "=", "tree_or_item", "# Grab the package m...
Given a tree, parse to a set of models
[ "Given", "a", "tree", "parse", "to", "a", "set", "of", "models" ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L227-L261
train
41,216
openstax/cnx-epub
cnxepub/adapters.py
adapt_single_html
def adapt_single_html(html): """Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder`` """ html_root = etree.fromstring(html) metadata = parse_metadata(html_root.xpath('//*[@data-type="metadata"]')[0]) id_ = metadata['cnx-archive-uri'] or 'book' binder = Binder(id_, metadata=metadata) nav_tree = parse_navigation_html_to_tree(html_root, id_) body = html_root.xpath('//xhtml:body', namespaces=HTML_DOCUMENT_NAMESPACES) _adapt_single_html_tree(binder, body[0], nav_tree, top_metadata=metadata) return binder
python
def adapt_single_html(html): """Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder`` """ html_root = etree.fromstring(html) metadata = parse_metadata(html_root.xpath('//*[@data-type="metadata"]')[0]) id_ = metadata['cnx-archive-uri'] or 'book' binder = Binder(id_, metadata=metadata) nav_tree = parse_navigation_html_to_tree(html_root, id_) body = html_root.xpath('//xhtml:body', namespaces=HTML_DOCUMENT_NAMESPACES) _adapt_single_html_tree(binder, body[0], nav_tree, top_metadata=metadata) return binder
[ "def", "adapt_single_html", "(", "html", ")", ":", "html_root", "=", "etree", ".", "fromstring", "(", "html", ")", "metadata", "=", "parse_metadata", "(", "html_root", ".", "xpath", "(", "'//*[@data-type=\"metadata\"]'", ")", "[", "0", "]", ")", "id_", "=", ...
Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder``
[ "Adapts", "a", "single", "html", "document", "generated", "by", ".", "formatters", ".", "SingleHTMLFormatter", "to", "a", "models", ".", "Binder" ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/adapters.py#L346-L361
train
41,217
jepegit/cellpy
cellpy/utils/ocv_rlx.py
MultiCycleOcvFit.get_best_fit_parameters_grouped
def get_best_fit_parameters_grouped(self): """Returns a dictionary of the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters] for i in range(self.circuits): result_dict['t' + str(i)] = [parameters['t' + str(i)] for parameters in self.best_fit_parameters] result_dict['w' + str(i)] = [parameters['w' + str(i)] for parameters in self.best_fit_parameters] return result_dict
python
def get_best_fit_parameters_grouped(self): """Returns a dictionary of the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters] for i in range(self.circuits): result_dict['t' + str(i)] = [parameters['t' + str(i)] for parameters in self.best_fit_parameters] result_dict['w' + str(i)] = [parameters['w' + str(i)] for parameters in self.best_fit_parameters] return result_dict
[ "def", "get_best_fit_parameters_grouped", "(", "self", ")", ":", "result_dict", "=", "dict", "(", ")", "result_dict", "[", "'ocv'", "]", "=", "[", "parameters", "[", "'ocv'", "]", "for", "parameters", "in", "self", ".", "best_fit_parameters", "]", "for", "i"...
Returns a dictionary of the best fit.
[ "Returns", "a", "dictionary", "of", "the", "best", "fit", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ocv_rlx.py#L312-L323
train
41,218
jepegit/cellpy
cellpy/utils/ocv_rlx.py
MultiCycleOcvFit.get_best_fit_parameters_translated_grouped
def get_best_fit_parameters_translated_grouped(self): """Returns the parameters as a dictionary of the 'real units' for the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters_translated] result_dict['ir'] = [parameters['ir'] for parameters in self.best_fit_parameters_translated] for i in range(self.circuits): result_dict['r' + str(i)] = [parameters['r' + str(i)] for parameters in self.best_fit_parameters_translated] result_dict['c' + str(i)] = [parameters['c' + str(i)] for parameters in self.best_fit_parameters_translated] return result_dict
python
def get_best_fit_parameters_translated_grouped(self): """Returns the parameters as a dictionary of the 'real units' for the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters_translated] result_dict['ir'] = [parameters['ir'] for parameters in self.best_fit_parameters_translated] for i in range(self.circuits): result_dict['r' + str(i)] = [parameters['r' + str(i)] for parameters in self.best_fit_parameters_translated] result_dict['c' + str(i)] = [parameters['c' + str(i)] for parameters in self.best_fit_parameters_translated] return result_dict
[ "def", "get_best_fit_parameters_translated_grouped", "(", "self", ")", ":", "result_dict", "=", "dict", "(", ")", "result_dict", "[", "'ocv'", "]", "=", "[", "parameters", "[", "'ocv'", "]", "for", "parameters", "in", "self", ".", "best_fit_parameters_translated",...
Returns the parameters as a dictionary of the 'real units' for the best fit.
[ "Returns", "the", "parameters", "as", "a", "dictionary", "of", "the", "real", "units", "for", "the", "best", "fit", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ocv_rlx.py#L325-L338
train
41,219
jepegit/cellpy
cellpy/utils/ocv_rlx.py
MultiCycleOcvFit.plot_summary
def plot_summary(self, cycles=None): """Convenience function for plotting the summary of the fit""" if cycles is None: cycles = [0] fig1 = plt.figure() ax1 = fig1.add_subplot(221) ax1.set_title('Fit') ax2 = fig1.add_subplot(222) ax2.set_title('OCV') ax3 = fig1.add_subplot(223) ax3.set_title('Tau') ax3.set_yscale("log") ax4 = fig1.add_subplot(224) ax4.set_title('Voltage Impact') plot_data = self.get_best_fit_data() for cycle in cycles: ax1.plot(plot_data[cycle][0], plot_data[cycle][1]) ax1.plot(plot_data[cycle][0], plot_data[cycle][2]) plot_data = self.get_best_fit_parameters_grouped() for i in range(self.circuits): ax3.plot(self.get_fit_cycles(), plot_data['t' + str(i)]) ax4.plot(self.get_fit_cycles(), plot_data['w' + str(i)]) ax2.plot(self.get_fit_cycles(), plot_data['ocv'])
python
def plot_summary(self, cycles=None): """Convenience function for plotting the summary of the fit""" if cycles is None: cycles = [0] fig1 = plt.figure() ax1 = fig1.add_subplot(221) ax1.set_title('Fit') ax2 = fig1.add_subplot(222) ax2.set_title('OCV') ax3 = fig1.add_subplot(223) ax3.set_title('Tau') ax3.set_yscale("log") ax4 = fig1.add_subplot(224) ax4.set_title('Voltage Impact') plot_data = self.get_best_fit_data() for cycle in cycles: ax1.plot(plot_data[cycle][0], plot_data[cycle][1]) ax1.plot(plot_data[cycle][0], plot_data[cycle][2]) plot_data = self.get_best_fit_parameters_grouped() for i in range(self.circuits): ax3.plot(self.get_fit_cycles(), plot_data['t' + str(i)]) ax4.plot(self.get_fit_cycles(), plot_data['w' + str(i)]) ax2.plot(self.get_fit_cycles(), plot_data['ocv'])
[ "def", "plot_summary", "(", "self", ",", "cycles", "=", "None", ")", ":", "if", "cycles", "is", "None", ":", "cycles", "=", "[", "0", "]", "fig1", "=", "plt", ".", "figure", "(", ")", "ax1", "=", "fig1", ".", "add_subplot", "(", "221", ")", "ax1"...
Convenience function for plotting the summary of the fit
[ "Convenience", "function", "for", "plotting", "the", "summary", "of", "the", "fit" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/ocv_rlx.py#L344-L370
train
41,220
openstax/cnx-epub
cnxepub/html_parsers.py
parse_resources
def parse_resources(html): """Return a list of resource names found in the html metadata section.""" xpath = '//*[@data-type="resources"]//xhtml:li/xhtml:a' for resource in html.xpath(xpath, namespaces=HTML_DOCUMENT_NAMESPACES): yield { 'id': resource.get('href'), 'filename': resource.text.strip(), }
python
def parse_resources(html): """Return a list of resource names found in the html metadata section.""" xpath = '//*[@data-type="resources"]//xhtml:li/xhtml:a' for resource in html.xpath(xpath, namespaces=HTML_DOCUMENT_NAMESPACES): yield { 'id': resource.get('href'), 'filename': resource.text.strip(), }
[ "def", "parse_resources", "(", "html", ")", ":", "xpath", "=", "'//*[@data-type=\"resources\"]//xhtml:li/xhtml:a'", "for", "resource", "in", "html", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "HTML_DOCUMENT_NAMESPACES", ")", ":", "yield", "{", "'id'", ":"...
Return a list of resource names found in the html metadata section.
[ "Return", "a", "list", "of", "resource", "names", "found", "in", "the", "html", "metadata", "section", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/html_parsers.py#L77-L84
train
41,221
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager.on_connect
def on_connect(self, client, userdata, flags, rc): ''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` constructor or :func:`paho.mqtt.client.Client.userdata_set`. flags : dict Response flags sent by the broker. The flag ``flags['session present']`` is useful for clients that are using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists. rc : int The connection result. The value of rc indicates success or not: - 0: Connection successful - 1: Connection refused - incorrect protocol version - 2: Connection refused - invalid client identifier - 3: Connection refused - server unavailable - 4: Connection refused - bad username or password - 5: Connection refused - not authorised - 6-255: Currently unused. Notes ----- Subscriptions should be defined in this method to ensure subscriptions will be renewed upon reconnecting after a loss of connection. ''' super(SerialDeviceManager, self).on_connect(client, userdata, flags, rc) if rc == 0: self.mqtt_client.subscribe('serial_device/+/connect') self.mqtt_client.subscribe('serial_device/+/send') self.mqtt_client.subscribe('serial_device/+/close') self.mqtt_client.subscribe('serial_device/refresh_comports') self.refresh_comports()
python
def on_connect(self, client, userdata, flags, rc): ''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` constructor or :func:`paho.mqtt.client.Client.userdata_set`. flags : dict Response flags sent by the broker. The flag ``flags['session present']`` is useful for clients that are using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists. rc : int The connection result. The value of rc indicates success or not: - 0: Connection successful - 1: Connection refused - incorrect protocol version - 2: Connection refused - invalid client identifier - 3: Connection refused - server unavailable - 4: Connection refused - bad username or password - 5: Connection refused - not authorised - 6-255: Currently unused. Notes ----- Subscriptions should be defined in this method to ensure subscriptions will be renewed upon reconnecting after a loss of connection. ''' super(SerialDeviceManager, self).on_connect(client, userdata, flags, rc) if rc == 0: self.mqtt_client.subscribe('serial_device/+/connect') self.mqtt_client.subscribe('serial_device/+/send') self.mqtt_client.subscribe('serial_device/+/close') self.mqtt_client.subscribe('serial_device/refresh_comports') self.refresh_comports()
[ "def", "on_connect", "(", "self", ",", "client", ",", "userdata", ",", "flags", ",", "rc", ")", ":", "super", "(", "SerialDeviceManager", ",", "self", ")", ".", "on_connect", "(", "client", ",", "userdata", ",", "flags", ",", "rc", ")", "if", "rc", "...
Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` constructor or :func:`paho.mqtt.client.Client.userdata_set`. flags : dict Response flags sent by the broker. The flag ``flags['session present']`` is useful for clients that are using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists. rc : int The connection result. The value of rc indicates success or not: - 0: Connection successful - 1: Connection refused - incorrect protocol version - 2: Connection refused - invalid client identifier - 3: Connection refused - server unavailable - 4: Connection refused - bad username or password - 5: Connection refused - not authorised - 6-255: Currently unused. Notes ----- Subscriptions should be defined in this method to ensure subscriptions will be renewed upon reconnecting after a loss of connection.
[ "Callback", "for", "when", "the", "client", "receives", "a", "CONNACK", "response", "from", "the", "broker", "." ]
5de1c3fc447ae829b57d80073ec6ac4fba3283c6
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L57-L106
train
41,222
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager.on_message
def on_message(self, client, userdata, msg): ''' Callback for when a ``PUBLISH`` message is received from the broker. ''' if msg.topic == 'serial_device/refresh_comports': self.refresh_comports() return match = CRE_MANAGER.match(msg.topic) if match is None: logger.debug('Topic NOT matched: `%s`', msg.topic) else: logger.debug('Topic matched: `%s`', msg.topic) # Message topic matches command. Handle request. command = match.group('command') port = match.group('port') # serial_device/<port>/send # Bytes to send if command == 'send': self._serial_send(port, msg.payload) elif command == 'connect': # serial_device/<port>/connect # Request connection try: request = json.loads(msg.payload) except ValueError as exception: logger.error('Error decoding "%s (%s)" request: %s', command, port, exception) return self._serial_connect(port, request) elif command == 'close': self._serial_close(port)
python
def on_message(self, client, userdata, msg): ''' Callback for when a ``PUBLISH`` message is received from the broker. ''' if msg.topic == 'serial_device/refresh_comports': self.refresh_comports() return match = CRE_MANAGER.match(msg.topic) if match is None: logger.debug('Topic NOT matched: `%s`', msg.topic) else: logger.debug('Topic matched: `%s`', msg.topic) # Message topic matches command. Handle request. command = match.group('command') port = match.group('port') # serial_device/<port>/send # Bytes to send if command == 'send': self._serial_send(port, msg.payload) elif command == 'connect': # serial_device/<port>/connect # Request connection try: request = json.loads(msg.payload) except ValueError as exception: logger.error('Error decoding "%s (%s)" request: %s', command, port, exception) return self._serial_connect(port, request) elif command == 'close': self._serial_close(port)
[ "def", "on_message", "(", "self", ",", "client", ",", "userdata", ",", "msg", ")", ":", "if", "msg", ".", "topic", "==", "'serial_device/refresh_comports'", ":", "self", ".", "refresh_comports", "(", ")", "return", "match", "=", "CRE_MANAGER", ".", "match", ...
Callback for when a ``PUBLISH`` message is received from the broker.
[ "Callback", "for", "when", "a", "PUBLISH", "message", "is", "received", "from", "the", "broker", "." ]
5de1c3fc447ae829b57d80073ec6ac4fba3283c6
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L108-L138
train
41,223
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._publish_status
def _publish_status(self, port): ''' Publish status for specified port. Parameters ---------- port : str Device name/port. ''' if port not in self.open_devices: status = {} else: device = self.open_devices[port].serial properties = ('port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout', 'xonxoff', 'rtscts', 'dsrdtr') status = {k: getattr(device, k) for k in properties} status_json = json.dumps(status) self.mqtt_client.publish(topic='serial_device/%s/status' % port, payload=status_json, retain=True)
python
def _publish_status(self, port): ''' Publish status for specified port. Parameters ---------- port : str Device name/port. ''' if port not in self.open_devices: status = {} else: device = self.open_devices[port].serial properties = ('port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout', 'xonxoff', 'rtscts', 'dsrdtr') status = {k: getattr(device, k) for k in properties} status_json = json.dumps(status) self.mqtt_client.publish(topic='serial_device/%s/status' % port, payload=status_json, retain=True)
[ "def", "_publish_status", "(", "self", ",", "port", ")", ":", "if", "port", "not", "in", "self", ".", "open_devices", ":", "status", "=", "{", "}", "else", ":", "device", "=", "self", ".", "open_devices", "[", "port", "]", ".", "serial", "properties", ...
Publish status for specified port. Parameters ---------- port : str Device name/port.
[ "Publish", "status", "for", "specified", "port", "." ]
5de1c3fc447ae829b57d80073ec6ac4fba3283c6
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L142-L160
train
41,224
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._serial_close
def _serial_close(self, port): ''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: logger.error('Error closing device `%s`: %s', port, exception) return else: logger.debug('Device not connected to `%s`', port) self._publish_status(port) return
python
def _serial_close(self, port): ''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: logger.error('Error closing device `%s`: %s', port, exception) return else: logger.debug('Device not connected to `%s`', port) self._publish_status(port) return
[ "def", "_serial_close", "(", "self", ",", "port", ")", ":", "if", "port", "in", "self", ".", "open_devices", ":", "try", ":", "self", ".", "open_devices", "[", "port", "]", ".", "close", "(", ")", "except", "Exception", "as", "exception", ":", "logger"...
Handle close request. Parameters ---------- port : str Device name/port.
[ "Handle", "close", "request", "." ]
5de1c3fc447ae829b57d80073ec6ac4fba3283c6
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L162-L180
train
41,225
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._serial_send
def _serial_send(self, port, payload): ''' Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device. ''' if port not in self.open_devices: # Not connected to device. logger.error('Error sending data: `%s` not connected', port) self._publish_status(port) else: try: device = self.open_devices[port] device.write(payload) logger.debug('Sent data to `%s`', port) except Exception as exception: logger.error('Error sending data to `%s`: %s', port, exception)
python
def _serial_send(self, port, payload): ''' Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device. ''' if port not in self.open_devices: # Not connected to device. logger.error('Error sending data: `%s` not connected', port) self._publish_status(port) else: try: device = self.open_devices[port] device.write(payload) logger.debug('Sent data to `%s`', port) except Exception as exception: logger.error('Error sending data to `%s`: %s', port, exception)
[ "def", "_serial_send", "(", "self", ",", "port", ",", "payload", ")", ":", "if", "port", "not", "in", "self", ".", "open_devices", ":", "# Not connected to device.", "logger", ".", "error", "(", "'Error sending data: `%s` not connected'", ",", "port", ")", "self...
Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device.
[ "Send", "data", "to", "connected", "device", "." ]
5de1c3fc447ae829b57d80073ec6ac4fba3283c6
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L326-L347
train
41,226
jepegit/cellpy
dev_utils/parsing_binary.py
print_datetime_object
def print_datetime_object(dt): """prints a date-object""" print(dt) print('ctime :', dt.ctime()) print('tuple :', dt.timetuple()) print('ordinal:', dt.toordinal()) print('Year :', dt.year) print('Mon :', dt.month) print('Day :', dt.day)
python
def print_datetime_object(dt): """prints a date-object""" print(dt) print('ctime :', dt.ctime()) print('tuple :', dt.timetuple()) print('ordinal:', dt.toordinal()) print('Year :', dt.year) print('Mon :', dt.month) print('Day :', dt.day)
[ "def", "print_datetime_object", "(", "dt", ")", ":", "print", "(", "dt", ")", "print", "(", "'ctime :'", ",", "dt", ".", "ctime", "(", ")", ")", "print", "(", "'tuple :'", ",", "dt", ".", "timetuple", "(", ")", ")", "print", "(", "'ordinal:'", ",",...
prints a date-object
[ "prints", "a", "date", "-", "object" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/dev_utils/parsing_binary.py#L21-L29
train
41,227
jepegit/cellpy
cellpy/readers/core.py
check64bit
def check64bit(current_system="python"): """checks if you are on a 64 bit platform""" if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not Iron) return True else: if 'PROCESSOR_ARCHITEW6432' in os.environ: return True # 32 bit program running on 64 bit Windows try: # 64 bit Windows 64 bit program return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64') except IndexError: pass # not Windows try: # this often works in Linux return '64' in platform.architecture()[0] except Exception: # is an older version of Python, assume also an older os@ # (best we can guess) return False
python
def check64bit(current_system="python"): """checks if you are on a 64 bit platform""" if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not Iron) return True else: if 'PROCESSOR_ARCHITEW6432' in os.environ: return True # 32 bit program running on 64 bit Windows try: # 64 bit Windows 64 bit program return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64') except IndexError: pass # not Windows try: # this often works in Linux return '64' in platform.architecture()[0] except Exception: # is an older version of Python, assume also an older os@ # (best we can guess) return False
[ "def", "check64bit", "(", "current_system", "=", "\"python\"", ")", ":", "if", "current_system", "==", "\"python\"", ":", "return", "sys", ".", "maxsize", ">", "2147483647", "elif", "current_system", "==", "\"os\"", ":", "import", "platform", "pm", "=", "platf...
checks if you are on a 64 bit platform
[ "checks", "if", "you", "are", "on", "a", "64", "bit", "platform" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L269-L292
train
41,228
jepegit/cellpy
cellpy/readers/core.py
humanize_bytes
def humanize_bytes(b, precision=1): """Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12342,2) '12.05 MB' >>> humanize_bytes(1024*1234,2) '1.21 MB' >>> humanize_bytes(1024*1234*1111,2) '1.31 GB' >>> humanize_bytes(1024*1234*1111,1) '1.3 GB' """ # abbrevs = ( # (1 << 50L, 'PB'), # (1 << 40L, 'TB'), # (1 << 30L, 'GB'), # (1 << 20L, 'MB'), # (1 << 10L, 'kB'), # (1, 'b') # ) abbrevs = ( (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'b') ) if b == 1: return '1 byte' for factor, suffix in abbrevs: if b >= factor: break # return '%.*f %s' % (precision, old_div(b, factor), suffix) return '%.*f %s' % (precision, b // factor, suffix)
python
def humanize_bytes(b, precision=1): """Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12342,2) '12.05 MB' >>> humanize_bytes(1024*1234,2) '1.21 MB' >>> humanize_bytes(1024*1234*1111,2) '1.31 GB' >>> humanize_bytes(1024*1234*1111,1) '1.3 GB' """ # abbrevs = ( # (1 << 50L, 'PB'), # (1 << 40L, 'TB'), # (1 << 30L, 'GB'), # (1 << 20L, 'MB'), # (1 << 10L, 'kB'), # (1, 'b') # ) abbrevs = ( (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'b') ) if b == 1: return '1 byte' for factor, suffix in abbrevs: if b >= factor: break # return '%.*f %s' % (precision, old_div(b, factor), suffix) return '%.*f %s' % (precision, b // factor, suffix)
[ "def", "humanize_bytes", "(", "b", ",", "precision", "=", "1", ")", ":", "# abbrevs = (", "# (1 << 50L, 'PB'),", "# (1 << 40L, 'TB'),", "# (1 << 30L, 'GB'),", "# (1 << 20L, 'MB'),", "# (1 << 10L, 'kB'),", "# (1, 'b')", "# )", "abbrevs", "=", "(", "("...
Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12342,2) '12.05 MB' >>> humanize_bytes(1024*1234,2) '1.21 MB' >>> humanize_bytes(1024*1234*1111,2) '1.31 GB' >>> humanize_bytes(1024*1234*1111,1) '1.3 GB'
[ "Return", "a", "humanized", "string", "representation", "of", "a", "number", "of", "b", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L295-L339
train
41,229
jepegit/cellpy
cellpy/readers/core.py
xldate_as_datetime
def xldate_as_datetime(xldate, datemode=0, option="to_datetime"): """Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object, float, or string). """ # This does not work for numpy-arrays if option == "to_float": d = (xldate - 25589) * 86400.0 else: try: d = datetime.datetime(1899, 12, 30) + \ datetime.timedelta(days=xldate + 1462 * datemode) # date_format = "%Y-%m-%d %H:%M:%S:%f" # with microseconds, # excel cannot cope with this! if option == "to_string": date_format = "%Y-%m-%d %H:%M:%S" # without microseconds d = d.strftime(date_format) except TypeError: logging.info(f'The date is not of correct type [{xldate}]') d = xldate return d
python
def xldate_as_datetime(xldate, datemode=0, option="to_datetime"): """Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object, float, or string). """ # This does not work for numpy-arrays if option == "to_float": d = (xldate - 25589) * 86400.0 else: try: d = datetime.datetime(1899, 12, 30) + \ datetime.timedelta(days=xldate + 1462 * datemode) # date_format = "%Y-%m-%d %H:%M:%S:%f" # with microseconds, # excel cannot cope with this! if option == "to_string": date_format = "%Y-%m-%d %H:%M:%S" # without microseconds d = d.strftime(date_format) except TypeError: logging.info(f'The date is not of correct type [{xldate}]') d = xldate return d
[ "def", "xldate_as_datetime", "(", "xldate", ",", "datemode", "=", "0", ",", "option", "=", "\"to_datetime\"", ")", ":", "# This does not work for numpy-arrays", "if", "option", "==", "\"to_float\"", ":", "d", "=", "(", "xldate", "-", "25589", ")", "*", "86400....
Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object, float, or string).
[ "Converts", "a", "xls", "date", "stamp", "to", "a", "more", "sensible", "format", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L342-L372
train
41,230
jepegit/cellpy
cellpy/readers/core.py
FileID.populate
def populate(self, filename): """Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file. """ if os.path.isfile(filename): fid_st = os.stat(filename) self.name = os.path.abspath(filename) self.full_name = filename self.size = fid_st.st_size self.last_modified = fid_st.st_mtime self.last_accessed = fid_st.st_atime self.last_info_changed = fid_st.st_ctime self.location = os.path.dirname(filename)
python
def populate(self, filename): """Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file. """ if os.path.isfile(filename): fid_st = os.stat(filename) self.name = os.path.abspath(filename) self.full_name = filename self.size = fid_st.st_size self.last_modified = fid_st.st_mtime self.last_accessed = fid_st.st_atime self.last_info_changed = fid_st.st_ctime self.location = os.path.dirname(filename)
[ "def", "populate", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "fid_st", "=", "os", ".", "stat", "(", "filename", ")", "self", ".", "name", "=", "os", ".", "path", ".", "abspath", "("...
Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file.
[ "Finds", "the", "file", "-", "stats", "and", "populates", "the", "class", "with", "stat", "values", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L81-L96
train
41,231
jepegit/cellpy
cellpy/readers/core.py
FileID.get_raw
def get_raw(self): """Get a list with information about the file. The returned list contains name, size, last_modified and location. """ return [self.name, self.size, self.last_modified, self.location]
python
def get_raw(self): """Get a list with information about the file. The returned list contains name, size, last_modified and location. """ return [self.name, self.size, self.last_modified, self.location]
[ "def", "get_raw", "(", "self", ")", ":", "return", "[", "self", ".", "name", ",", "self", ".", "size", ",", "self", ".", "last_modified", ",", "self", ".", "location", "]" ]
Get a list with information about the file. The returned list contains name, size, last_modified and location.
[ "Get", "a", "list", "with", "information", "about", "the", "file", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L98-L103
train
41,232
jepegit/cellpy
cellpy/readers/core.py
DataSet.dfsummary_made
def dfsummary_made(self): """check if the summary table exists""" try: empty = self.dfsummary.empty except AttributeError: empty = True return not empty
python
def dfsummary_made(self): """check if the summary table exists""" try: empty = self.dfsummary.empty except AttributeError: empty = True return not empty
[ "def", "dfsummary_made", "(", "self", ")", ":", "try", ":", "empty", "=", "self", ".", "dfsummary", ".", "empty", "except", "AttributeError", ":", "empty", "=", "True", "return", "not", "empty" ]
check if the summary table exists
[ "check", "if", "the", "summary", "table", "exists" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L243-L249
train
41,233
jepegit/cellpy
cellpy/readers/core.py
DataSet.step_table_made
def step_table_made(self): """check if the step table exists""" try: empty = self.step_table.empty except AttributeError: empty = True return not empty
python
def step_table_made(self): """check if the step table exists""" try: empty = self.step_table.empty except AttributeError: empty = True return not empty
[ "def", "step_table_made", "(", "self", ")", ":", "try", ":", "empty", "=", "self", ".", "step_table", ".", "empty", "except", "AttributeError", ":", "empty", "=", "True", "return", "not", "empty" ]
check if the step table exists
[ "check", "if", "the", "step", "table", "exists" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/core.py#L252-L258
train
41,234
jepegit/cellpy
cellpy/readers/dbreader.py
Reader._open_sheet
def _open_sheet(self, dtypes_dict=None): """Opens sheets and returns it""" table_name = self.db_sheet_table header_row = self.db_header_row nrows = self.nrows if dtypes_dict is None: dtypes_dict = self.dtypes_dict rows_to_skip = self.skiprows logging.debug(f"Trying to open the file {self.db_file}") logging.debug(f"Number of rows: {nrows}") logging.debug(f"Skipping the following rows: {rows_to_skip}") logging.debug(f"Declaring the following dtyps: {dtypes_dict}") work_book = pd.ExcelFile(self.db_file) try: sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, dtype=dtypes_dict, nrows=nrows, ) except ValueError as e: logging.debug("Could not parse all the columns (ValueError) " "using given dtypes. Trying without dtypes.") logging.debug(str(e)) sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, nrows=nrows, ) return sheet
python
def _open_sheet(self, dtypes_dict=None): """Opens sheets and returns it""" table_name = self.db_sheet_table header_row = self.db_header_row nrows = self.nrows if dtypes_dict is None: dtypes_dict = self.dtypes_dict rows_to_skip = self.skiprows logging.debug(f"Trying to open the file {self.db_file}") logging.debug(f"Number of rows: {nrows}") logging.debug(f"Skipping the following rows: {rows_to_skip}") logging.debug(f"Declaring the following dtyps: {dtypes_dict}") work_book = pd.ExcelFile(self.db_file) try: sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, dtype=dtypes_dict, nrows=nrows, ) except ValueError as e: logging.debug("Could not parse all the columns (ValueError) " "using given dtypes. Trying without dtypes.") logging.debug(str(e)) sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, nrows=nrows, ) return sheet
[ "def", "_open_sheet", "(", "self", ",", "dtypes_dict", "=", "None", ")", ":", "table_name", "=", "self", ".", "db_sheet_table", "header_row", "=", "self", ".", "db_header_row", "nrows", "=", "self", ".", "nrows", "if", "dtypes_dict", "is", "None", ":", "dt...
Opens sheets and returns it
[ "Opens", "sheets", "and", "returns", "it" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L122-L151
train
41,235
jepegit/cellpy
cellpy/readers/dbreader.py
Reader._validate
def _validate(self): """Checks that the db-file is ok Returns: True if OK, False if not. """ probably_good_to_go = True sheet = self.table identity = self.db_sheet_cols.id # check if you have unique srnos id_col = sheet.loc[:, identity] if any(id_col.duplicated()): warnings.warn( "your database is corrupt: duplicates" " encountered in the srno-column") logger.debug("srno duplicates:\n" + str( id_col.duplicated())) probably_good_to_go = False return probably_good_to_go
python
def _validate(self): """Checks that the db-file is ok Returns: True if OK, False if not. """ probably_good_to_go = True sheet = self.table identity = self.db_sheet_cols.id # check if you have unique srnos id_col = sheet.loc[:, identity] if any(id_col.duplicated()): warnings.warn( "your database is corrupt: duplicates" " encountered in the srno-column") logger.debug("srno duplicates:\n" + str( id_col.duplicated())) probably_good_to_go = False return probably_good_to_go
[ "def", "_validate", "(", "self", ")", ":", "probably_good_to_go", "=", "True", "sheet", "=", "self", ".", "table", "identity", "=", "self", ".", "db_sheet_cols", ".", "id", "# check if you have unique srnos", "id_col", "=", "sheet", ".", "loc", "[", ":", ","...
Checks that the db-file is ok Returns: True if OK, False if not.
[ "Checks", "that", "the", "db", "-", "file", "is", "ok" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L153-L172
train
41,236
jepegit/cellpy
cellpy/readers/dbreader.py
Reader.select_serial_number_row
def select_serial_number_row(self, serial_number): """Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col] == serial_number return sheet.loc[rows, :]
python
def select_serial_number_row(self, serial_number): """Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col] == serial_number return sheet.loc[rows, :]
[ "def", "select_serial_number_row", "(", "self", ",", "serial_number", ")", ":", "sheet", "=", "self", ".", "table", "col", "=", "self", ".", "db_sheet_cols", ".", "id", "rows", "=", "sheet", ".", "loc", "[", ":", ",", "col", "]", "==", "serial_number", ...
Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame
[ "Select", "row", "for", "identification", "number", "serial_number" ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L182-L194
train
41,237
jepegit/cellpy
cellpy/readers/dbreader.py
Reader.select_all
def select_all(self, serial_numbers): """Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col].isin(serial_numbers) return sheet.loc[rows, :]
python
def select_all(self, serial_numbers): """Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col].isin(serial_numbers) return sheet.loc[rows, :]
[ "def", "select_all", "(", "self", ",", "serial_numbers", ")", ":", "sheet", "=", "self", ".", "table", "col", "=", "self", ".", "db_sheet_cols", ".", "id", "rows", "=", "sheet", ".", "loc", "[", ":", ",", "col", "]", ".", "isin", "(", "serial_numbers...
Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame
[ "Select", "rows", "for", "identification", "for", "a", "list", "of", "serial_number", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L196-L208
train
41,238
jepegit/cellpy
cellpy/readers/dbreader.py
Reader.print_serial_number_info
def print_serial_number_info(self, serial_number, print_to_screen=True): """Print information about the run. Args: serial_number: serial number. print_to_screen: runs the print statement if True, returns txt if not. Returns: txt if print_to_screen is False, else None. """ r = self.select_serial_number_row(serial_number) if r.empty: warnings.warn("missing serial number") return txt1 = 80 * "=" txt1 += "\n" txt1 += f" serial number {serial_number}\n" txt1 = 80 * "-" txt1 += "\n" txt2 = "" for label, value in zip(r.columns, r.values[0]): if label in self.headers: txt1 += f"{label}: \t {value}\n" else: txt2 += f"({label}: \t {value})\n" if print_to_screen: print(txt1) print(80 * "-") print(txt2) print(80 * "=") return else: return txt1
python
def print_serial_number_info(self, serial_number, print_to_screen=True): """Print information about the run. Args: serial_number: serial number. print_to_screen: runs the print statement if True, returns txt if not. Returns: txt if print_to_screen is False, else None. """ r = self.select_serial_number_row(serial_number) if r.empty: warnings.warn("missing serial number") return txt1 = 80 * "=" txt1 += "\n" txt1 += f" serial number {serial_number}\n" txt1 = 80 * "-" txt1 += "\n" txt2 = "" for label, value in zip(r.columns, r.values[0]): if label in self.headers: txt1 += f"{label}: \t {value}\n" else: txt2 += f"({label}: \t {value})\n" if print_to_screen: print(txt1) print(80 * "-") print(txt2) print(80 * "=") return else: return txt1
[ "def", "print_serial_number_info", "(", "self", ",", "serial_number", ",", "print_to_screen", "=", "True", ")", ":", "r", "=", "self", ".", "select_serial_number_row", "(", "serial_number", ")", "if", "r", ".", "empty", ":", "warnings", ".", "warn", "(", "\"...
Print information about the run. Args: serial_number: serial number. print_to_screen: runs the print statement if True, returns txt if not. Returns: txt if print_to_screen is False, else None.
[ "Print", "information", "about", "the", "run", "." ]
9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L210-L244
train
41,239
openstax/cnx-epub
cnxepub/scripts/collated_single_html/main.py
main
def main(argv=None): """Parse passed in cooked single HTML.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('collated_html', type=argparse.FileType('r'), help='Path to the collated html' ' file (use - for stdin)') parser.add_argument('-d', '--dump-tree', action='store_true', help='Print out parsed model tree.') parser.add_argument('-o', '--output', type=argparse.FileType('w+'), help='Write out epub of parsed tree.') parser.add_argument('-i', '--input', type=argparse.FileType('r'), help='Read and copy resources/ for output epub.') args = parser.parse_args(argv) if args.input and args.output == sys.stdout: raise ValueError('Cannot output to stdout if reading resources') from cnxepub.collation import reconstitute binder = reconstitute(args.collated_html) if args.dump_tree: print(pformat(cnxepub.model_to_tree(binder)), file=sys.stdout) if args.output: cnxepub.adapters.make_epub(binder, args.output) if args.input: args.output.seek(0) zout = ZipFile(args.output, 'a', ZIP_DEFLATED) zin = ZipFile(args.input, 'r') for res in zin.namelist(): if res.startswith('resources'): zres = zin.open(res) zi = zin.getinfo(res) zout.writestr(zi, zres.read(), ZIP_DEFLATED) zout.close() # TODO Check for documents that have no identifier. # These should likely be composite-documents # or the the metadata got wiped out. # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter) # if x.ident_hash is None] return 0
python
def main(argv=None): """Parse passed in cooked single HTML.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('collated_html', type=argparse.FileType('r'), help='Path to the collated html' ' file (use - for stdin)') parser.add_argument('-d', '--dump-tree', action='store_true', help='Print out parsed model tree.') parser.add_argument('-o', '--output', type=argparse.FileType('w+'), help='Write out epub of parsed tree.') parser.add_argument('-i', '--input', type=argparse.FileType('r'), help='Read and copy resources/ for output epub.') args = parser.parse_args(argv) if args.input and args.output == sys.stdout: raise ValueError('Cannot output to stdout if reading resources') from cnxepub.collation import reconstitute binder = reconstitute(args.collated_html) if args.dump_tree: print(pformat(cnxepub.model_to_tree(binder)), file=sys.stdout) if args.output: cnxepub.adapters.make_epub(binder, args.output) if args.input: args.output.seek(0) zout = ZipFile(args.output, 'a', ZIP_DEFLATED) zin = ZipFile(args.input, 'r') for res in zin.namelist(): if res.startswith('resources'): zres = zin.open(res) zi = zin.getinfo(res) zout.writestr(zi, zres.read(), ZIP_DEFLATED) zout.close() # TODO Check for documents that have no identifier. # These should likely be composite-documents # or the the metadata got wiped out. # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter) # if x.ident_hash is None] return 0
[ "def", "main", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ")", "parser", ".", "add_argument", "(", "'collated_html'", ",", "type", "=", "argparse", ".", "FileType", "(", "'r'", ...
Parse passed in cooked single HTML.
[ "Parse", "passed", "in", "cooked", "single", "HTML", "." ]
f648a309eff551b0a68a115a98ddf7858149a2ea
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/scripts/collated_single_html/main.py#L28-L74
train
41,240
ModisWorks/modis
modis/discord_modis/modules/hex/ui_embed.py
success
def success(channel, image, hex_str): """ Creates an embed UI containing a hex color message Args: channel (discord.Channel): The Discord channel to bind the embed to image (str): The url of the image to add hex_str (str): The hex value Returns: ui (ui_embed.UI): The embed UI object that was created """ hex_number = int(hex_str, 16) # Create embed UI object gui = ui_embed.UI( channel, "", "#{}".format(hex_str), modulename=modulename, colour=hex_number, thumbnail=image, ) return gui
python
def success(channel, image, hex_str): """ Creates an embed UI containing a hex color message Args: channel (discord.Channel): The Discord channel to bind the embed to image (str): The url of the image to add hex_str (str): The hex value Returns: ui (ui_embed.UI): The embed UI object that was created """ hex_number = int(hex_str, 16) # Create embed UI object gui = ui_embed.UI( channel, "", "#{}".format(hex_str), modulename=modulename, colour=hex_number, thumbnail=image, ) return gui
[ "def", "success", "(", "channel", ",", "image", ",", "hex_str", ")", ":", "hex_number", "=", "int", "(", "hex_str", ",", "16", ")", "# Create embed UI object", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"\"", ",", "\"#{}\"", ".", "format",...
Creates an embed UI containing a hex color message Args: channel (discord.Channel): The Discord channel to bind the embed to image (str): The url of the image to add hex_str (str): The hex value Returns: ui (ui_embed.UI): The embed UI object that was created
[ "Creates", "an", "embed", "UI", "containing", "a", "hex", "color", "message" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/hex/ui_embed.py#L5-L30
train
41,241
ModisWorks/modis
GenerateReadme.py
add_md
def add_md(text, s, level=0): """Adds text to the readme at the given level""" if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
python
def add_md(text, s, level=0): """Adds text to the readme at the given level""" if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
[ "def", "add_md", "(", "text", ",", "s", ",", "level", "=", "0", ")", ":", "if", "level", ">", "0", ":", "if", "text", "!=", "\"\"", ":", "text", "+=", "\"\\n\"", "text", "+=", "\"#\"", "*", "level", "text", "+=", "\" \"", "text", "+=", "s", "+"...
Adds text to the readme at the given level
[ "Adds", "text", "to", "the", "readme", "at", "the", "given", "level" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/GenerateReadme.py#L10-L23
train
41,242
ModisWorks/modis
GenerateReadme.py
add_ul
def add_ul(text, ul): """Adds an unordered list to the readme""" text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
python
def add_ul(text, ul): """Adds an unordered list to the readme""" text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
[ "def", "add_ul", "(", "text", ",", "ul", ")", ":", "text", "+=", "\"\\n\"", "for", "li", "in", "ul", ":", "text", "+=", "\"- \"", "+", "li", "+", "\"\\n\"", "text", "+=", "\"\\n\"", "return", "text" ]
Adds an unordered list to the readme
[ "Adds", "an", "unordered", "list", "to", "the", "readme" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/GenerateReadme.py#L26-L33
train
41,243
freelawproject/reporters-db
reporters_db/make_csv.py
make_editions_dict
def make_editions_dict(editions): """Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter. """ d = {} nums = ['1', '2', '3', '4', '5', '6'] num_counter = 0 for k, date_dict in editions.items(): d['edition%s' % nums[num_counter]] = k if date_dict['start'] is not None: d['start_e%s' % nums[num_counter]] = date_dict['start'].isoformat() if date_dict['end'] is not None: d['end_e%s' % nums[num_counter]] = date_dict['end'].isoformat() num_counter += 1 return d
python
def make_editions_dict(editions): """Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter. """ d = {} nums = ['1', '2', '3', '4', '5', '6'] num_counter = 0 for k, date_dict in editions.items(): d['edition%s' % nums[num_counter]] = k if date_dict['start'] is not None: d['start_e%s' % nums[num_counter]] = date_dict['start'].isoformat() if date_dict['end'] is not None: d['end_e%s' % nums[num_counter]] = date_dict['end'].isoformat() num_counter += 1 return d
[ "def", "make_editions_dict", "(", "editions", ")", ":", "d", "=", "{", "}", "nums", "=", "[", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", "]", "num_counter", "=", "0", "for", "k", ",", "date_dict", "in", "editions", ".", "i...
Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter.
[ "Take", "a", "reporter", "editions", "dict", "and", "flatten", "it", "returning", "a", "dict", "for", "use", "in", "the", "DictWriter", "." ]
ee17ee38a4e39de8d83beb78d84d146cd7e8afbc
https://github.com/freelawproject/reporters-db/blob/ee17ee38a4e39de8d83beb78d84d146cd7e8afbc/reporters_db/make_csv.py#L15-L31
train
41,244
ModisWorks/modis
modis/discord_modis/modules/manager/ui_embed.py
modify_module
def modify_module(channel, module_name, module_state): """ Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed """ # Create embed UI object gui = ui_embed.UI( channel, "{} updated".format(module_name), "{} is now {}".format(module_name, "activated" if module_state else "deactivated"), modulename=modulename ) return gui
python
def modify_module(channel, module_name, module_state): """ Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed """ # Create embed UI object gui = ui_embed.UI( channel, "{} updated".format(module_name), "{} is now {}".format(module_name, "activated" if module_state else "deactivated"), modulename=modulename ) return gui
[ "def", "modify_module", "(", "channel", ",", "module_name", ",", "module_state", ")", ":", "# Create embed UI object", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"{} updated\"", ".", "format", "(", "module_name", ")", ",", "\"{} is now {}\"", ".",...
Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed
[ "Creates", "an", "embed", "UI", "containing", "the", "module", "modified", "message" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/manager/ui_embed.py#L7-L28
train
41,245
ModisWorks/modis
modis/discord_modis/modules/manager/ui_embed.py
modify_prefix
def modify_prefix(channel, new_prefix): """ Creates an embed UI containing the prefix modified message Args: channel (discord.Channel): The Discord channel to bind the embed to new_prefix (str): The value of the new prefix Returns: embed: The created embed """ # Create embed UI object gui = ui_embed.UI( channel, "Prefix updated", "Modis prefix is now `{}`".format(new_prefix), modulename=modulename ) return gui
python
def modify_prefix(channel, new_prefix): """ Creates an embed UI containing the prefix modified message Args: channel (discord.Channel): The Discord channel to bind the embed to new_prefix (str): The value of the new prefix Returns: embed: The created embed """ # Create embed UI object gui = ui_embed.UI( channel, "Prefix updated", "Modis prefix is now `{}`".format(new_prefix), modulename=modulename ) return gui
[ "def", "modify_prefix", "(", "channel", ",", "new_prefix", ")", ":", "# Create embed UI object", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"Prefix updated\"", ",", "\"Modis prefix is now `{}`\"", ".", "format", "(", "new_prefix", ")", ",", "modulen...
Creates an embed UI containing the prefix modified message Args: channel (discord.Channel): The Discord channel to bind the embed to new_prefix (str): The value of the new prefix Returns: embed: The created embed
[ "Creates", "an", "embed", "UI", "containing", "the", "prefix", "modified", "message" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/manager/ui_embed.py#L31-L51
train
41,246
ModisWorks/modis
modis/discord_modis/modules/!core/api_core.py
update_server_data
async def update_server_data(server): """ Updates the server info for the given server Args: server: The Discord server to update info for """ data = datatools.get_data() # Add the server to server data if it doesn't yet exist send_welcome_message = False if server.id not in data["discord"]["servers"]: logger.debug("Adding new server to serverdata") data["discord"]["servers"][server.id] = {"prefix": "!"} if "mute_intro" not in data or not data["mute_intro"]: send_welcome_message = True # Make sure all modules are in the server _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) for module_name in os.listdir(_dir_modules): if module_name.startswith("_") or module_name.startswith("!"): continue if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)): logger.warning("No _data.py file found for module {}".format(module_name)) continue try: import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data") _data = importlib.import_module(import_name, "modis") if _data.modulename not in data["discord"]["servers"][server.id]: data["discord"]["servers"][server.id][_data.modulename] = _data.sd_structure datatools.write_data(data) except Exception as e: logger.error("Could not initialise module {}".format(module_name)) logger.exception(e) datatools.write_data(data) # Send a welcome message now if send_welcome_message: default_channel = server.default_channel if not default_channel: for channel in server.channels: if channel.name == "general": default_channel = channel break if not default_channel: for channel in server.channels: if "general" in channel.name: default_channel = channel break if not default_channel: for channel in server.channels: if channel.type == discord.ChannelType.text: default_channel = channel break # Display a welcome message if default_channel: hello_message = "Hello! I'm Modis.\n\n" + \ "The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \ "You can use `!help` to get help commands for all modules, " + \ "or {} me to get the server prefix and help commands.".format(server.me.mention) await client.send_message(default_channel, hello_message)
python
async def update_server_data(server): """ Updates the server info for the given server Args: server: The Discord server to update info for """ data = datatools.get_data() # Add the server to server data if it doesn't yet exist send_welcome_message = False if server.id not in data["discord"]["servers"]: logger.debug("Adding new server to serverdata") data["discord"]["servers"][server.id] = {"prefix": "!"} if "mute_intro" not in data or not data["mute_intro"]: send_welcome_message = True # Make sure all modules are in the server _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) for module_name in os.listdir(_dir_modules): if module_name.startswith("_") or module_name.startswith("!"): continue if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)): logger.warning("No _data.py file found for module {}".format(module_name)) continue try: import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data") _data = importlib.import_module(import_name, "modis") if _data.modulename not in data["discord"]["servers"][server.id]: data["discord"]["servers"][server.id][_data.modulename] = _data.sd_structure datatools.write_data(data) except Exception as e: logger.error("Could not initialise module {}".format(module_name)) logger.exception(e) datatools.write_data(data) # Send a welcome message now if send_welcome_message: default_channel = server.default_channel if not default_channel: for channel in server.channels: if channel.name == "general": default_channel = channel break if not default_channel: for channel in server.channels: if "general" in channel.name: default_channel = channel break if not default_channel: for channel in server.channels: if channel.type == discord.ChannelType.text: default_channel = channel break # Display a welcome message if default_channel: hello_message = "Hello! I'm Modis.\n\n" + \ "The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \ "You can use `!help` to get help commands for all modules, " + \ "or {} me to get the server prefix and help commands.".format(server.me.mention) await client.send_message(default_channel, hello_message)
[ "async", "def", "update_server_data", "(", "server", ")", ":", "data", "=", "datatools", ".", "get_data", "(", ")", "# Add the server to server data if it doesn't yet exist", "send_welcome_message", "=", "False", "if", "server", ".", "id", "not", "in", "data", "[", ...
Updates the server info for the given server Args: server: The Discord server to update info for
[ "Updates", "the", "server", "info", "for", "the", "given", "server" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/!core/api_core.py#L10-L76
train
41,247
ModisWorks/modis
modis/discord_modis/modules/!core/api_core.py
remove_server_data
def remove_server_data(server_id): """ Remove a server from the server data Args: server_id (int): The server to remove from the server data """ logger.debug("Removing server from serverdata") # Remove the server from data data = datatools.get_data() if server_id in data["discord"]["servers"]: data["discord"]["servers"].pop(server_id) datatools.write_data(data)
python
def remove_server_data(server_id): """ Remove a server from the server data Args: server_id (int): The server to remove from the server data """ logger.debug("Removing server from serverdata") # Remove the server from data data = datatools.get_data() if server_id in data["discord"]["servers"]: data["discord"]["servers"].pop(server_id) datatools.write_data(data)
[ "def", "remove_server_data", "(", "server_id", ")", ":", "logger", ".", "debug", "(", "\"Removing server from serverdata\"", ")", "# Remove the server from data", "data", "=", "datatools", ".", "get_data", "(", ")", "if", "server_id", "in", "data", "[", "\"discord\"...
Remove a server from the server data Args: server_id (int): The server to remove from the server data
[ "Remove", "a", "server", "from", "the", "server", "data" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/!core/api_core.py#L79-L92
train
41,248
ModisWorks/modis
modis/discord_modis/modules/!core/api_core.py
check_all_servers
def check_all_servers(): """Checks all servers, removing any that Modis isn't part of any more""" data = datatools.get_data() for server_id in data["discord"]["servers"]: is_in_client = False for client_server in client.servers: if server_id == client_server.id: is_in_client = True break if not is_in_client: remove_server_data(server_id)
python
def check_all_servers(): """Checks all servers, removing any that Modis isn't part of any more""" data = datatools.get_data() for server_id in data["discord"]["servers"]: is_in_client = False for client_server in client.servers: if server_id == client_server.id: is_in_client = True break if not is_in_client: remove_server_data(server_id)
[ "def", "check_all_servers", "(", ")", ":", "data", "=", "datatools", ".", "get_data", "(", ")", "for", "server_id", "in", "data", "[", "\"discord\"", "]", "[", "\"servers\"", "]", ":", "is_in_client", "=", "False", "for", "client_server", "in", "client", "...
Checks all servers, removing any that Modis isn't part of any more
[ "Checks", "all", "servers", "removing", "any", "that", "Modis", "isn", "t", "part", "of", "any", "more" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/!core/api_core.py#L95-L106
train
41,249
ModisWorks/modis
modis/discord_modis/gui.py
ModuleFrame.clear_modules
def clear_modules(self): """Clears all modules from the list""" for child in self.module_selection.winfo_children(): child.destroy() self.clear_ui() tk.Label(self.module_ui, text="Start Modis and select a module").grid( column=0, row=0, padx=0, pady=0, sticky="W E N S") if self.current_button is not None: self.current_button.config(bg="white") self.module_buttons = {} self.current_button = None
python
def clear_modules(self): """Clears all modules from the list""" for child in self.module_selection.winfo_children(): child.destroy() self.clear_ui() tk.Label(self.module_ui, text="Start Modis and select a module").grid( column=0, row=0, padx=0, pady=0, sticky="W E N S") if self.current_button is not None: self.current_button.config(bg="white") self.module_buttons = {} self.current_button = None
[ "def", "clear_modules", "(", "self", ")", ":", "for", "child", "in", "self", ".", "module_selection", ".", "winfo_children", "(", ")", ":", "child", ".", "destroy", "(", ")", "self", ".", "clear_ui", "(", ")", "tk", ".", "Label", "(", "self", ".", "m...
Clears all modules from the list
[ "Clears", "all", "modules", "from", "the", "list" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L137-L151
train
41,250
ModisWorks/modis
modis/discord_modis/gui.py
ModuleFrame.add_module
def add_module(self, module_name, module_ui): """ Adds a module to the list Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI """ m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w") m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S") self.module_buttons[module_name] = m_button m_button.bind("<Button-1>", lambda e: self.module_selected(module_name, module_ui))
python
def add_module(self, module_name, module_ui): """ Adds a module to the list Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI """ m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w") m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S") self.module_buttons[module_name] = m_button m_button.bind("<Button-1>", lambda e: self.module_selected(module_name, module_ui))
[ "def", "add_module", "(", "self", ",", "module_name", ",", "module_ui", ")", ":", "m_button", "=", "tk", ".", "Label", "(", "self", ".", "module_selection", ",", "text", "=", "module_name", ",", "bg", "=", "\"white\"", ",", "anchor", "=", "\"w\"", ")", ...
Adds a module to the list Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
[ "Adds", "a", "module", "to", "the", "list" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L158-L170
train
41,251
ModisWorks/modis
modis/discord_modis/gui.py
ModuleFrame.module_selected
def module_selected(self, module_name, module_ui): """ Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI """ if self.current_button == self.module_buttons[module_name]: return self.module_buttons[module_name].config(bg="#cacaca") if self.current_button is not None: self.current_button.config(bg="white") self.current_button = self.module_buttons[module_name] self.clear_ui() try: # Create the UI module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui) module_ui_frame.grid(column=0, row=0, sticky="W E N S") except Exception as e: logger.error("Could not load UI for {}".format(module_name)) logger.exception(e) # Create a error UI tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid( column=0, row=0, padx=0, pady=0, sticky="W E N S")
python
def module_selected(self, module_name, module_ui): """ Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI """ if self.current_button == self.module_buttons[module_name]: return self.module_buttons[module_name].config(bg="#cacaca") if self.current_button is not None: self.current_button.config(bg="white") self.current_button = self.module_buttons[module_name] self.clear_ui() try: # Create the UI module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui) module_ui_frame.grid(column=0, row=0, sticky="W E N S") except Exception as e: logger.error("Could not load UI for {}".format(module_name)) logger.exception(e) # Create a error UI tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid( column=0, row=0, padx=0, pady=0, sticky="W E N S")
[ "def", "module_selected", "(", "self", ",", "module_name", ",", "module_ui", ")", ":", "if", "self", ".", "current_button", "==", "self", ".", "module_buttons", "[", "module_name", "]", ":", "return", "self", ".", "module_buttons", "[", "module_name", "]", "...
Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
[ "Called", "when", "a", "module", "is", "selected" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L172-L199
train
41,252
ModisWorks/modis
modis/discord_modis/gui.py
BotControl.toggle
def toggle(self, discord_token, discord_client_id): """Toggles Modis on or off""" if self.state == 'off': self.start(discord_token, discord_client_id) elif self.state == 'on': self.stop()
python
def toggle(self, discord_token, discord_client_id): """Toggles Modis on or off""" if self.state == 'off': self.start(discord_token, discord_client_id) elif self.state == 'on': self.stop()
[ "def", "toggle", "(", "self", ",", "discord_token", ",", "discord_client_id", ")", ":", "if", "self", ".", "state", "==", "'off'", ":", "self", ".", "start", "(", "discord_token", ",", "discord_client_id", ")", "elif", "self", ".", "state", "==", "'on'", ...
Toggles Modis on or off
[ "Toggles", "Modis", "on", "or", "off" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L295-L300
train
41,253
ModisWorks/modis
modis/discord_modis/gui.py
BotControl.start
def start(self, discord_token, discord_client_id): """Start Modis and log it into Discord.""" self.button_toggle_text.set("Stop Modis") self.state = "on" self.status_bar.set_status(1) logger.info("----------------STARTING DISCORD MODIS----------------") # Clear the module list self.module_frame.clear_modules() # Start Modis from modis.discord_modis import main logger.debug("Creating event loop") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.discord_thread = threading.Thread( target=main.start, args=[discord_token, discord_client_id, loop, self.on_ready]) logger.debug("Starting event loop") self.discord_thread.start() # Find module UIs database_dir = "{}/modules".format( os.path.dirname(os.path.realpath(__file__))) for module_name in os.listdir(database_dir): module_dir = "{}/{}".format(database_dir, module_name) # Iterate through files in module if os.path.isdir(module_dir) and not module_name.startswith("_"): # Add all defined event handlers in module files module_event_handlers = os.listdir(module_dir) if "_ui.py" in module_event_handlers: import_name = ".discord_modis.modules.{}.{}".format( module_name, "_ui") logger.debug( "Found module UI file {}".format(import_name[23:])) self.module_frame.add_module(module_name, importlib.import_module(import_name, "modis")) else: self.module_frame.add_module(module_name, None)
python
def start(self, discord_token, discord_client_id): """Start Modis and log it into Discord.""" self.button_toggle_text.set("Stop Modis") self.state = "on" self.status_bar.set_status(1) logger.info("----------------STARTING DISCORD MODIS----------------") # Clear the module list self.module_frame.clear_modules() # Start Modis from modis.discord_modis import main logger.debug("Creating event loop") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.discord_thread = threading.Thread( target=main.start, args=[discord_token, discord_client_id, loop, self.on_ready]) logger.debug("Starting event loop") self.discord_thread.start() # Find module UIs database_dir = "{}/modules".format( os.path.dirname(os.path.realpath(__file__))) for module_name in os.listdir(database_dir): module_dir = "{}/{}".format(database_dir, module_name) # Iterate through files in module if os.path.isdir(module_dir) and not module_name.startswith("_"): # Add all defined event handlers in module files module_event_handlers = os.listdir(module_dir) if "_ui.py" in module_event_handlers: import_name = ".discord_modis.modules.{}.{}".format( module_name, "_ui") logger.debug( "Found module UI file {}".format(import_name[23:])) self.module_frame.add_module(module_name, importlib.import_module(import_name, "modis")) else: self.module_frame.add_module(module_name, None)
[ "def", "start", "(", "self", ",", "discord_token", ",", "discord_client_id", ")", ":", "self", ".", "button_toggle_text", ".", "set", "(", "\"Stop Modis\"", ")", "self", ".", "state", "=", "\"on\"", "self", ".", "status_bar", ".", "set_status", "(", "1", "...
Start Modis and log it into Discord.
[ "Start", "Modis", "and", "log", "it", "into", "Discord", "." ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L302-L344
train
41,254
ModisWorks/modis
modis/discord_modis/gui.py
BotControl.stop
def stop(self): """Stop Modis and log it out of Discord.""" self.button_toggle_text.set("Start Modis") self.state = "off" logger.info("Stopping Discord Modis") from ._client import client asyncio.run_coroutine_threadsafe(client.logout(), client.loop) self.status_bar.set_status(0)
python
def stop(self): """Stop Modis and log it out of Discord.""" self.button_toggle_text.set("Start Modis") self.state = "off" logger.info("Stopping Discord Modis") from ._client import client asyncio.run_coroutine_threadsafe(client.logout(), client.loop) self.status_bar.set_status(0)
[ "def", "stop", "(", "self", ")", ":", "self", ".", "button_toggle_text", ".", "set", "(", "\"Start Modis\"", ")", "self", ".", "state", "=", "\"off\"", "logger", ".", "info", "(", "\"Stopping Discord Modis\"", ")", "from", ".", "_client", "import", "client",...
Stop Modis and log it out of Discord.
[ "Stop", "Modis", "and", "log", "it", "out", "of", "Discord", "." ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L350-L359
train
41,255
ModisWorks/modis
modis/discord_modis/gui.py
BotControl.key_changed
def key_changed(self): """Checks if the key name and value fields have been set, and updates the add key button""" if self.key_name.get() and self.key_val.get(): self.button_key_add.state(["!disabled"]) else: self.button_key_add.state(["disabled"])
python
def key_changed(self): """Checks if the key name and value fields have been set, and updates the add key button""" if self.key_name.get() and self.key_val.get(): self.button_key_add.state(["!disabled"]) else: self.button_key_add.state(["disabled"])
[ "def", "key_changed", "(", "self", ")", ":", "if", "self", ".", "key_name", ".", "get", "(", ")", "and", "self", ".", "key_val", ".", "get", "(", ")", ":", "self", ".", "button_key_add", ".", "state", "(", "[", "\"!disabled\"", "]", ")", "else", ":...
Checks if the key name and value fields have been set, and updates the add key button
[ "Checks", "if", "the", "key", "name", "and", "value", "fields", "have", "been", "set", "and", "updates", "the", "add", "key", "button" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L361-L366
train
41,256
ModisWorks/modis
modis/discord_modis/gui.py
BotControl.key_add
def key_add(self): """Adds the current API key to the bot's data""" from .main import add_api_key add_api_key(self.key_name.get(), self.key_val.get()) # Clear the text fields self.key_name.set("") self.key_val.set("")
python
def key_add(self): """Adds the current API key to the bot's data""" from .main import add_api_key add_api_key(self.key_name.get(), self.key_val.get()) # Clear the text fields self.key_name.set("") self.key_val.set("")
[ "def", "key_add", "(", "self", ")", ":", "from", ".", "main", "import", "add_api_key", "add_api_key", "(", "self", ".", "key_name", ".", "get", "(", ")", ",", "self", ".", "key_val", ".", "get", "(", ")", ")", "# Clear the text fields", "self", ".", "k...
Adds the current API key to the bot's data
[ "Adds", "the", "current", "API", "key", "to", "the", "bot", "s", "data" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L368-L375
train
41,257
ModisWorks/modis
modis/discord_modis/gui.py
StatusBar.set_status
def set_status(self, status): """ Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online """ text = "" colour = "#FFFFFF" if status == 0: text = "OFFLINE" colour = "#EF9A9A" elif status == 1: text = "STARTING" colour = "#FFE082" elif status == 2: text = "ONLINE" colour = "#A5D6A7" self.status.set(text) self.statusbar.config(background=colour)
python
def set_status(self, status): """ Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online """ text = "" colour = "#FFFFFF" if status == 0: text = "OFFLINE" colour = "#EF9A9A" elif status == 1: text = "STARTING" colour = "#FFE082" elif status == 2: text = "ONLINE" colour = "#A5D6A7" self.status.set(text) self.statusbar.config(background=colour)
[ "def", "set_status", "(", "self", ",", "status", ")", ":", "text", "=", "\"\"", "colour", "=", "\"#FFFFFF\"", "if", "status", "==", "0", ":", "text", "=", "\"OFFLINE\"", "colour", "=", "\"#EF9A9A\"", "elif", "status", "==", "1", ":", "text", "=", "\"ST...
Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online
[ "Updates", "the", "status", "text" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/gui.py#L485-L507
train
41,258
ModisWorks/modis
modis/helptools.py
get_help_data
def get_help_data(filepath): """ Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file """ try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=OrderedDict) except Exception as e: logger.error("Could not load file {}".format(filepath)) logger.exception(e) return {}
python
def get_help_data(filepath): """ Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file """ try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=OrderedDict) except Exception as e: logger.error("Could not load file {}".format(filepath)) logger.exception(e) return {}
[ "def", "get_help_data", "(", "filepath", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "file", ":", "return", "_json", ".", "load", "(", "file", ",", "object_pairs_hook", "=", "OrderedDict", ")", "except", "Exception", "as...
Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file
[ "Get", "the", "json", "data", "from", "a", "help", "file" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/helptools.py#L9-L26
train
41,259
ModisWorks/modis
modis/helptools.py
get_help_datapacks
def get_help_datapacks(filepath, prefix="!"): """ Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file """ help_contents = get_help_data(filepath) datapacks = [] # Add the content for d in help_contents: heading = d content = "" if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue content += "- `" command = prefix + c["name"] content += "{}".format(command) if "params" in c: for param in c["params"]: content += " [{}]".format(param) content += "`: " if "description" in c: content += c["description"] content += "\n" else: content += help_contents[d] datapacks.append((heading, content, False)) return datapacks
python
def get_help_datapacks(filepath, prefix="!"): """ Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file """ help_contents = get_help_data(filepath) datapacks = [] # Add the content for d in help_contents: heading = d content = "" if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue content += "- `" command = prefix + c["name"] content += "{}".format(command) if "params" in c: for param in c["params"]: content += " [{}]".format(param) content += "`: " if "description" in c: content += c["description"] content += "\n" else: content += help_contents[d] datapacks.append((heading, content, False)) return datapacks
[ "def", "get_help_datapacks", "(", "filepath", ",", "prefix", "=", "\"!\"", ")", ":", "help_contents", "=", "get_help_data", "(", "filepath", ")", "datapacks", "=", "[", "]", "# Add the content", "for", "d", "in", "help_contents", ":", "heading", "=", "d", "c...
Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file
[ "Load", "help", "text", "from", "a", "file", "and", "give", "it", "as", "datapacks" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/helptools.py#L29-L70
train
41,260
ModisWorks/modis
modis/helptools.py
add_help_text
def add_help_text(parent, filepath, prefix="!"): """ Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands """ import tkinter as tk import tkinter.ttk as ttk help_contents = get_help_data(filepath) text = tk.Text(parent, wrap='word', font=("Helvetica", 10)) text.grid(row=0, column=0, sticky="W E N S") text.tag_config("heading", font=("Helvetica", 14)) text.tag_config("command", font=("Courier", 10)) text.tag_config("param", font=("Courier", 10)) text.tag_config("description") # Vertical Scrollbar scrollbar = ttk.Scrollbar(parent, orient="vertical", command=text.yview) scrollbar.grid(column=1, row=0, sticky="N S") text['yscrollcommand'] = scrollbar.set # Add the content for d in help_contents: text.insert('end', d, "heading") text.insert('end', '\n') if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue command = prefix + c["name"] text.insert('end', command, ("command", "description")) if "params" in c: for param in c["params"]: text.insert('end', " [{}]".format(param), ("param", "description")) text.insert('end', ": ") if "description" in c: text.insert('end', c["description"], "description") text.insert('end', '\n') text.insert('end', '\n') else: text.insert('end', help_contents[d], "description") text.insert('end', '\n\n') text.config(state=tk.DISABLED)
python
def add_help_text(parent, filepath, prefix="!"): """ Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands """ import tkinter as tk import tkinter.ttk as ttk help_contents = get_help_data(filepath) text = tk.Text(parent, wrap='word', font=("Helvetica", 10)) text.grid(row=0, column=0, sticky="W E N S") text.tag_config("heading", font=("Helvetica", 14)) text.tag_config("command", font=("Courier", 10)) text.tag_config("param", font=("Courier", 10)) text.tag_config("description") # Vertical Scrollbar scrollbar = ttk.Scrollbar(parent, orient="vertical", command=text.yview) scrollbar.grid(column=1, row=0, sticky="N S") text['yscrollcommand'] = scrollbar.set # Add the content for d in help_contents: text.insert('end', d, "heading") text.insert('end', '\n') if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue command = prefix + c["name"] text.insert('end', command, ("command", "description")) if "params" in c: for param in c["params"]: text.insert('end', " [{}]".format(param), ("param", "description")) text.insert('end', ": ") if "description" in c: text.insert('end', c["description"], "description") text.insert('end', '\n') text.insert('end', '\n') else: text.insert('end', help_contents[d], "description") text.insert('end', '\n\n') text.config(state=tk.DISABLED)
[ "def", "add_help_text", "(", "parent", ",", "filepath", ",", "prefix", "=", "\"!\"", ")", ":", "import", "tkinter", "as", "tk", "import", "tkinter", ".", "ttk", "as", "ttk", "help_contents", "=", "get_help_data", "(", "filepath", ")", "text", "=", "tk", ...
Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands
[ "Load", "help", "text", "from", "a", "file", "and", "adds", "it", "to", "the", "parent" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/helptools.py#L73-L126
train
41,261
ModisWorks/modis
modis/__init__.py
console
def console(discord_token, discord_client_id): """ Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID """ state, response = datatools.get_compare_version() logger.info("Starting Modis in console") logger.info(response) import threading import asyncio logger.debug("Loading packages") from modis.discord_modis import main as discord_modis_console from modis.reddit_modis import main as reddit_modis_console from modis.facebook_modis import main as facebook_modis_console # Create threads logger.debug("Initiating threads") loop = asyncio.get_event_loop() discord_thread = threading.Thread( target=discord_modis_console.start, args=[discord_token, discord_client_id, loop]) reddit_thread = threading.Thread( target=reddit_modis_console.start, args=[]) facebook_thread = threading.Thread( target=facebook_modis_console.start, args=[]) # Run threads logger.debug("Starting threads") discord_thread.start() reddit_thread.start() facebook_thread.start() logger.debug("Root startup completed")
python
def console(discord_token, discord_client_id): """ Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID """ state, response = datatools.get_compare_version() logger.info("Starting Modis in console") logger.info(response) import threading import asyncio logger.debug("Loading packages") from modis.discord_modis import main as discord_modis_console from modis.reddit_modis import main as reddit_modis_console from modis.facebook_modis import main as facebook_modis_console # Create threads logger.debug("Initiating threads") loop = asyncio.get_event_loop() discord_thread = threading.Thread( target=discord_modis_console.start, args=[discord_token, discord_client_id, loop]) reddit_thread = threading.Thread( target=reddit_modis_console.start, args=[]) facebook_thread = threading.Thread( target=facebook_modis_console.start, args=[]) # Run threads logger.debug("Starting threads") discord_thread.start() reddit_thread.start() facebook_thread.start() logger.debug("Root startup completed")
[ "def", "console", "(", "discord_token", ",", "discord_client_id", ")", ":", "state", ",", "response", "=", "datatools", ".", "get_compare_version", "(", ")", "logger", ".", "info", "(", "\"Starting Modis in console\"", ")", "logger", ".", "info", "(", "response"...
Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
[ "Start", "Modis", "in", "console", "format", "." ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/__init__.py#L40-L79
train
41,262
ModisWorks/modis
modis/__init__.py
gui
def gui(discord_token, discord_client_id): """ Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID """ logger.info("Starting Modis in GUI") import tkinter as tk logger.debug("Loading packages") from modis.discord_modis import gui as discord_modis_gui from modis.reddit_modis import gui as reddit_modis_gui from modis.facebook_modis import gui as facebook_modis_gui logger.debug("Initialising window") # Setup the root window root = tk.Tk() root.minsize(width=800, height=400) root.geometry("800x600") root.title("Modis Control Panel") # Icon root.iconbitmap(r"{}/assets/modis.ico".format(file_dir)) # Setup the notebook """notebook = ttk.Notebook(root) notebook.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S") # Configure stretch ratios root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) notebook.columnconfigure(0, weight=1) notebook.rowconfigure(0, weight=1) # Add tabs logger.debug("Adding packages to window") notebook.add( discord_modis_gui.Frame(notebook, discord_token, discord_client_id), text="Discord") notebook.add(reddit_modis_gui.Frame(notebook), text="Reddit") notebook.add(facebook_modis_gui.Frame(notebook), text="Facebook")""" discord = discord_modis_gui.Frame(root, discord_token, discord_client_id) discord.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S") # Configure stretch ratios root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) discord.columnconfigure(0, weight=1) discord.rowconfigure(0, weight=1) logger.debug("GUI initialised") # Run the window UI root.mainloop()
python
def gui(discord_token, discord_client_id): """ Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID """ logger.info("Starting Modis in GUI") import tkinter as tk logger.debug("Loading packages") from modis.discord_modis import gui as discord_modis_gui from modis.reddit_modis import gui as reddit_modis_gui from modis.facebook_modis import gui as facebook_modis_gui logger.debug("Initialising window") # Setup the root window root = tk.Tk() root.minsize(width=800, height=400) root.geometry("800x600") root.title("Modis Control Panel") # Icon root.iconbitmap(r"{}/assets/modis.ico".format(file_dir)) # Setup the notebook """notebook = ttk.Notebook(root) notebook.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S") # Configure stretch ratios root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) notebook.columnconfigure(0, weight=1) notebook.rowconfigure(0, weight=1) # Add tabs logger.debug("Adding packages to window") notebook.add( discord_modis_gui.Frame(notebook, discord_token, discord_client_id), text="Discord") notebook.add(reddit_modis_gui.Frame(notebook), text="Reddit") notebook.add(facebook_modis_gui.Frame(notebook), text="Facebook")""" discord = discord_modis_gui.Frame(root, discord_token, discord_client_id) discord.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S") # Configure stretch ratios root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) discord.columnconfigure(0, weight=1) discord.rowconfigure(0, weight=1) logger.debug("GUI initialised") # Run the window UI root.mainloop()
[ "def", "gui", "(", "discord_token", ",", "discord_client_id", ")", ":", "logger", ".", "info", "(", "\"Starting Modis in GUI\"", ")", "import", "tkinter", "as", "tk", "logger", ".", "debug", "(", "\"Loading packages\"", ")", "from", "modis", ".", "discord_modis"...
Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
[ "Start", "Modis", "in", "gui", "format", "." ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/__init__.py#L82-L138
train
41,263
ModisWorks/modis
modis/datatools.py
write_data
def write_data(data): """ Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis """ sorted_dict = sort_recursive(data) with open(_datafile, 'w') as file: _json.dump(sorted_dict, file, indent=2)
python
def write_data(data): """ Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis """ sorted_dict = sort_recursive(data) with open(_datafile, 'w') as file: _json.dump(sorted_dict, file, indent=2)
[ "def", "write_data", "(", "data", ")", ":", "sorted_dict", "=", "sort_recursive", "(", "data", ")", "with", "open", "(", "_datafile", ",", "'w'", ")", "as", "file", ":", "_json", ".", "dump", "(", "sorted_dict", ",", "file", ",", "indent", "=", "2", ...
Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis
[ "Write", "the", "data", "to", "the", "data", ".", "json", "file" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/datatools.py#L51-L62
train
41,264
ModisWorks/modis
modis/datatools.py
sort_recursive
def sort_recursive(data): """ Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict """ newdict = {} for i in data.items(): if type(i[1]) is dict: newdict[i[0]] = sort_recursive(i[1]) else: newdict[i[0]] = i[1] return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))
python
def sort_recursive(data): """ Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict """ newdict = {} for i in data.items(): if type(i[1]) is dict: newdict[i[0]] = sort_recursive(i[1]) else: newdict[i[0]] = i[1] return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))
[ "def", "sort_recursive", "(", "data", ")", ":", "newdict", "=", "{", "}", "for", "i", "in", "data", ".", "items", "(", ")", ":", "if", "type", "(", "i", "[", "1", "]", ")", "is", "dict", ":", "newdict", "[", "i", "[", "0", "]", "]", "=", "s...
Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict
[ "Recursively", "sorts", "all", "elements", "in", "a", "dictionary" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/datatools.py#L65-L84
train
41,265
ModisWorks/modis
modis/datatools.py
get_compare_version
def get_compare_version(): """ Get the version comparison info. Returns: (tuple) state (int): -1 for lower version, 0 for same version, 1 for higher version than latest. response (str): The response string. """ state, latest_version = compare_latest_version() if state < 0: return -1, "A new version of Modis is available (v{})".format(latest_version) elif state == 0: return 0, "You are running the latest version of Modis (v{})".format(version) else: return 1, "You are running a preview version of Modis (v{} pre-release)".format(version)
python
def get_compare_version(): """ Get the version comparison info. Returns: (tuple) state (int): -1 for lower version, 0 for same version, 1 for higher version than latest. response (str): The response string. """ state, latest_version = compare_latest_version() if state < 0: return -1, "A new version of Modis is available (v{})".format(latest_version) elif state == 0: return 0, "You are running the latest version of Modis (v{})".format(version) else: return 1, "You are running a preview version of Modis (v{} pre-release)".format(version)
[ "def", "get_compare_version", "(", ")", ":", "state", ",", "latest_version", "=", "compare_latest_version", "(", ")", "if", "state", "<", "0", ":", "return", "-", "1", ",", "\"A new version of Modis is available (v{})\"", ".", "format", "(", "latest_version", ")",...
Get the version comparison info. Returns: (tuple) state (int): -1 for lower version, 0 for same version, 1 for higher version than latest. response (str): The response string.
[ "Get", "the", "version", "comparison", "info", "." ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/datatools.py#L137-L152
train
41,266
ModisWorks/modis
modis/discord_modis/modules/rocketleague/ui_embed.py
success
def success(channel, stats, name, platform, dp): """Creates an embed UI containing the Rocket League stats Args: channel (discord.Channel): The Discord channel to bind the embed to stats (tuple): Tuples of (field, value, percentile) name (str): The name of the player platform (str): The playfor to search on, can be 'steam', 'ps', or 'xbox' dp (str): URL to the player's dp Returns: (discord.Embed): The created embed """ # Create datapacks datapacks = [("Platform", platform, False)] for stat in stats: # Add stats if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"): stat_name = "__" + stat[0] + "__" stat_value = "**" + stat[1] + "**" else: stat_name = stat[0] stat_value = stat[1] # Add percentile if it exists if stat[2]: stat_value += " *(Top " + stat[2] + "%)*" datapacks.append((stat_name, stat_value, True)) # Create embed UI object gui = ui_embed.UI( channel, "Rocket League Stats: {}".format(name), "*Stats obtained from [Rocket League Tracker Network](https://rocketleague.tracker.network/)*", modulename=modulename, colour=0x0088FF, thumbnail=dp, datapacks=datapacks ) return gui
python
def success(channel, stats, name, platform, dp): """Creates an embed UI containing the Rocket League stats Args: channel (discord.Channel): The Discord channel to bind the embed to stats (tuple): Tuples of (field, value, percentile) name (str): The name of the player platform (str): The playfor to search on, can be 'steam', 'ps', or 'xbox' dp (str): URL to the player's dp Returns: (discord.Embed): The created embed """ # Create datapacks datapacks = [("Platform", platform, False)] for stat in stats: # Add stats if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"): stat_name = "__" + stat[0] + "__" stat_value = "**" + stat[1] + "**" else: stat_name = stat[0] stat_value = stat[1] # Add percentile if it exists if stat[2]: stat_value += " *(Top " + stat[2] + "%)*" datapacks.append((stat_name, stat_value, True)) # Create embed UI object gui = ui_embed.UI( channel, "Rocket League Stats: {}".format(name), "*Stats obtained from [Rocket League Tracker Network](https://rocketleague.tracker.network/)*", modulename=modulename, colour=0x0088FF, thumbnail=dp, datapacks=datapacks ) return gui
[ "def", "success", "(", "channel", ",", "stats", ",", "name", ",", "platform", ",", "dp", ")", ":", "# Create datapacks", "datapacks", "=", "[", "(", "\"Platform\"", ",", "platform", ",", "False", ")", "]", "for", "stat", "in", "stats", ":", "# Add stats"...
Creates an embed UI containing the Rocket League stats Args: channel (discord.Channel): The Discord channel to bind the embed to stats (tuple): Tuples of (field, value, percentile) name (str): The name of the player platform (str): The playfor to search on, can be 'steam', 'ps', or 'xbox' dp (str): URL to the player's dp Returns: (discord.Embed): The created embed
[ "Creates", "an", "embed", "UI", "containing", "the", "Rocket", "League", "stats" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/rocketleague/ui_embed.py#L5-L47
train
41,267
ModisWorks/modis
modis/discord_modis/modules/rocketleague/ui_embed.py
fail_steamid
def fail_steamid(channel): """Creates an embed UI for invalid SteamIDs Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "That SteamID doesn't exist.", "You can get your SteamID by going to your profile page and looking at the url, " "or you can set a custom ID by going to edit profile on your profile page.", modulename=modulename, colour=0x0088FF ) return gui
python
def fail_steamid(channel): """Creates an embed UI for invalid SteamIDs Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "That SteamID doesn't exist.", "You can get your SteamID by going to your profile page and looking at the url, " "or you can set a custom ID by going to edit profile on your profile page.", modulename=modulename, colour=0x0088FF ) return gui
[ "def", "fail_steamid", "(", "channel", ")", ":", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"That SteamID doesn't exist.\"", ",", "\"You can get your SteamID by going to your profile page and looking at the url, \"", "\"or you can set a custom ID by going to edit pro...
Creates an embed UI for invalid SteamIDs Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
[ "Creates", "an", "embed", "UI", "for", "invalid", "SteamIDs" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/rocketleague/ui_embed.py#L50-L69
train
41,268
ModisWorks/modis
modis/discord_modis/modules/rocketleague/ui_embed.py
fail_api
def fail_api(channel): """Creates an embed UI for when the API call didn't work Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "Couldn't get stats off RLTrackerNetwork.", "Maybe the API changed, please tell Infraxion.", modulename=modulename, colour=0x0088FF ) return gui
python
def fail_api(channel): """Creates an embed UI for when the API call didn't work Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "Couldn't get stats off RLTrackerNetwork.", "Maybe the API changed, please tell Infraxion.", modulename=modulename, colour=0x0088FF ) return gui
[ "def", "fail_api", "(", "channel", ")", ":", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"Couldn't get stats off RLTrackerNetwork.\"", ",", "\"Maybe the API changed, please tell Infraxion.\"", ",", "modulename", "=", "modulename", ",", "colour", "=", "0x...
Creates an embed UI for when the API call didn't work Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
[ "Creates", "an", "embed", "UI", "for", "when", "the", "API", "call", "didn", "t", "work" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/rocketleague/ui_embed.py#L72-L90
train
41,269
ModisWorks/modis
modis/discord_modis/modules/gamedeals/ui_embed.py
success
def success(channel, post): """Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns: """ # Create datapacks datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)] # Create embed UI object gui = ui_embed.UI( channel, "Link", post[1], modulename=modulename, colour=0xFF8800, thumbnail=post[1], datapacks=datapacks ) return gui
python
def success(channel, post): """Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns: """ # Create datapacks datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)] # Create embed UI object gui = ui_embed.UI( channel, "Link", post[1], modulename=modulename, colour=0xFF8800, thumbnail=post[1], datapacks=datapacks ) return gui
[ "def", "success", "(", "channel", ",", "post", ")", ":", "# Create datapacks", "datapacks", "=", "[", "(", "\"Game\"", ",", "post", "[", "0", "]", ",", "True", ")", ",", "(", "\"Upvotes\"", ",", "post", "[", "2", "]", ",", "True", ")", "]", "# Crea...
Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns:
[ "Creates", "an", "embed", "UI", "containing", "the", "Reddit", "posts" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/gamedeals/ui_embed.py#L5-L30
train
41,270
ModisWorks/modis
modis/discord_modis/modules/gamedeals/ui_embed.py
no_results
def no_results(channel): """Creates an embed UI for when there were no results Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "No results", ":c", modulename=modulename, colour=0xFF8800 ) return gui
python
def no_results(channel): """Creates an embed UI for when there were no results Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object """ gui = ui_embed.UI( channel, "No results", ":c", modulename=modulename, colour=0xFF8800 ) return gui
[ "def", "no_results", "(", "channel", ")", ":", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"No results\"", ",", "\":c\"", ",", "modulename", "=", "modulename", ",", "colour", "=", "0xFF8800", ")", "return", "gui" ]
Creates an embed UI for when there were no results Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
[ "Creates", "an", "embed", "UI", "for", "when", "there", "were", "no", "results" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/gamedeals/ui_embed.py#L33-L51
train
41,271
ModisWorks/modis
modis/discord_modis/modules/music/_timebar.py
make_timebar
def make_timebar(progress=0, duration=0): """ Makes a new time bar string Args: progress: How far through the current song we are (in seconds) duration: The duration of the current song (in seconds) Returns: timebar (str): The time bar string """ duration_string = api_music.duration_to_string(duration) if duration <= 0: return "---" time_counts = int(round((progress / duration) * TIMEBAR_LENGTH)) if time_counts > TIMEBAR_LENGTH: time_counts = TIMEBAR_LENGTH if duration > 0: bar = "│" + (TIMEBAR_PCHAR * time_counts) + (TIMEBAR_ECHAR * (TIMEBAR_LENGTH - time_counts)) + "│" time_bar = "{} {}".format(bar, duration_string) else: time_bar = duration_string return time_bar
python
def make_timebar(progress=0, duration=0): """ Makes a new time bar string Args: progress: How far through the current song we are (in seconds) duration: The duration of the current song (in seconds) Returns: timebar (str): The time bar string """ duration_string = api_music.duration_to_string(duration) if duration <= 0: return "---" time_counts = int(round((progress / duration) * TIMEBAR_LENGTH)) if time_counts > TIMEBAR_LENGTH: time_counts = TIMEBAR_LENGTH if duration > 0: bar = "│" + (TIMEBAR_PCHAR * time_counts) + (TIMEBAR_ECHAR * (TIMEBAR_LENGTH - time_counts)) + "│" time_bar = "{} {}".format(bar, duration_string) else: time_bar = duration_string return time_bar
[ "def", "make_timebar", "(", "progress", "=", "0", ",", "duration", "=", "0", ")", ":", "duration_string", "=", "api_music", ".", "duration_to_string", "(", "duration", ")", "if", "duration", "<=", "0", ":", "return", "\"---\"", "time_counts", "=", "int", "...
Makes a new time bar string Args: progress: How far through the current song we are (in seconds) duration: The duration of the current song (in seconds) Returns: timebar (str): The time bar string
[ "Makes", "a", "new", "time", "bar", "string" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_timebar.py#L9-L35
train
41,272
ModisWorks/modis
modis/discord_modis/modules/_tools/ui_embed.py
UI.build
def build(self): """Builds Discord embed GUI Returns: discord.Embed: Built GUI """ if self.colour: embed = discord.Embed( title=self.title, type='rich', description=self.description, colour=self.colour) else: embed = discord.Embed( title=self.title, type='rich', description=self.description) if self.thumbnail: embed.set_thumbnail(url=self.thumbnail) if self.image: embed.set_image(url=self.image) embed.set_author( name="Modis", url="https://musicbyango.com/modis/", icon_url="http://musicbyango.com/modis/dp/modis64t.png") for pack in self.datapacks: embed.add_field( name=pack[0], value=pack[1], inline=pack[2] ) return embed
python
def build(self): """Builds Discord embed GUI Returns: discord.Embed: Built GUI """ if self.colour: embed = discord.Embed( title=self.title, type='rich', description=self.description, colour=self.colour) else: embed = discord.Embed( title=self.title, type='rich', description=self.description) if self.thumbnail: embed.set_thumbnail(url=self.thumbnail) if self.image: embed.set_image(url=self.image) embed.set_author( name="Modis", url="https://musicbyango.com/modis/", icon_url="http://musicbyango.com/modis/dp/modis64t.png") for pack in self.datapacks: embed.add_field( name=pack[0], value=pack[1], inline=pack[2] ) return embed
[ "def", "build", "(", "self", ")", ":", "if", "self", ".", "colour", ":", "embed", "=", "discord", ".", "Embed", "(", "title", "=", "self", ".", "title", ",", "type", "=", "'rich'", ",", "description", "=", "self", ".", "description", ",", "colour", ...
Builds Discord embed GUI Returns: discord.Embed: Built GUI
[ "Builds", "Discord", "embed", "GUI" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/_tools/ui_embed.py#L33-L70
train
41,273
ModisWorks/modis
modis/discord_modis/modules/_tools/ui_embed.py
UI.send
async def send(self): """Send new GUI""" await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
python
async def send(self): """Send new GUI""" await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
[ "async", "def", "send", "(", "self", ")", ":", "await", "client", ".", "send_typing", "(", "self", ".", "channel", ")", "self", ".", "sent_embed", "=", "await", "client", ".", "send_message", "(", "self", ".", "channel", ",", "embed", "=", "self", ".",...
Send new GUI
[ "Send", "new", "GUI" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/_tools/ui_embed.py#L72-L76
train
41,274
ModisWorks/modis
modis/discord_modis/modules/_tools/ui_embed.py
UI.update_data
def update_data(self, index, data): """Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack """ datapack = self.built_embed.to_dict()["fields"][index] self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])
python
def update_data(self, index, data): """Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack """ datapack = self.built_embed.to_dict()["fields"][index] self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])
[ "def", "update_data", "(", "self", ",", "index", ",", "data", ")", ":", "datapack", "=", "self", ".", "built_embed", ".", "to_dict", "(", ")", "[", "\"fields\"", "]", "[", "index", "]", "self", ".", "built_embed", ".", "set_field_at", "(", "index", ","...
Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack
[ "Updates", "a", "particular", "datapack", "s", "data" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/_tools/ui_embed.py#L96-L105
train
41,275
freelawproject/reporters-db
reporters_db/utils.py
suck_out_variations_only
def suck_out_variations_only(reporters): """Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possibly referring to. """ variations_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for variation_key, variation_value in data["variations"].items(): try: variations_list = variations_out[variation_key] if variation_value not in variations_list: variations_list.append(variation_value) except KeyError: # The item wasn't there; add it. variations_out[variation_key] = [variation_value] return variations_out
python
def suck_out_variations_only(reporters): """Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possibly referring to. """ variations_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for variation_key, variation_value in data["variations"].items(): try: variations_list = variations_out[variation_key] if variation_value not in variations_list: variations_list.append(variation_value) except KeyError: # The item wasn't there; add it. variations_out[variation_key] = [variation_value] return variations_out
[ "def", "suck_out_variations_only", "(", "reporters", ")", ":", "variations_out", "=", "{", "}", "for", "reporter_key", ",", "data_list", "in", "reporters", ".", "items", "(", ")", ":", "# For each reporter key...", "for", "data", "in", "data_list", ":", "# For e...
Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possibly referring to.
[ "Builds", "a", "dictionary", "of", "variations", "to", "canonical", "reporters", "." ]
ee17ee38a4e39de8d83beb78d84d146cd7e8afbc
https://github.com/freelawproject/reporters-db/blob/ee17ee38a4e39de8d83beb78d84d146cd7e8afbc/reporters_db/utils.py#L7-L34
train
41,276
freelawproject/reporters-db
reporters_db/utils.py
suck_out_editions
def suck_out_editions(reporters): """Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key. """ editions_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for edition_key, edition_value in data["editions"].items(): try: editions_out[edition_key] except KeyError: # The item wasn't there; add it. editions_out[edition_key] = reporter_key return editions_out
python
def suck_out_editions(reporters): """Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key. """ editions_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for edition_key, edition_value in data["editions"].items(): try: editions_out[edition_key] except KeyError: # The item wasn't there; add it. editions_out[edition_key] = reporter_key return editions_out
[ "def", "suck_out_editions", "(", "reporters", ")", ":", "editions_out", "=", "{", "}", "for", "reporter_key", ",", "data_list", "in", "reporters", ".", "items", "(", ")", ":", "# For each reporter key...", "for", "data", "in", "data_list", ":", "# For each book ...
Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key.
[ "Builds", "a", "dictionary", "mapping", "edition", "keys", "to", "their", "root", "name", "." ]
ee17ee38a4e39de8d83beb78d84d146cd7e8afbc
https://github.com/freelawproject/reporters-db/blob/ee17ee38a4e39de8d83beb78d84d146cd7e8afbc/reporters_db/utils.py#L37-L62
train
41,277
freelawproject/reporters-db
reporters_db/utils.py
names_to_abbreviations
def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key, data_list in reporters.items(): for data in data_list: abbrevs = data['editions'].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data['editions'][x]['start']) + x abbrevs = sorted(abbrevs, key=sort_func) names[data['name']] = abbrevs sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0])) return sorted_names
python
def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key, data_list in reporters.items(): for data in data_list: abbrevs = data['editions'].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data['editions'][x]['start']) + x abbrevs = sorted(abbrevs, key=sort_func) names[data['name']] = abbrevs sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0])) return sorted_names
[ "def", "names_to_abbreviations", "(", "reporters", ")", ":", "names", "=", "{", "}", "for", "reporter_key", ",", "data_list", "in", "reporters", ".", "items", "(", ")", ":", "for", "data", "in", "data_list", ":", "abbrevs", "=", "data", "[", "'editions'", ...
Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date.
[ "Build", "a", "dict", "mapping", "names", "to", "their", "variations" ]
ee17ee38a4e39de8d83beb78d84d146cd7e8afbc
https://github.com/freelawproject/reporters-db/blob/ee17ee38a4e39de8d83beb78d84d146cd7e8afbc/reporters_db/utils.py#L65-L85
train
41,278
ModisWorks/modis
modis/discord_modis/modules/bethebot/_ui.py
runcoro
def runcoro(async_function): """ Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run """ future = _asyncio.run_coroutine_threadsafe(async_function, client.loop) result = future.result() return result
python
def runcoro(async_function): """ Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run """ future = _asyncio.run_coroutine_threadsafe(async_function, client.loop) result = future.result() return result
[ "def", "runcoro", "(", "async_function", ")", ":", "future", "=", "_asyncio", ".", "run_coroutine_threadsafe", "(", "async_function", ",", "client", ".", "loop", ")", "result", "=", "future", ".", "result", "(", ")", "return", "result" ]
Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run
[ "Runs", "an", "asynchronous", "function", "without", "needing", "to", "use", "await", "-", "useful", "for", "lambda" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/bethebot/_ui.py#L98-L108
train
41,279
ModisWorks/modis
modis/discord_modis/modules/manager/api_manager.py
warn_user
async def warn_user(channel, user): """ Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3 if "warnings" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings"] = {} if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] += 1 else: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 1 datatools.write_data(data) warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] max_warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] await client.send_typing(channel) embed = ui_embed.user_warning(channel, user, warnings, max_warnings) await embed.send() if warnings >= max_warnings: await ban_user(channel, user)
python
async def warn_user(channel, user): """ Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3 if "warnings" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings"] = {} if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] += 1 else: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 1 datatools.write_data(data) warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] max_warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] await client.send_typing(channel) embed = ui_embed.user_warning(channel, user, warnings, max_warnings) await embed.send() if warnings >= max_warnings: await ban_user(channel, user)
[ "async", "def", "warn_user", "(", "channel", ",", "user", ")", ":", "data", "=", "datatools", ".", "get_data", "(", ")", "server_id", "=", "channel", ".", "server", ".", "id", "if", "\"warnings_max\"", "not", "in", "data", "[", "\"discord\"", "]", "[", ...
Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to
[ "Gives", "a", "user", "a", "warning", "and", "bans", "them", "if", "they", "are", "over", "the", "maximum", "warnings" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/manager/api_manager.py#L74-L106
train
41,280
ModisWorks/modis
modis/discord_modis/modules/manager/api_manager.py
ban_user
async def ban_user(channel, user): """ Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id try: await client.ban(user) except discord.errors.Forbidden: await client.send_typing(channel) embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.") await embed.send() return # Set the user's warnings to 0 if "warnings" in data["discord"]["servers"][server_id][_data.modulename]: if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 0 datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.user_ban(channel, user) await embed.send() try: response = "You have been banned from the server '{}' " \ "contact the owners to resolve this issue.".format(channel.server.name) await client.send_message(user, response) except Exception as e: logger.exception(e)
python
async def ban_user(channel, user): """ Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to """ data = datatools.get_data() server_id = channel.server.id try: await client.ban(user) except discord.errors.Forbidden: await client.send_typing(channel) embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.") await embed.send() return # Set the user's warnings to 0 if "warnings" in data["discord"]["servers"][server_id][_data.modulename]: if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 0 datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.user_ban(channel, user) await embed.send() try: response = "You have been banned from the server '{}' " \ "contact the owners to resolve this issue.".format(channel.server.name) await client.send_message(user, response) except Exception as e: logger.exception(e)
[ "async", "def", "ban_user", "(", "channel", ",", "user", ")", ":", "data", "=", "datatools", ".", "get_data", "(", ")", "server_id", "=", "channel", ".", "server", ".", "id", "try", ":", "await", "client", ".", "ban", "(", "user", ")", "except", "dis...
Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to
[ "Bans", "a", "user", "from", "a", "server" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/manager/api_manager.py#L109-L144
train
41,281
ModisWorks/modis
modis/discord_modis/modules/help/api_help.py
get_help_datapacks
def get_help_datapacks(module_name, server_prefix): """ Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module """ _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) module_dir = "{}/../{}".format(_dir, module_name, "_help.json") if os.path.isdir(module_dir): module_help_path = "{}/{}".format(module_dir, "_help.json") if os.path.isfile(module_help_path): return helptools.get_help_datapacks(module_help_path, server_prefix) else: return [("Help", "{} does not have a help.json file".format(module_name), False)] else: return [("Help", "No module found called {}".format(module_name), False)]
python
def get_help_datapacks(module_name, server_prefix): """ Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module """ _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) module_dir = "{}/../{}".format(_dir, module_name, "_help.json") if os.path.isdir(module_dir): module_help_path = "{}/{}".format(module_dir, "_help.json") if os.path.isfile(module_help_path): return helptools.get_help_datapacks(module_help_path, server_prefix) else: return [("Help", "{} does not have a help.json file".format(module_name), False)] else: return [("Help", "No module found called {}".format(module_name), False)]
[ "def", "get_help_datapacks", "(", "module_name", ",", "server_prefix", ")", ":", "_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "path", ".", "dirname", "(", ...
Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module
[ "Get", "the", "help", "datapacks", "for", "a", "module" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/help/api_help.py#L6-L29
train
41,282
ModisWorks/modis
modis/discord_modis/modules/help/api_help.py
get_help_commands
def get_help_commands(server_prefix): """ Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules """ datapacks = [] _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) for module_name in os.listdir("{}/../".format(_dir)): if not module_name.startswith("_") and not module_name.startswith("!"): help_command = "`{}help {}`".format(server_prefix, module_name) datapacks.append((module_name, help_command, True)) return datapacks
python
def get_help_commands(server_prefix): """ Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules """ datapacks = [] _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) for module_name in os.listdir("{}/../".format(_dir)): if not module_name.startswith("_") and not module_name.startswith("!"): help_command = "`{}help {}`".format(server_prefix, module_name) datapacks.append((module_name, help_command, True)) return datapacks
[ "def", "get_help_commands", "(", "server_prefix", ")", ":", "datapacks", "=", "[", "]", "_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "path", ".", "dirname"...
Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules
[ "Get", "the", "help", "commands", "for", "all", "modules" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/help/api_help.py#L32-L52
train
41,283
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
clear_cache_root
def clear_cache_root(): """Clears everything in the song cache""" logger.debug("Clearing root cache") if os.path.isdir(_root_songcache_dir): for filename in os.listdir(_root_songcache_dir): file_path = os.path.join(_root_songcache_dir, filename) try: if os.path.isfile(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except PermissionError: pass except Exception as e: logger.exception(e) logger.debug("Root cache cleared")
python
def clear_cache_root(): """Clears everything in the song cache""" logger.debug("Clearing root cache") if os.path.isdir(_root_songcache_dir): for filename in os.listdir(_root_songcache_dir): file_path = os.path.join(_root_songcache_dir, filename) try: if os.path.isfile(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except PermissionError: pass except Exception as e: logger.exception(e) logger.debug("Root cache cleared")
[ "def", "clear_cache_root", "(", ")", ":", "logger", ".", "debug", "(", "\"Clearing root cache\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "_root_songcache_dir", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "_root_songcache_dir", ")"...
Clears everything in the song cache
[ "Clears", "everything", "in", "the", "song", "cache" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L25-L40
train
41,284
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.play
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False): """ The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end of the queue stop_current (bool): Whether to stop the currently playing song shuffle (bool): Whether to shuffle the queue after starting """ if self.state == 'off': self.state = 'starting' self.prev_queue = [] await self.set_topic("") # Init the music player await self.msetup(text_channel) # Queue the song await self.enqueue(query, index, stop_current, shuffle) # Connect to voice await self.vsetup(author) # Mark as 'ready' if everything is ok self.state = 'ready' if self.mready and self.vready else 'off' else: # Queue the song await self.enqueue(query, index, stop_current, shuffle) if self.state == 'ready': if self.streamer is None: await self.vplay()
python
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False): """ The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end of the queue stop_current (bool): Whether to stop the currently playing song shuffle (bool): Whether to shuffle the queue after starting """ if self.state == 'off': self.state = 'starting' self.prev_queue = [] await self.set_topic("") # Init the music player await self.msetup(text_channel) # Queue the song await self.enqueue(query, index, stop_current, shuffle) # Connect to voice await self.vsetup(author) # Mark as 'ready' if everything is ok self.state = 'ready' if self.mready and self.vready else 'off' else: # Queue the song await self.enqueue(query, index, stop_current, shuffle) if self.state == 'ready': if self.streamer is None: await self.vplay()
[ "async", "def", "play", "(", "self", ",", "author", ",", "text_channel", ",", "query", ",", "index", "=", "None", ",", "stop_current", "=", "False", ",", "shuffle", "=", "False", ")", ":", "if", "self", ".", "state", "==", "'off'", ":", "self", ".", ...
The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end of the queue stop_current (bool): Whether to stop the currently playing song shuffle (bool): Whether to shuffle the queue after starting
[ "The", "play", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L162-L194
train
41,285
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.destroy
async def destroy(self): """Destroy the whole gui and music player""" self.logger.debug("destroy command") self.state = 'destroyed' await self.set_topic("") self.nowplayinglog.debug("---") self.nowplayingauthorlog.debug("---") self.nowplayingsourcelog.debug("---") self.timelog.debug(_timebar.make_timebar()) self.prev_time = "---" self.statuslog.debug("Destroying") self.mready = False self.vready = False self.pause_time = None self.loop_type = 'off' if self.vclient: try: await self.vclient.disconnect() except Exception as e: logger.error(e) pass if self.streamer: try: self.streamer.stop() except: pass self.vclient = None self.vchannel = None self.streamer = None self.current_duration = 0 self.current_download_elapsed = 0 self.is_live = False self.queue = [] self.prev_queue = [] if self.embed: await self.embed.delete() self.embed = None self.clear_cache()
python
async def destroy(self): """Destroy the whole gui and music player""" self.logger.debug("destroy command") self.state = 'destroyed' await self.set_topic("") self.nowplayinglog.debug("---") self.nowplayingauthorlog.debug("---") self.nowplayingsourcelog.debug("---") self.timelog.debug(_timebar.make_timebar()) self.prev_time = "---" self.statuslog.debug("Destroying") self.mready = False self.vready = False self.pause_time = None self.loop_type = 'off' if self.vclient: try: await self.vclient.disconnect() except Exception as e: logger.error(e) pass if self.streamer: try: self.streamer.stop() except: pass self.vclient = None self.vchannel = None self.streamer = None self.current_duration = 0 self.current_download_elapsed = 0 self.is_live = False self.queue = [] self.prev_queue = [] if self.embed: await self.embed.delete() self.embed = None self.clear_cache()
[ "async", "def", "destroy", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"destroy command\"", ")", "self", ".", "state", "=", "'destroyed'", "await", "self", ".", "set_topic", "(", "\"\"", ")", "self", ".", "nowplayinglog", ".", "deb...
Destroy the whole gui and music player
[ "Destroy", "the", "whole", "gui", "and", "music", "player" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L256-L301
train
41,286
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.toggle
async def toggle(self): """Toggles between pause and resume command""" self.logger.debug("toggle command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): await self.pause() else: await self.resume() except Exception as e: logger.error(e) pass
python
async def toggle(self): """Toggles between pause and resume command""" self.logger.debug("toggle command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): await self.pause() else: await self.resume() except Exception as e: logger.error(e) pass
[ "async", "def", "toggle", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"toggle command\"", ")", "if", "not", "self", ".", "state", "==", "'ready'", ":", "return", "if", "self", ".", "streamer", "is", "None", ":", "return", "try", ...
Toggles between pause and resume command
[ "Toggles", "between", "pause", "and", "resume", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L303-L321
train
41,287
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.pause
async def pause(self): """Pauses playback if playing""" self.logger.debug("pause command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): self.streamer.pause() self.pause_time = self.vclient.loop.time() self.statuslog.info("Paused") except Exception as e: logger.error(e) pass
python
async def pause(self): """Pauses playback if playing""" self.logger.debug("pause command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): self.streamer.pause() self.pause_time = self.vclient.loop.time() self.statuslog.info("Paused") except Exception as e: logger.error(e) pass
[ "async", "def", "pause", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"pause command\"", ")", "if", "not", "self", ".", "state", "==", "'ready'", ":", "return", "if", "self", ".", "streamer", "is", "None", ":", "return", "try", ...
Pauses playback if playing
[ "Pauses", "playback", "if", "playing" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L323-L341
train
41,288
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.resume
async def resume(self): """Resumes playback if paused""" self.logger.debug("resume command") if not self.state == 'ready': return if self.streamer is None: return try: if not self.streamer.is_playing(): play_state = "Streaming" if self.is_live else "Playing" self.statuslog.info(play_state) self.streamer.resume() if self.pause_time is not None: self.vclient_starttime += (self.vclient.loop.time() - self.pause_time) self.pause_time = None except Exception as e: logger.error(e) pass
python
async def resume(self): """Resumes playback if paused""" self.logger.debug("resume command") if not self.state == 'ready': return if self.streamer is None: return try: if not self.streamer.is_playing(): play_state = "Streaming" if self.is_live else "Playing" self.statuslog.info(play_state) self.streamer.resume() if self.pause_time is not None: self.vclient_starttime += (self.vclient.loop.time() - self.pause_time) self.pause_time = None except Exception as e: logger.error(e) pass
[ "async", "def", "resume", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"resume command\"", ")", "if", "not", "self", ".", "state", "==", "'ready'", ":", "return", "if", "self", ".", "streamer", "is", "None", ":", "return", "try", ...
Resumes playback if paused
[ "Resumes", "playback", "if", "paused" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L343-L365
train
41,289
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.skip
async def skip(self, query="1"): """The skip command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to skip from wrong state '{}'".format(self.state)) return if query == "": query = "1" elif query == "all": query = str(len(self.queue) + 1) try: num = int(query) except TypeError: self.statuslog.error("Skip argument must be a number") except ValueError: self.statuslog.error("Skip argument must be a number") else: self.statuslog.info("Skipping") for i in range(num - 1): if len(self.queue) > 0: self.prev_queue.append(self.queue.pop(0)) try: self.streamer.stop() except Exception as e: logger.exception(e)
python
async def skip(self, query="1"): """The skip command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to skip from wrong state '{}'".format(self.state)) return if query == "": query = "1" elif query == "all": query = str(len(self.queue) + 1) try: num = int(query) except TypeError: self.statuslog.error("Skip argument must be a number") except ValueError: self.statuslog.error("Skip argument must be a number") else: self.statuslog.info("Skipping") for i in range(num - 1): if len(self.queue) > 0: self.prev_queue.append(self.queue.pop(0)) try: self.streamer.stop() except Exception as e: logger.exception(e)
[ "async", "def", "skip", "(", "self", ",", "query", "=", "\"1\"", ")", ":", "if", "not", "self", ".", "state", "==", "'ready'", ":", "logger", ".", "debug", "(", "\"Trying to skip from wrong state '{}'\"", ".", "format", "(", "self", ".", "state", ")", ")...
The skip command Args: query (str): The number of items to skip
[ "The", "skip", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L367-L399
train
41,290
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.remove
async def remove(self, index=""): """ The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##' """ if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.state)) return if index == "": self.statuslog.error("Must provide index to remove") return elif index == "all": self.queue = [] self.update_queue() self.statuslog.info("Removed all songs") return indexes = index.split("-") self.logger.debug("Removing {}".format(indexes)) try: if len(indexes) == 0: self.statuslog.error("Remove must specify an index or range") return elif len(indexes) == 1: num_lower = int(indexes[0]) - 1 num_upper = num_lower + 1 elif len(indexes) == 2: num_lower = int(indexes[0]) - 1 num_upper = int(indexes[1]) else: self.statuslog.error("Cannot have more than 2 indexes for remove range") return except TypeError: self.statuslog.error("Remove index must be a number") return except ValueError: self.statuslog.error("Remove index must be a number") return if num_lower < 0 or num_lower >= len(self.queue) or num_upper > len(self.queue): if len(self.queue) == 0: self.statuslog.warning("No songs in queue") elif len(self.queue) == 1: self.statuslog.error("Remove index must be 1 (only 1 song in queue)") else: self.statuslog.error("Remove index must be between 1 and {}".format(len(self.queue))) return if num_upper <= num_lower: self.statuslog.error("Second index in range must be greater than first") return lower_songname = self.queue[num_lower][1] for num in range(0, num_upper - num_lower): self.logger.debug("Removed {}".format(self.queue[num_lower][1])) self.queue.pop(num_lower) if len(indexes) == 1: self.statuslog.info("Removed {}".format(lower_songname)) else: self.statuslog.info("Removed songs {}-{}".format(num_lower + 1, num_upper)) self.update_queue()
python
async def remove(self, index=""): """ The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##' """ if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.state)) return if index == "": self.statuslog.error("Must provide index to remove") return elif index == "all": self.queue = [] self.update_queue() self.statuslog.info("Removed all songs") return indexes = index.split("-") self.logger.debug("Removing {}".format(indexes)) try: if len(indexes) == 0: self.statuslog.error("Remove must specify an index or range") return elif len(indexes) == 1: num_lower = int(indexes[0]) - 1 num_upper = num_lower + 1 elif len(indexes) == 2: num_lower = int(indexes[0]) - 1 num_upper = int(indexes[1]) else: self.statuslog.error("Cannot have more than 2 indexes for remove range") return except TypeError: self.statuslog.error("Remove index must be a number") return except ValueError: self.statuslog.error("Remove index must be a number") return if num_lower < 0 or num_lower >= len(self.queue) or num_upper > len(self.queue): if len(self.queue) == 0: self.statuslog.warning("No songs in queue") elif len(self.queue) == 1: self.statuslog.error("Remove index must be 1 (only 1 song in queue)") else: self.statuslog.error("Remove index must be between 1 and {}".format(len(self.queue))) return if num_upper <= num_lower: self.statuslog.error("Second index in range must be greater than first") return lower_songname = self.queue[num_lower][1] for num in range(0, num_upper - num_lower): self.logger.debug("Removed {}".format(self.queue[num_lower][1])) self.queue.pop(num_lower) if len(indexes) == 1: self.statuslog.info("Removed {}".format(lower_songname)) else: self.statuslog.info("Removed songs {}-{}".format(num_lower + 1, num_upper)) self.update_queue()
[ "async", "def", "remove", "(", "self", ",", "index", "=", "\"\"", ")", ":", "if", "not", "self", ".", "state", "==", "'ready'", ":", "logger", ".", "debug", "(", "\"Trying to remove from wrong state '{}'\"", ".", "format", "(", "self", ".", "state", ")", ...
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
[ "The", "remove", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L401-L468
train
41,291
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.rewind
async def rewind(self, query="1"): """ The rewind command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to rewind from wrong state '{}'".format(self.state)) return if query == "": query = "1" try: num = int(query) except TypeError: self.statuslog.error("Rewind argument must be a number") except ValueError: self.statuslog.error("Rewind argument must be a number") else: if len(self.prev_queue) == 0: self.statuslog.error("No songs to rewind") return if num < 0: self.statuslog.error("Rewind must be postitive or 0") return elif num > len(self.prev_queue): self.statuslog.warning("Rewinding to start") else: self.statuslog.info("Rewinding") for i in range(num + 1): if len(self.prev_queue) > 0: self.queue.insert(0, self.prev_queue.pop()) try: self.streamer.stop() except Exception as e: logger.exception(e)
python
async def rewind(self, query="1"): """ The rewind command Args: query (str): The number of items to skip """ if not self.state == 'ready': logger.debug("Trying to rewind from wrong state '{}'".format(self.state)) return if query == "": query = "1" try: num = int(query) except TypeError: self.statuslog.error("Rewind argument must be a number") except ValueError: self.statuslog.error("Rewind argument must be a number") else: if len(self.prev_queue) == 0: self.statuslog.error("No songs to rewind") return if num < 0: self.statuslog.error("Rewind must be postitive or 0") return elif num > len(self.prev_queue): self.statuslog.warning("Rewinding to start") else: self.statuslog.info("Rewinding") for i in range(num + 1): if len(self.prev_queue) > 0: self.queue.insert(0, self.prev_queue.pop()) try: self.streamer.stop() except Exception as e: logger.exception(e)
[ "async", "def", "rewind", "(", "self", ",", "query", "=", "\"1\"", ")", ":", "if", "not", "self", ".", "state", "==", "'ready'", ":", "logger", ".", "debug", "(", "\"Trying to rewind from wrong state '{}'\"", ".", "format", "(", "self", ".", "state", ")", ...
The rewind command Args: query (str): The number of items to skip
[ "The", "rewind", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L470-L511
train
41,292
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.shuffle
async def shuffle(self): """The shuffle command""" self.logger.debug("shuffle command") if not self.state == 'ready': return self.statuslog.debug("Shuffling") random.shuffle(self.queue) self.update_queue() self.statuslog.debug("Shuffled")
python
async def shuffle(self): """The shuffle command""" self.logger.debug("shuffle command") if not self.state == 'ready': return self.statuslog.debug("Shuffling") random.shuffle(self.queue) self.update_queue() self.statuslog.debug("Shuffled")
[ "async", "def", "shuffle", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"shuffle command\"", ")", "if", "not", "self", ".", "state", "==", "'ready'", ":", "return", "self", ".", "statuslog", ".", "debug", "(", "\"Shuffling\"", ")", ...
The shuffle command
[ "The", "shuffle", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L513-L526
train
41,293
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.set_loop
async def set_loop(self, loop_value): """Updates the loop value, can be 'off', 'on', or 'shuffle'""" if loop_value not in ['on', 'off', 'shuffle']: self.statuslog.error("Loop value must be `off`, `on`, or `shuffle`") return self.loop_type = loop_value if self.loop_type == 'on': self.statuslog.info("Looping on") elif self.loop_type == 'off': self.statuslog.info("Looping off") elif self.loop_type == 'shuffle': self.statuslog.info("Looping on and shuffling")
python
async def set_loop(self, loop_value): """Updates the loop value, can be 'off', 'on', or 'shuffle'""" if loop_value not in ['on', 'off', 'shuffle']: self.statuslog.error("Loop value must be `off`, `on`, or `shuffle`") return self.loop_type = loop_value if self.loop_type == 'on': self.statuslog.info("Looping on") elif self.loop_type == 'off': self.statuslog.info("Looping off") elif self.loop_type == 'shuffle': self.statuslog.info("Looping on and shuffling")
[ "async", "def", "set_loop", "(", "self", ",", "loop_value", ")", ":", "if", "loop_value", "not", "in", "[", "'on'", ",", "'off'", ",", "'shuffle'", "]", ":", "self", ".", "statuslog", ".", "error", "(", "\"Loop value must be `off`, `on`, or `shuffle`\"", ")", ...
Updates the loop value, can be 'off', 'on', or 'shuffle
[ "Updates", "the", "loop", "value", "can", "be", "off", "on", "or", "shuffle" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L528-L540
train
41,294
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.setvolume
async def setvolume(self, value): """The volume command Args: value (str): The value to set the volume to """ self.logger.debug("volume command") if self.state != 'ready': return logger.debug("Volume command received") if value == '+': if self.volume < 100: self.statuslog.debug("Volume up") self.volume = (10 * (self.volume // 10)) + 10 self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.warning("Already at maximum volume") elif value == '-': if self.volume > 0: self.statuslog.debug("Volume down") self.volume = (10 * ((self.volume + 9) // 10)) - 10 self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.warning("Already at minimum volume") else: try: value = int(value) except ValueError: self.statuslog.error("Volume argument must be +, -, or a %") else: if 0 <= value <= 200: self.statuslog.debug("Setting volume") self.volume = value self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.error("Volume must be between 0 and 200") self.write_volume()
python
async def setvolume(self, value): """The volume command Args: value (str): The value to set the volume to """ self.logger.debug("volume command") if self.state != 'ready': return logger.debug("Volume command received") if value == '+': if self.volume < 100: self.statuslog.debug("Volume up") self.volume = (10 * (self.volume // 10)) + 10 self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.warning("Already at maximum volume") elif value == '-': if self.volume > 0: self.statuslog.debug("Volume down") self.volume = (10 * ((self.volume + 9) // 10)) - 10 self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.warning("Already at minimum volume") else: try: value = int(value) except ValueError: self.statuslog.error("Volume argument must be +, -, or a %") else: if 0 <= value <= 200: self.statuslog.debug("Setting volume") self.volume = value self.volumelog.info(str(self.volume)) try: self.streamer.volume = self.volume / 100 except AttributeError: pass else: self.statuslog.error("Volume must be between 0 and 200") self.write_volume()
[ "async", "def", "setvolume", "(", "self", ",", "value", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"volume command\"", ")", "if", "self", ".", "state", "!=", "'ready'", ":", "return", "logger", ".", "debug", "(", "\"Volume command received\"", "...
The volume command Args: value (str): The value to set the volume to
[ "The", "volume", "command" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L542-L597
train
41,295
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.write_volume
def write_volume(self): """Writes the current volume to the data.json""" # Update the volume data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume datatools.write_data(data)
python
def write_volume(self): """Writes the current volume to the data.json""" # Update the volume data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume datatools.write_data(data)
[ "def", "write_volume", "(", "self", ")", ":", "# Update the volume", "data", "=", "datatools", ".", "get_data", "(", ")", "data", "[", "\"discord\"", "]", "[", "\"servers\"", "]", "[", "self", ".", "server_id", "]", "[", "_data", ".", "modulename", "]", ...
Writes the current volume to the data.json
[ "Writes", "the", "current", "volume", "to", "the", "data", ".", "json" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L599-L604
train
41,296
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.movehere
async def movehere(self, channel): """ Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to """ self.logger.debug("movehere command") # Delete the old message await self.embed.delete() # Set the channel to this channel self.embed.channel = channel # Send a new embed to the channel await self.embed.send() # Re-add the reactions await self.add_reactions() self.statuslog.info("Moved to front")
python
async def movehere(self, channel): """ Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to """ self.logger.debug("movehere command") # Delete the old message await self.embed.delete() # Set the channel to this channel self.embed.channel = channel # Send a new embed to the channel await self.embed.send() # Re-add the reactions await self.add_reactions() self.statuslog.info("Moved to front")
[ "async", "def", "movehere", "(", "self", ",", "channel", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"movehere command\"", ")", "# Delete the old message", "await", "self", ".", "embed", ".", "delete", "(", ")", "# Set the channel to this channel", "se...
Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to
[ "Moves", "the", "embed", "message", "to", "a", "new", "channel", ";", "can", "also", "be", "used", "to", "move", "the", "musicplayer", "to", "the", "front" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L606-L625
train
41,297
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.vsetup
async def vsetup(self, author): """Creates the voice client Args: author (discord.Member): The user that the voice ui will seek """ if self.vready: logger.warning("Attempt to init voice when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debug("Setting up voice") # Create voice client self.vchannel = author.voice.voice_channel if self.vchannel: self.statuslog.info("Connecting to voice") try: self.vclient = await client.join_voice_channel(self.vchannel) except discord.ClientException as e: logger.exception(e) self.statuslog.warning("I'm already connected to a voice channel.") return except discord.opus.OpusNotLoaded as e: logger.exception(e) logger.error("Could not load Opus. This is an error with your FFmpeg setup.") self.statuslog.error("Could not load Opus.") return except discord.DiscordException as e: logger.exception(e) self.statuslog.error("I couldn't connect to the voice channel. Check my permissions.") return except Exception as e: self.statuslog.error("Internal error connecting to voice, disconnecting.") logger.error("Error connecting to voice {}".format(e)) return else: self.statuslog.error("You're not connected to a voice channel.") return self.vready = True
python
async def vsetup(self, author): """Creates the voice client Args: author (discord.Member): The user that the voice ui will seek """ if self.vready: logger.warning("Attempt to init voice when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debug("Setting up voice") # Create voice client self.vchannel = author.voice.voice_channel if self.vchannel: self.statuslog.info("Connecting to voice") try: self.vclient = await client.join_voice_channel(self.vchannel) except discord.ClientException as e: logger.exception(e) self.statuslog.warning("I'm already connected to a voice channel.") return except discord.opus.OpusNotLoaded as e: logger.exception(e) logger.error("Could not load Opus. This is an error with your FFmpeg setup.") self.statuslog.error("Could not load Opus.") return except discord.DiscordException as e: logger.exception(e) self.statuslog.error("I couldn't connect to the voice channel. Check my permissions.") return except Exception as e: self.statuslog.error("Internal error connecting to voice, disconnecting.") logger.error("Error connecting to voice {}".format(e)) return else: self.statuslog.error("You're not connected to a voice channel.") return self.vready = True
[ "async", "def", "vsetup", "(", "self", ",", "author", ")", ":", "if", "self", ".", "vready", ":", "logger", ".", "warning", "(", "\"Attempt to init voice when already initialised\"", ")", "return", "if", "self", ".", "state", "!=", "'starting'", ":", "logger",...
Creates the voice client Args: author (discord.Member): The user that the voice ui will seek
[ "Creates", "the", "voice", "client" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L660-L704
train
41,298
ModisWorks/modis
modis/discord_modis/modules/music/_musicplayer.py
MusicPlayer.msetup
async def msetup(self, text_channel): """Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in """ if self.mready: logger.warning("Attempt to init music when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debug("Setting up gui") # Create gui self.mchannel = text_channel self.new_embed_ui() await self.embed.send() await self.embed.usend() await self.add_reactions() self.mready = True
python
async def msetup(self, text_channel): """Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in """ if self.mready: logger.warning("Attempt to init music when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debug("Setting up gui") # Create gui self.mchannel = text_channel self.new_embed_ui() await self.embed.send() await self.embed.usend() await self.add_reactions() self.mready = True
[ "async", "def", "msetup", "(", "self", ",", "text_channel", ")", ":", "if", "self", ".", "mready", ":", "logger", ".", "warning", "(", "\"Attempt to init music when already initialised\"", ")", "return", "if", "self", ".", "state", "!=", "'starting'", ":", "lo...
Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in
[ "Creates", "the", "gui" ]
1f1225c9841835ec1d1831fc196306527567db8b
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/music/_musicplayer.py#L706-L730
train
41,299