docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Executes a prepared CQL (Cassandra Query Language) statement by passing an id token and a list of variables
to bind and returns a CqlResult containing the results.
Parameters:
- itemId
- values | def execute_prepared_cql_query(self, itemId, values):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_execute_prepared_cql_query(itemId, values)
return d | 673,020 |
@deprecated This is now a no-op. Please use the CQL3 specific methods instead.
Parameters:
- version | def set_cql_version(self, version):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_set_cql_version(version)
return d | 673,024 |
Return the topmost item located at ``pos`` (x, y).
Parameters:
- selected: if False returns first non-selected item
- exclude: if specified don't check for these items | def get_item_at_point_exclude(self, pos, selected=True, exclude=None):
items = self._qtree.find_intersect((pos[0], pos[1], 1, 1))
for item in self._canvas.sort(items, reverse=True):
if not selected and item in self.selected_items:
continue # skip selected items
... | 675,178 |
Initialize a wrapper for the array
Args:
ary: (list-like, or ArrayWrapper) | def __init__(self, ary):
self._dirty = True
self._typed = None
if isinstance(ary, (list, tuple, collections.Sequence)):
self.data = ary
elif isinstance(ary, ArrayWrapper):
self.data = ary.data
else:
raise TypeError... | 676,192 |
Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
An object of the generated type
... | def from_json(cls, jsonmsg):
import json
msg = json.loads(jsonmsg)
obj = cls(**msg)
obj.validate()
return obj | 676,241 |
Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values | def eval_features(json):
return {'close' : json[-1]['close'],
'sma' : SMA.eval_from_json(json),
'rsi' : RSI.eval_from_json(json),
'so' : SO.eval_from_json(json),
'obv' : OBV.eval_from_json(json)} | 676,486 |
Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code. | def target_code_to_name(code):
TARGET_NAMES = {v: k for k, v in TARGET_CODES.items()}
return TARGET_NAMES[code] | 676,487 |
Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
seed: Random state to use when splitting sets and creating the model
**k... | def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
assert len(x) > 1 and len(y) > 1, 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))'.format(len(x), len(y))
sets = namedtuple('Datasets', ['train', 'test'])
x_train, x_test, y_train, y_... | 676,488 |
Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with columns as numpy.float32 features. | def set_features(self, partition=1):
if len(self.json) < partition + 1:
raise ValueError('Not enough dates for the specified partition size: {0}. Try a smaller partition.'.format(partition))
data = []
for offset in range(len(self.json) - partition):
json = self... | 676,491 |
Inits a Random Forest Classifier with a market attribute
Args:
**kwargs: Scikit Learn's RandomForestClassifier kwargs | def __init__(self, features, targets, **kwargs):
# Init model
super().__init__(**kwargs)
# Set axes
self.features = features
self.targets = targets
# Train model
self.fit(features.train, targets.train) | 676,495 |
Evaluates OBV
Args:
curr: Dict of current volume and close
prev: Dict of previous OBV and close
Returns:
Float of OBV | def eval_algorithm(curr, prev):
if curr['close'] > prev['close']:
v = curr['volume']
elif curr['close'] < prev['close']:
v = curr['volume'] * -1
else:
v = 0
return prev['obv'] + v | 676,522 |
Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV | def eval_from_json(json):
closes = poloniex.get_attribute(json, 'close')
volumes = poloniex.get_attribute(json, 'volume')
obv = 0
for date in range(1, len(json)):
curr = {'close': closes[date], 'volume': volumes[date]}
prev = {'close': closes[date - 1], '... | 676,523 |
Evaluates the RS variable in RSI algorithm
Args:
gains: List of price gains.
losses: List of prices losses.
Returns:
Float of average gains over average losses. | def eval_rs(gains, losses):
# Number of days that the data was collected through
count = len(gains) + len(losses)
avg_gains = stats.avg(gains, count=count) if gains else 1
avg_losses = stats.avg(losses,count=count) if losses else 1
if avg_losses == 0:
return... | 676,596 |
Evaluates RSI from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float between 0 and 100, momentum indicator
of a market measuring the speed and change of price movements. | def eval_from_json(json):
changes = poloniex.get_gains_losses(poloniex.parse_changes(json))
return RSI.eval_algorithm(changes['gains'], changes['losses']) | 676,597 |
Converts a JSON to a URL by the Poloniex API
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
symbol: String of currency pair, like a ticker symbol.
Returns:
String URL to Poloniex API representing the given JSON. | def json_to_url(json, symbol):
start = json[0]['date']
end = json[-1]['date']
diff = end - start
# Get period by a ratio from calculated period to valid periods
# Ratio closest to 1 is the period
# Valid values: 300, 900, 1800, 7200, 14400, 86400
periods = [300, 900, 1800, 7200, 14400,... | 676,606 |
Gets price changes from JSON
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
List of floats of price changes between entries in JSON. | def parse_changes(json):
changes = []
dates = len(json)
for date in range(1, dates):
last_close = json[date - 1]['close']
now_close = json[date]['close']
changes.append(now_close - last_close)
logger.debug('Market Changes (from JSON):\n{0}'.format(changes))
return chang... | 676,608 |
Categorizes changes into gains and losses
Args:
changes: List of floats of price changes between entries in JSON.
Returns:
Dict of changes with keys 'gains' and 'losses'.
All values are positive. | def get_gains_losses(changes):
res = {'gains': [], 'losses': []}
for change in changes:
if change > 0:
res['gains'].append(change)
else:
res['losses'].append(change * -1)
logger.debug('Gains: {0}'.format(res['gains']))
logger.debug('Losses: {0}'.format(res['l... | 676,609 |
Gets the values of an attribute from JSON
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
attr: String of attribute in JSON file to collect.
Returns:
List of values of specified attribute from JSON | def get_attribute(json, attr):
res = [json[entry][attr] for entry, _ in enumerate(json)]
logger.debug('{0}s (from JSON):\n{1}'.format(attr, res))
return res | 676,610 |
Evaluates the SO algorithm
Args:
closing: Float of current closing price.
low: Float of lowest low closing price throughout some duration.
high: Float of highest high closing price throughout some duration.
Returns:
Float SO between 0 and 100. | def eval_algorithm(closing, low, high):
if high - low == 0: # High and low are the same, zero division error
return 100 * (closing - low)
else:
return 100 * (closing - low) / (high - low) | 676,629 |
Evaluates SO from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float SO between 0 and 100. | def eval_from_json(json):
close = json[-1]['close'] # Latest closing price
low = min(poloniex.get_attribute(json, 'low')) # Lowest low
high = max(poloniex.get_attribute(json, 'high')) # Highest high
return SO.eval_algorithm(close, low, high) | 676,630 |
Returns the average value
Args:
vals: List of numbers to calculate average from.
count: Int of total count that vals was part of.
Returns:
Float average value throughout a count. | def avg(vals, count=None):
sum = 0
for v in vals:
sum += v
if count is None:
count = len(vals)
return float(sum) / count | 676,633 |
Converts date arguments to a Delorean instance in UTC
Args:
year: int between 1 and 9999.
month: int between 1 and 12.
day: int between 1 and 31.
Returns:
Delorean instance in UTC of date. | def date_to_delorean(year, month, day):
return Delorean(datetime=dt(year, month, day), timezone='UTC') | 676,648 |
Converts a date to epoch in UTC
Args:
year: int between 1 and 9999.
month: int between 1 and 12.
day: int between 1 and 31.
Returns:
Int epoch in UTC from date. | def date_to_epoch(year, month, day):
return int(date_to_delorean(year, month, day).epoch) | 676,649 |
Load a raw data-file
Args:
file_name (path)
Returns:
loaded test | def load(self, file_name):
new_rundata = self.loader(file_name)
new_rundata = self.inspect(new_rundata)
return new_rundata | 676,817 |
Loads data from biologics .mpr files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s
(in cycle c) to skip loading.
Returns:
new_tests (list of data objects) | def loader(self, file_name, bad_steps=None, **kwargs):
new_tests = []
if not os.path.isfile(file_name):
self.logger.info("Missing file_\n %s" % file_name)
return None
filesize = os.path.getsize(file_name)
hfilesize = humanize_bytes(filesize)
tx... | 676,829 |
run dumber (once pr. engine)
Args:
dumper: dumper to run (function or method).
The dumper takes the attributes experiments, farms, and barn as input.
It does not return anything. But can, if the dumper designer feels in
a bad and nasty mood, modify the input objects
... | def run_dumper(self, dumper):
logging.debug("start dumper::")
dumper(
experiments=self.experiments,
farms=self.farms,
barn=self.barn,
engine=self.current_engine,
)
logging.debug("::dumper ended") | 676,865 |
Function for dumping values from a file.
Should only be used by developers.
Args:
file_name: name of the file
headers: list of headers to pick
default:
["Discharge_Capacity", "Charge_Capacity"]
Returns: pandas.DataFrame | def _iterdump(self, file_name, headers=None):
if headers is None:
headers = ["Discharge_Capacity", "Charge_Capacity"]
step_txt = self.headers_normal['step_index_txt']
point_txt = self.headers_normal['data_point_txt']
cycle_txt = self.headers_normal['cycle_index_txt'... | 676,908 |
Loads data from arbin .res files.
Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s (in cycle c) to skip loading.
Returns:
new_tests (list of data objects) | def loader(self, file_name, bad_steps=None, **kwargs):
# TODO: @jepe - insert kwargs - current chunk, only normal data, etc
new_tests = []
if not os.path.isfile(file_name):
self.logger.info("Missing file_\n %s" % file_name)
return None
self.logger.deb... | 676,909 |
Create a pandas DataFrame with the info needed for ``cellpy`` to load
the runs.
Args:
batch_name (str): Name of the batch.
batch_col (str): The column where the batch name is in the db.
reader (method): the db-loader method.
reader_label (str): the label for the db-loader (if db... | def make_df_from_batch(batch_name, batch_col="b01", reader=None, reader_label=None):
batch_name = batch_name
batch_col = batch_col
logger.debug(f"batch_name, batch_col: {batch_name}, {batch_col}")
if reader is None:
reader_obj = get_db_reader(reader_label)
reader = reader_obj()
... | 676,917 |
Writes the summaries to csv-files
Args:
frames: list of ``cellpy`` summary DataFrames
keys: list of indexes (typically run-names) for the different runs
selected_summaries: list defining which summary data to save
batch_dir: directory to save to
batch_name: the batch name (w... | def save_summaries(frames, keys, selected_summaries, batch_dir, batch_name):
if not frames:
logger.info("Could save summaries - no summaries to save!")
logger.info("You have no frames - aborting")
return None
if not keys:
logger.info("Could save summaries - no summaries to s... | 676,920 |
Exports dQ/dV data from a CellpyData instance.
Args:
cell_data: CellpyData instance
savedir: path to the folder where the files should be saved
sep: separator for the .csv-files.
last_cycle: only export up to this cycle (if not None) | def export_dqdv(cell_data, savedir, sep, last_cycle=None):
logger.debug("exporting dqdv")
filename = cell_data.dataset.loaded_from
no_merged_sets = ""
firstname, extension = os.path.splitext(filename)
firstname += no_merged_sets
if savedir:
firstname = os.path.join(savedir, os.path.... | 676,924 |
Plot summary graphs.
Args:
show: shows the figure if True.
save: saves the figure if True.
figure_type: optional, figure type to create. | def plot_summaries(self, show=False, save=True, figure_type=None):
if not figure_type:
figure_type = self.default_figure_type
if not figure_type in self.default_figure_types:
logger.debug("unknown figure type selected")
figure_type = self.default_figure_typ... | 676,943 |
Updates the selected datasets.
Args:
all_in_memory (bool): store the cellpydata in memory (default
False) | def update(self, all_in_memory=None):
logging.info("[update experiment]")
if all_in_memory is not None:
self.all_in_memory = all_in_memory
pages = self.journal.pages
summary_frames = dict()
cell_data_frames = dict()
number_of_runs = len(pages)
... | 676,945 |
Simply load an dataset based on serial number (srno).
This convenience function reads a dataset based on a serial number. This
serial number (srno) must then be defined in your database. It is mainly
used to check that things are set up correctly.
Args:
prm_filename: name of parameter file (op... | def just_load_srno(srno, prm_filename=None):
from cellpy import dbreader, filefinder
print("just_load_srno: srno: %i" % srno)
# ------------reading parameters--------------------------------------------
# print "just_load_srno: read prms"
# prm = prmreader.read(prm_filename)
#
# print ... | 676,991 |
Load a raw data file and save it as cellpy-file.
Args:
mass (float): active material mass [mg].
outdir (path): optional, path to directory for saving the hdf5-file.
outfile (str): optional, name of hdf5-file.
filename (str): name of the resfile.
Returns:
out_file_name (... | def load_and_save_resfile(filename, outfile=None, outdir=None, mass=1.00):
d = CellpyData()
if not outdir:
outdir = prms.Paths["cellpydatadir"]
if not outfile:
outfile = os.path.basename(filename).split(".")[0] + ".h5"
outfile = os.path.join(outdir, outfile)
print("filena... | 676,992 |
Load a raw data file and print information.
Args:
filename (str): name of the resfile.
info_dict (dict):
Returns:
info (str): string describing something. | def load_and_print_resfile(filename, info_dict=None):
# self.test_no = None
# self.mass = 1.0 # mass of (active) material (in mg)
# self.no_cycles = 0.0
# self.charge_steps = None # not in use at the moment
# self.discharge_steps = None # not in use at the moment
# self.ir_steps = None ... | 676,993 |
CellpyData object
Args:
filenames: list of files to load.
selected_scans:
profile: experimental feature.
filestatuschecker: property to compare cellpy and raw-files;
default read from prms-file.
fetch_one_liners: experimental feature.
... | def __init__(self, filenames=None,
selected_scans=None,
profile=False,
filestatuschecker=None, # "modified"
fetch_one_liners=False,
tester=None,
initialize=False,
):
if tester is Non... | 676,996 |
Set the instrument (i.e. tell cellpy the file-type you use).
Args:
instrument: (str) in ["arbin", "bio-logic-csv", "bio-logic-bin",...]
Sets the instrument used for obtaining the data (i.e. sets fileformat) | def set_instrument(self, instrument=None):
if instrument is None:
instrument = self.tester
if instrument in ["arbin", "arbin_res"]:
self._set_arbin()
self.tester = "arbin"
elif instrument == "arbin_sql":
self._set_arbin_sql()
... | 676,997 |
Set the directory containing .res-files.
Used for setting directory for looking for res-files.@
A valid directory name is required.
Args:
directory (str): path to res-directory
Example:
>>> d = CellpyData()
>>> directory = "MyData/Arbindata"
... | def set_raw_datadir(self, directory=None):
if directory is None:
self.logger.info("no directory name given")
return
if not os.path.isdir(directory):
self.logger.info(directory)
self.logger.info("directory does not exist")
return
... | 677,004 |
Set the directory containing .hdf5-files.
Used for setting directory for looking for hdf5-files.
A valid directory name is required.
Args:
directory (str): path to hdf5-directory
Example:
>>> d = CellpyData()
>>> directory = "MyData/HDF5"
... | def set_cellpy_datadir(self, directory=None):
if directory is None:
self.logger.info("no directory name given")
return
if not os.path.isdir(directory):
self.logger.info("directory does not exist")
return
self.cellpy_datadir = directory | 677,005 |
Load a raw data-file.
Args:
file_names (list of raw-file names): uses CellpyData.file_names if
None. If the list contains more than one file name, then the
runs will be merged together. | def from_raw(self, file_names=None, **kwargs):
# This function only loads one test at a time (but could contain several
# files). The function from_res() also implements loading several
# datasets (using list of lists as input).
if file_names:
self.file_names = file... | 677,011 |
Loads a cellpy file.
Args:
cellpy_file (path, str): Full path to the cellpy file.
parent_level (str, optional): Parent level | def load(self, cellpy_file, parent_level="CellpyData"):
try:
self.logger.debug("loading cellpy-file (hdf5):")
self.logger.debug(cellpy_file)
new_datasets = self._load_hdf5(cellpy_file, parent_level)
self.logger.debug("cellpy-file loaded")
except ... | 677,015 |
Load a cellpy-file.
Args:
filename (str): Name of the cellpy file.
parent_level (str) (optional): name of the parent level
(defaults to "CellpyData")
Returns:
loaded datasets (DataSet-object) | def _load_hdf5(self, filename, parent_level="CellpyData"):
if not os.path.isfile(filename):
self.logger.info(f"file does not exist: {filename}")
raise IOError
store = pd.HDFStore(filename)
# required_keys = ['dfdata', 'dfsummary', 'fidtable', 'info']
re... | 677,016 |
Returns voltage for cycle, step.
Convinience function; same as issuing
dfdata[(dfdata[cycle_index_header] == cycle) &
(dfdata[step_index_header] == step)][voltage_header]
Args:
cycle: cycle number
step: step number
set_number: the dataset... | def sget_voltage(self, cycle, step, set_number=None):
time_00 = time.time()
set_number = self._validate_dataset_number(set_number)
if set_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
... | 677,040 |
Returns voltage (in V).
Args:
cycle: cycle number (all cycles if None)
dataset_number: first dataset if None
full: valid only for cycle=None (i.e. all cycles), returns the full
pandas.Series if True, else a list of pandas.Series
Returns:
p... | def get_voltage(self, cycle=None, dataset_number=None, full=True):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
volt... | 677,041 |
Returns current (in mA).
Args:
cycle: cycle number (all cycles if None)
dataset_number: first dataset if None
full: valid only for cycle=None (i.e. all cycles), returns the full
pandas.Series if True, else a list of pandas.Series
Returns:
... | def get_current(self, cycle=None, dataset_number=None, full=True):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
curr... | 677,042 |
Returns step time for cycle, step.
Convinience function; same as issuing
dfdata[(dfdata[cycle_index_header] == cycle) &
(dfdata[step_index_header] == step)][step_time_header]
Args:
cycle: cycle number
step: step number
dataset_number: the... | def sget_steptime(self, cycle, step, dataset_number=None):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
step_time_he... | 677,043 |
Returns timestamp for cycle, step.
Convinience function; same as issuing
dfdata[(dfdata[cycle_index_header] == cycle) &
(dfdata[step_index_header] == step)][timestamp_header]
Args:
cycle: cycle number
step: step number
dataset_number: the... | def sget_timestamp(self, cycle, step, dataset_number=None):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.headers_normal.cycle_index_txt
timestamp_h... | 677,044 |
Returns timestamps (in sec or minutes (if in_minutes==True)).
Args:
cycle: cycle number (all if None)
dataset_number: first dataset if None
in_minutes: return values in minutes instead of seconds if True
full: valid only for cycle=None (i.e. all cycles), returns ... | def get_timestamp(self, cycle=None, dataset_number=None,
in_minutes=False, full=True):
dataset_number = self._validate_dataset_number(dataset_number)
if dataset_number is None:
self._report_empty_dataset()
return
cycle_index_header = self.h... | 677,045 |
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 | def _dqdv_combinded_frame(cell, **kwargs):
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 | 677,186 |
Performing fit of the OCV steps in the cycles set by set_cycles()
from the data set by set_data()
r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start).
c is found from using tau / r --> err(c) = err(r) + err(tau)
Args:
cellpydata (CellpyData): data obje... | def set_cellpydata(self, cellpydata, cycle):
self.data = cellpydata
self.step_table = self.data.dataset # hope it works...
time_voltage = self.data.get_ocv(direction='up',
cycles=cycle)
time = time_voltage.Step_Time
voltage = tim... | 677,227 |
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... | 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.0
else:
try:
d = datetime.datetime(1899, 12, 30) + \
datetime.timedelta(days=xldate + 1462 * datemo... | 677,276 |
Finds the file-stats and populates the class with stat values.
Args:
filename (str): name of the file. | def populate(self, filename):
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_access... | 677,279 |
Select row for identification number serial_number
Args:
serial_number: serial number
Returns:
pandas.DataFrame | def select_serial_number_row(self, serial_number):
sheet = self.table
col = self.db_sheet_cols.id
rows = sheet.loc[:, col] == serial_number
return sheet.loc[rows, :] | 677,295 |
Select rows for identification for a list of serial_number.
Args:
serial_numbers: list (or ndarray) of serial numbers
Returns:
pandas.DataFrame | def select_all(self, serial_numbers):
sheet = self.table
col = self.db_sheet_cols.id
rows = sheet.loc[:, col].isin(serial_numbers)
return sheet.loc[rows, :] | 677,296 |
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. | 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("missing serial number")
return
txt1 = 80 * "="
txt1 += "\n"
txt1 += f" serial number {serial_nu... | 677,297 |
Filters sheet/table by slurry name.
Input is slurry name or list of slurry names, for example 'es030' or
["es012","es033","es031"].
Args:
slurry (str or list of strings): slurry names.
appender (chr): char that surrounds slurry names.
Returns:
List ... | def filter_by_slurry(self, slurry, appender="_"):
sheet = self.table
identity = self.db_sheet_cols.id
exists = self.db_sheet_cols.exists
cellname = self.db_sheet_cols.cell_name
search_string = ""
if not isinstance(slurry, (list, tuple)):
slurry = [s... | 677,315 |
filters sheet/table by columns (input is column header)
The routine returns the serial numbers with values>1 in the selected
columns.
Args:
column_names (list): the column headers.
Returns:
pandas.DataFrame | def filter_by_col(self, column_names):
if not isinstance(column_names, (list, tuple)):
column_names = [column_names, ]
sheet = self.table
identity = self.db_sheet_cols.id
exists = self.db_sheet_cols.exists
criterion = True
for column_name in column... | 677,316 |
filters sheet/table by column.
The routine returns the serial-numbers with min_val <= values >= max_val
in the selected column.
Args:
column_name (str): column name.
min_val (int): minimum value of serial number.
max_val (int): maximum value of serial number... | def filter_by_col_value(self, column_name,
min_val=None, max_val=None):
sheet = self.table
identity = self.db_sheet_cols.id
exists_col_number = self.db_sheet_cols.exists
exists = sheet.loc[:, exists_col_number] > 0
if min_val is not None and... | 677,317 |
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 | def success(channel, image, hex_str):
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 | 677,325 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,331 |
Create a new UI for the module
Args:
parent: A tk or ttk object | def __init__(self, parent):
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
# Set default values
from ....datatools import get_data
data = get_data()
# API Frame
api_frame = ttk.Label... | 677,332 |
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 | def modify_module(channel, module_name, module_state):
# 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 | 677,334 |
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 | def modify_prefix(channel, new_prefix):
# Create embed UI object
gui = ui_embed.UI(
channel,
"Prefix updated",
"Modis prefix is now `{}`".format(new_prefix),
modulename=modulename
)
return gui | 677,335 |
Creates an embed UI containing an user warning message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
user (discord.User): The user to warn
warnings (str): The warnings for the user
max_warnings (str): The maximum warnings for the user
Returns:
... | def user_warning(channel, user, warnings, max_warnings):
username = user.name
if isinstance(user, discord.Member):
if user.nick is not None:
username = user.nick
warning_count_text = "warnings" if warnings != 1 else "warning"
warning_text = "{} {}".format(warnings, warning_cou... | 677,336 |
Creates an embed UI containing an user warning message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
user (discord.User): The user to ban
Returns:
ui (ui_embed.UI): The embed UI object | def user_ban(channel, user):
username = user.name
if isinstance(user, discord.Member):
if user.nick is not None:
username = user.nick
# Create embed UI object
gui = ui_embed.UI(
channel,
"Banned {}".format(username),
"{} has been banned from this server... | 677,337 |
Creates an embed UI containing an error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
max_warnings (int): The new maximum warnings
Returns:
ui (ui_embed.UI): The embed UI object | def warning_max_changed(channel, max_warnings):
# Create embed UI object
gui = ui_embed.UI(
channel,
"Maximum Warnings Changed",
"Users must now have {} warnings to be banned "
"(this won't ban existing users with warnings)".format(max_warnings),
modulename=modulena... | 677,338 |
Creates an embed UI containing an error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
description (str): The description for the error
Returns:
ui (ui_embed.UI): The embed UI object | def error(channel, title, description):
# Create embed UI object
gui = ui_embed.UI(
channel,
title,
description,
modulename=modulename
)
return gui | 677,339 |
Updates the server info for the given server
Args:
server: The Discord server to update info for | 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["discord"]["servers"]:
logger.debug("Adding new server to serverdata")
data["discord"]["servers"][server.i... | 677,340 |
Remove a server from the server data
Args:
server_id (int): The server to remove from the server 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"]["servers"]:
data["discord"]["servers"].pop(server_id)
datatools.write_data(data) | 677,341 |
Create a new main window frame.
Args:
parent: A tk or ttk object | def __init__(self, parent, discord_token, discord_client_id):
super(Frame, self).__init__(parent)
logger.debug("Initialising frame")
# Status bar
statusbar = StatusBar(self)
statusbar.grid(column=0, row=1, sticky="W E S")
# Create the main control panel
... | 677,343 |
Create a new module frame and add it to the given parent.
Args:
parent: A tk or ttk object | def __init__(self, parent):
super(ModuleFrame, self).__init__(parent)
logger.debug("Initialising module tabs")
# Setup styles
style = ttk.Style()
style.configure("Module.TFrame", background="white")
self.module_buttons = {}
self.current_button = None
... | 677,345 |
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 | def add_module(self, module_name, module_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
... | 677,347 |
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 | def module_selected(self, module_name, module_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.cu... | 677,348 |
Create a new base for a module UI
Args:
parent: A tk or ttk object
module_name (str): The name of the module
module_ui: The _ui.py file to add for the module | def __init__(self, parent, module_name, module_ui):
super(ModuleUIBaseFrame, self).__init__(parent, padding=8)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
if module_ui is not None:
# Module UI frame
module_ui.ModuleUIFrame(self).gri... | 677,349 |
Create a new control panel and add it to the parent.
Args:
parent: A tk or ttk object | def __init__(self, parent, discord_token, discord_client_id, module_frame, status_bar):
logger.debug("Initialising main control panel")
super(BotControl, self).__init__(
parent, padding=8, text="Modis control panel")
self.discord_thread = None
# Key name
s... | 677,350 |
Create a new text box for the console log.
Args:
parent: A tk or ttk object | def __init__(self, parent):
logger.debug("Initialising log panel")
super(Log, self).__init__(parent, padding=8, text="Python console log")
# Log text box
log = tk.Text(self, wrap="none")
log.grid(column=0, row=0, sticky="W E N S")
# Config tags
log.tag... | 677,356 |
Create a new status bar.
Args:
parent: A tk or ttk object | def __init__(self, parent):
logger.debug("Initialising status bar")
super(StatusBar, self).__init__(parent)
self.status = tk.StringVar()
# Status bar
self.statusbar = ttk.Label(self, textvariable=self.status, padding=2, anchor="center")
self.statusbar.grid(colu... | 677,357 |
Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online | def set_status(self, status):
text = ""
colour = "#FFFFFF"
if status == 0:
text = "OFFLINE"
colour = "#EF9A9A"
elif status == 1:
text = "STARTING"
colour = "#FFE082"
elif status == 2:
text = "ONLINE"
... | 677,358 |
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 | def get_help_data(filepath):
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 {} | 677,359 |
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 | def get_help_datapacks(filepath, prefix="!"):
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:
... | 677,360 |
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 | def add_help_text(parent, filepath, prefix="!"):
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", 1... | 677,361 |
The on_message event handler for this module
Args:
reaction (discord.Reaction): Input reaction
user (discord.User): The user that added the reaction | async def on_reaction_add(reaction, user):
# Simplify reaction info
server = reaction.message.server
emoji = reaction.emoji
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# Commands section
if user != reaction.... | 677,362 |
Start Modis in console format.
Args:
discord_token (str): The bot token for your Discord application
discord_client_id: The bot's client ID | def console(discord_token, discord_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_cons... | 677,363 |
Start Modis in gui format.
Args:
discord_token (str): The bot token for your Discord application
discord_client_id: The bot's client ID | 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 import gui as discord_modis_gui
from modis.reddit_modis import gui as reddit_modis_gui
from modis.facebook_modis import gui as fa... | 677,364 |
Write the data to the data.json file
Args:
data (dict): The updated data dictionary for Modis | def write_data(data):
sorted_dict = sort_recursive(data)
with open(_datafile, 'w') as file:
_json.dump(sorted_dict, file, indent=2) | 677,365 |
Recursively sorts all elements in a dictionary
Args:
data (dict): The dictionary to sort
Returns:
sorted_dict (OrderedDict): The sorted data dict | def sort_recursive(data):
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]))) | 677,366 |
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 ... | def success(channel, stats, name, platform, dp):
# 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_... | 677,369 |
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 | 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 profile on your profile page.",
modulename=modulename,
... | 677,370 |
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 | 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=0x0088FF
)
return gui | 677,371 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,372 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,374 |
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: | def success(channel, post):
# 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],
... | 677,376 |
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 | def no_results(channel):
gui = ui_embed.UI(
channel,
"No results",
":c",
modulename=modulename,
colour=0xFF8800
)
return gui | 677,377 |
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 | def make_timebar(progress=0, duration=0):
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:
... | 677,378 |
The on_message event handler for this module
Args:
message (discord.Message): Input message | async def on_message(message):
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.get_data()
if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
return
# On... | 677,379 |
Updates a particular datapack's data
Args:
index (int): The index of the datapack
data (str): The new value to set for this datapack | def update_data(self, index, data):
datapack = self.built_embed.to_dict()["fields"][index]
self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"]) | 677,383 |
Gets the Rocket League stats and name and dp of a UserID
Args:
player (str): The UserID of the player we want to rank check
platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox'
Returns:
success (bool): Whether the rank check was successful
package (tuple):... | def check_rank(player, platform="steam"):
# Get player ID and name Rocket League Tracker Network
webpage = requests.get(
"https://rocketleague.tracker.network/profile/{}/{}".format(platform, player)
).text
try:
# Get player ID
playerid_index = webpage.index("/live?ids=") +... | 677,388 |
Send a message to a channel
Args:
channel_id (str): The id of the channel to send the message to
message (str): The message to send to the channel | def send_message(channel_id, message):
channel = client.get_channel(channel_id)
if channel is None:
logger.info("{} is not a channel".format(channel_id))
return
# Check that it's enabled in the server
data = datatools.get_data()
if not data["discord"]["servers"][channel.serve... | 677,389 |
Runs an asynchronous function without needing to use await - useful for lambda
Args:
async_function (Coroutine): The asynchronous function to run | def runcoro(async_function):
future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)
result = future.result()
return result | 677,390 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.