Skip to content

Commit

Permalink
Apply suggestions from clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
atodorov committed Apr 5, 2024
1 parent f66aae4 commit 3d3811b
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 39 deletions.
5 changes: 2 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
// Set Config struct into a CONFIG lazy_static to avoid multiple processing.
//
use clap::{App, Arg, SubCommand};
use dotenv;
use lazy_static::lazy_static;
use log::{info, warn};
use serde::Deserialize;
Expand Down Expand Up @@ -482,12 +481,12 @@ fn get_config() -> Config {

// Try to load configuration from file first
let config_path = matches.value_of("config-path").unwrap_or(".env");
match dotenv::from_filename(&config_path).ok() {
match dotenv::from_filename(config_path).ok() {
Some(_) => info!("Loading configuration from {} file", &config_path),
None => {
let config_path =
env::var("CRUNCH_CONFIG_FILENAME").unwrap_or(".env".to_string());
if let Some(_) = dotenv::from_filename(&config_path).ok() {
if dotenv::from_filename(&config_path).is_ok() {
info!("Loading configuration from {} file", &config_path);
}
}
Expand Down
19 changes: 8 additions & 11 deletions src/crunch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub async fn create_or_await_substrate_node_client(
pub fn get_from_seed(seed: &str, pass: Option<&str>) -> sr25519::Pair {
// Use regex to remove control characters
let re = Regex::new(r"[\x00-\x1F]").unwrap();
let clean_seed = re.replace_all(&seed.trim(), "");
let clean_seed = re.replace_all(seed.trim(), "");
sr25519::Pair::from_string(&clean_seed, pass)
.expect("constructed from known-good static value; qed")
}
Expand Down Expand Up @@ -250,10 +250,8 @@ fn spawn_and_restart_crunch_flakes_on_error() {
let c: Crunch = Crunch::new().await;
if let Err(e) = c.try_run_batch().await {
let sleep_min = u32::pow(config.error_interval, n);
match e {
_ => {
error!("{}", e);
}
{
error!("{}", e);
}
thread::sleep(time::Duration::from_secs((60 * sleep_min).into()));
n += 1;
Expand All @@ -269,7 +267,7 @@ fn spawn_and_restart_crunch_flakes_on_error() {
}

fn healthcheck() -> async_std::task::JoinHandle<()> {
let h = task::spawn(async {
task::spawn(async {
let listener = TcpListener::bind("127.0.0.1:9999").unwrap();
let response = "HTTP/1.1 200 OK\r\n\r\n".as_bytes();

Expand All @@ -287,10 +285,9 @@ fn healthcheck() -> async_std::task::JoinHandle<()> {

stream.write_all(response).unwrap();
}
});

return h;
})
}

fn spawn_crunch_view() {
let crunch_task = task::spawn(async {
let c: Crunch = Crunch::new().await;
Expand All @@ -309,7 +306,7 @@ pub fn random_wait(max: u64) -> u64 {
pub async fn try_fetch_stashes_from_remote_url(
) -> Result<Option<Vec<String>>, CrunchError> {
let config = CONFIG.clone();
if config.stashes_url.len() == 0 {
if config.stashes_url.is_empty() {
return Ok(None);
}
let response = reqwest::get(&config.stashes_url).await?.text().await?;
Expand Down Expand Up @@ -339,7 +336,7 @@ pub async fn try_fetch_onet_data(
return Ok(None);
}

let endpoint = if config.onet_api_url != "" {
let endpoint = if !config.onet_api_url.is_empty() {
config.onet_api_url
} else {
format!("https://{}-onet-api-beta.turboflakes.io", chain_name)
Expand Down
2 changes: 0 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use codec;
use reqwest;
use std::{str::Utf8Error, string::String};
use subxt::error::{DispatchError, MetadataError};
use thiserror::Error;
Expand Down
2 changes: 1 addition & 1 deletion src/pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub fn nomination_pool_account(account_type: AccountType, pool_id: u32) -> Accou
let buffer_hex = buffer.encode_hex::<String>();
// NOTE: subxt::utils::AccountId32 currently doesn't support from hex conversion
let acc = subxt::ext::sp_runtime::AccountId32::from_str(&buffer_hex).unwrap();
return AccountId32::from_str(&acc.to_string()).unwrap();
AccountId32::from_str(&acc.to_string()).unwrap()
}

#[test]
Expand Down
30 changes: 15 additions & 15 deletions src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl From<RawData> for Report {
* 100.0,
)
} else {
format!("")
String::new()
};

let summary_already_desc = if data
Expand All @@ -204,7 +204,7 @@ impl From<RawData> for Report {
.total_validators_previous_era_already_claimed,
)
} else {
format!("")
String::new()
};

let summary_next_desc = if data.payout_summary.next_minimum_expected > 0 {
Expand Down Expand Up @@ -260,12 +260,12 @@ impl From<RawData> for Report {
report.add_raw_text(format!(
"{} <b><a href=\"https://{}.subscan.io/validator/{}\">{}</a></b>",
is_active_desc,
data.network.name.to_lowercase().trim().replace(" ", ""),
data.network.name.to_lowercase().trim().replace(' ', ""),
validator.stash,
validator.name,
));
// Show validator warnings
if validator.warnings.len() > 0 {
if !validator.warnings.is_empty() {
for warning in validator.warnings {
report.add_raw_text(format!("⚠️ {} ⚠️", warning.clone()));
warn!("{}", warning);
Expand All @@ -279,7 +279,7 @@ impl From<RawData> for Report {
));

// Check if there are no payouts
if validator.payouts.len() == 0 {
if validator.payouts.is_empty() {
if validator.is_active {
report.add_text(format!(
"🥣 Looking forward for next <code>crunch</code> {} {}",
Expand All @@ -303,7 +303,7 @@ impl From<RawData> for Report {
/ 10f64.powi(data.network.token_decimals.into()),
data.network.token_symbol,
good_performance(
payout.points.validator.into(),
payout.points.validator,
payout.points.ci99_9_interval.1,
payout.points.outlier_limits.1
)
Expand Down Expand Up @@ -356,14 +356,14 @@ impl From<RawData> for Report {
(<a href=\"https://{}.subscan.io/extrinsic/{:?}\">{}</a>) ✨",
payout.era_index,
payout.block_number,
data.network.name.to_lowercase().trim().replace(" ", ""),
data.network.name.to_lowercase().trim().replace(' ', ""),
payout.extrinsic,
payout.extrinsic.to_string()
payout.extrinsic
));
}

// Check if there are still eras left to claim
if validator.unclaimed.len() > 0 {
if !validator.unclaimed.is_empty() {
let symbols = number_to_symbols(validator.unclaimed.len(), "⚡", 84);
report.add_text(format!(
"{} There are still {} eras left with {} to <code>crunch</code> {}",
Expand Down Expand Up @@ -395,7 +395,7 @@ impl From<RawData> for Report {
));

// Claimed
if validator.claimed.len() > 0 {
if !validator.claimed.is_empty() {
let claimed_percentage = (validator.claimed.len() as f32
/ (validator.claimed.len() + validator.unclaimed.len()) as f32)
* 100.0;
Expand Down Expand Up @@ -437,9 +437,9 @@ impl From<RawData> for Report {
"💯 Batch finalized at block #{}
(<a href=\"https://{}.subscan.io/extrinsic/{:?}\">{}</a>) ✨",
batch.block_number,
data.network.name.to_lowercase().trim().replace(" ", ""),
data.network.name.to_lowercase().trim().replace(' ', ""),
batch.extrinsic,
batch.extrinsic.to_string()
batch.extrinsic
));
}
} else {
Expand Down Expand Up @@ -476,9 +476,9 @@ impl From<RawData> for Report {

fn number_to_symbols(n: usize, symbol: &str, max: usize) -> String {
let cap: usize = match n {
n if n < (max / 4) as usize => 1,
n if n < (max / 2) as usize => 2,
n if n < max - (max / 4) as usize => 3,
n if n < (max / 4) => 1,
n if n < (max / 2) => 2,
n if n < max - (max / 4) => 3,
_ => 4,
};
let v = vec![""; cap + 1];
Expand Down
16 changes: 9 additions & 7 deletions src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#[allow(clippy::ptr_arg)]
pub fn mean(list: &Vec<f64>) -> f64 {
if list.len() == 0 {
if list.is_empty() {
return 0.0;
}
let sum: f64 = list.iter().sum();
Expand All @@ -29,13 +30,13 @@ pub fn mean(list: &Vec<f64>) -> f64 {

pub fn standard_deviation(list: &Vec<f64>) -> f64 {
let m = mean(list);
let mut variance: Vec<f64> =
list.iter().map(|&score| (score - m).powf(2.0)).collect();
mean(&mut variance).sqrt()
let variance: Vec<f64> = list.iter().map(|&score| (score - m).powf(2.0)).collect();
mean(&variance).sqrt()
}

#[allow(clippy::ptr_arg)]
pub fn median(list: &mut Vec<u32>) -> u32 {
if list.len() == 0 {
if list.is_empty() {
return 0;
}
list.sort();
Expand Down Expand Up @@ -67,13 +68,14 @@ pub fn confidence_interval(list: &Vec<f64>, z: f64) -> (f64, f64) {
}
// Find outliers by Interquartile Range(IQR)
// https://www.statisticshowto.com/statistics-basics/find-outliers/
#[allow(clippy::ptr_arg)]
pub fn iqr_interval(list: &mut Vec<u32>) -> (f64, f64) {
if list.len() == 0 {
if list.is_empty() {
return (0.0, 0.0);
}
list.sort();
let q1 = median(&mut (&list[..&list.len() / 2]).into());
let q3 = median(&mut (&list[&list.len() - (&list.len() / 2)..]).into());
let q3 = median(&mut (&list[list.len() - (&list.len() / 2)..]).into());
let iqr = q3 - q1;
(
(q1 as f64) - (iqr as f64 * 1.5),
Expand Down

0 comments on commit 3d3811b

Please sign in to comment.