the-way 0.12.0

A code snippets manager for your terminal
Documentation
{"index":1,"description":"Append to an existing key in sled","language":"rust","code":"/// If key exists, add value to existing values - join with a semicolon\n/// use as db.set_merge_operator(merge_index)\nfn merge_index(_key: &[u8], old_indices: Option<&[u8]>, new_index: &[u8]) -> Option<Vec<u8>> {\n    let mut ret = old_indices.map_or_else(Vec::new, |old| old.to_vec());\n    if !ret.is_empty() {\n        ret.extend_from_slice(&[utils::SEMICOLON]);\n    }\n    ret.extend_from_slice(new_index);\n    Some(ret)\n}","extension":".rs","tags":["database","sled"],"date":"2020-05-14T07:38:53.725243Z","updated":"2020-07-12T17:39:28.830750Z"}{"index":10,"description":"Get brew SHA for new the-way version","language":"sh","code":"wget https://github.com/out-of-cheese-error/the-way/releases/download/v<version>/the-way-v<version>-x86_64-apple-darwin.tar.gz && shasum -a 256 the-way-v<version>-x86_64-apple-darwin.tar.gz && rm the-way-v<version>-x86_64-apple-darwin.tar.gz","extension":".sh","tags":["brew","the-way"],"date":"2020-10-08T00:00:00Z","updated":"2020-10-21T18:27:59.181881Z"}{"index":11,"description":"Linking to a remote jupyter notebook","language":"sh","code":"ssh -N -L localhost:<port=8913>:<host=eddy.bioinformatics.nl>:<port> <username=durai001>@<host2>","extension":".sh","tags":["one-line","shell"],"date":"2020-05-15T00:00:00Z","updated":"2020-10-21T18:28:48.884874Z"}{"index":12,"description":"Make new PyPi release","language":"sh","code":"python setup.py sdist bdist_wheel && python -m twine upload --repository pypi dist/* --skip-existing","extension":".sh","tags":["pip"],"date":"2020-10-16T10:21:44.108508Z","updated":"2020-10-16T10:21:44.108763Z"}{"index":13,"description":"Make docs for geometricus","language":"sh","code":"sphinx-apidoc -efo ./ ../geometricus && make github","extension":".sh","tags":["geometricus","pip"],"date":"2020-10-16T10:24:55.065417Z","updated":"2020-10-16T10:24:55.065696Z"}{"index":14,"description":"Fasta file parser","language":"python","code":"import typing\nfrom pathlib import Path\n\n\ndef get_sequences_from_fasta_yield(fasta_file: typing.Union[str, Path]) -> tuple:\n    \"\"\"\n    Returns (accession, sequence) iterator\n    Parameters\n    ----------\n    fasta_file\n    Returns\n    -------\n    (accession, sequence)\n    \"\"\"\n    with open(fasta_file) as f:\n        current_sequence = \"\"\n        current_key = None\n        for line in f:\n            if not len(line.strip()):\n                continue\n            if \"==\" in line:\n                continue\n            if \">\" in line:\n                if current_key is None:\n                    current_key = line.split(\">\")[1].strip()\n                else:\n                    yield current_key, current_sequence\n                    current_sequence = \"\"\n                    current_key = line.split(\">\")[1].strip()\n            else:\n                current_sequence += line.strip()\n        yield current_key, current_sequence\n\n\ndef get_sequences_from_fasta(fasta_file: typing.Union[str, Path]) -> dict:\n    \"\"\"\n    Returns dict of accession to sequence from fasta file\n    Parameters\n    ----------\n    fasta_file\n    Returns\n    -------\n    {accession:sequence}\n    \"\"\"\n    return {key: sequence for (key, sequence) in get_sequences_from_fasta_yield(fasta_file)}","extension":".py","tags":["bioinformatics"],"date":"2020-05-14T07:38:53.726459Z","updated":"2020-07-12T17:39:28.830949Z"}{"index":15,"description":"This snippet needs editing","language":"python","code":"print(\"Don't edit snippet\")","extension":".py","tags":["the-way"],"date":"2020-10-21T00:00:00Z","updated":"2020-10-22T10:04:10.479691Z"}{"index":17,"description":"Groups identifiers according to lineage","language":"python","code":"from ete3 import NCBITaxa\nNCBI = NCBITaxa()\n\n\ndef split_lineages(species_dict):\n    \"\"\"\n    Makes a dictionary of lineage groups to a set of identifiers belonging in that lineage\n    \"\"\"\n    def get_lineage_taxids_from_species(species: str) -> list:\n        try:\n            taxid = NCBI.get_name_translator([species])[species][0]\n            return NCBI.get_lineage(taxid)\n        except KeyError:\n            return []\n\n    lineages = defaultdict(set)\n    for i, identifier in enumerate(species_dict):\n        if i % 20 == 0:\n            print(i)\n        for group in (NCBI.get_taxid_translator(\n            get_lineage_taxids_from_species(\n                plant_species_dict[identifier]\n            )\n        ).values()):\n            lineages[group].add(identifier)\n    return lineages","extension":".py","tags":["bioinformatics"],"date":"2020-05-14T07:38:53.726501Z","updated":"2020-07-12T17:39:28.830965Z"}{"index":18,"description":"Scatter plot with grouped and labelled data","language":"python","code":"from matplotlib import cm\ncmap_colors = cm.tab20.colors\n\nplt.figure(figsize=(20, 10))\nlabels = [\"l1\", \"l2\", \"l3\"]\nmapping = dict(zip(labels, range(len(labels))))\ngroups = [mapping[x] for x in data_labels]\n\nfor i in range(len(labels)):\n    indices = np.where(np.array(groups) == i)[0]\n    plt.scatter(data[indices, 0], data[indices, 1], label=labels[i], color=cmap_colors[i])\nplt.legend()","extension":".py","tags":["plotting","matplotlib"],"date":"2020-05-14T07:38:53.726522Z","updated":"2020-07-12T17:39:28.830772Z"}{"index":19,"description":"Fetch a sequence from UniProt","language":"python","code":"import requests\ndef get_uniprot_sequence(uniprot_id: str) -> str:\n    mapping_url = f\"http://www.uniprot.org/uniprot/{uniprot_id}.fasta\"\n    response = requests.get(mapping_url).text\n    if \"html\" not in response.strip():\n        return ''.join(response.split('\\n')[1:])\n    else:\n        mapping_url = f\"http://www.uniprot.org/uniparc/{uniprot_id}.fasta\"\n        response = requests.get(mapping_url).text\n        if \"html\" not in response.strip():\n            return ''.join(response.split('\\n')[1:])\n        else:\n            return None","extension":".py","tags":["uniprot"],"date":"2020-06-18T10:20:21.461597Z","updated":"2020-07-12T17:39:28.830794Z"}{"index":20,"description":"Customize fuzzy search","language":"rust","code":"/// searchable snippet information\n#[derive(Debug)]\nstruct SearchSnippet {\n    index: usize,\n    /// Highlighted title\n    text_highlight: String,\n    /// Plain text title\n    text: String,\n    /// Highlighted code\n    code_highlight: String,\n    /// Plain code for copying\n    code: String,\n}\n\nimpl<'a> SkimItem for SearchSnippet {\n    fn display(&self) -> Cow<AnsiString> {\n        Cow::Owned(AnsiString::parse(&self.text_highlight))\n    }\n\n    fn text(&self) -> Cow<str> {\n        Cow::Owned(self.text.to_owned())\n    }\n\n    fn preview(&self) -> ItemPreview {\n        ItemPreview::AnsiText(self.code_highlight.to_owned())\n    }\n\n    fn output(&self) -> Cow<str> {\n        copy_to_clipboard(self.code.to_owned()).expect(\"Clipboard Error\");\n        let text = format!(\"Copied snippet #{} to clipboard\", self.index);\n        Cow::Owned(text)\n    }\n}\n/// Makes a fuzzy search window with the bottom panel listing each snippet's index, description,\n/// language and tags (all searchable) and the top panel showing the code for the selected snippet.\nfn search(input: Vec<SearchSnippet>) -> Result<(), Error> {\n    let options = SkimOptionsBuilder::default()\n        .height(Some(\"100%\"))\n        .preview(Some(\"\"))\n        .preview_window(Some(\"up:60%\"))\n        .multi(true)\n        .reverse(true)\n        .build()\n        .map_err(|_| LostTheWay::SearchError)?;\n\n    let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = unbounded();\n    for item in input {\n        let _ = tx_item.send(Arc::new(item));\n    }\n    drop(tx_item); // so that skim could know when to stop waiting for more items.\n\n    let selected_items =\n        Skim::run_with(&options, Some(rx_item)).map_or_else(Vec::new, |out| out.selected_items);\n    for item in &selected_items {\n        print!(\"{}{}\", item.output(), \"\\n\");\n    }\n    Ok(())\n}","extension":".rs","tags":["cli","skim"],"date":"2020-05-14T07:38:53.725323Z","updated":"2020-07-12T17:39:28.830826Z"}{"index":21,"description":"Terminal code highlight","language":"rust","code":"use syntect::easy::HighlightLines;\nuse syntect::highlighting::{Color, FontStyle, Style, StyleModifier, ThemeSet};\nuse syntect::parsing::SyntaxSet;\nuse syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};\nuse std::path::PathBuf;\n\nstruct CodeHighlight {\n    syntax_set: SyntaxSet,\n    theme_set: ThemeSet,\n    theme_name: String,\n    theme_dir: PathBuf\n}\nimpl CodeHighlight {\n    /// Loads themes from `theme_dir` and default syntax set.\n    /// Sets highlighting styles\n    fn new(theme: &str, theme_dir: PathBuf) -> Result<Self, Error> {\n        let mut theme_set = ThemeSet::load_defaults();\n        theme_set\n            .add_from_folder(&theme_dir)\n            .map_err(|_| LostTheWay::ThemeError {\n                theme: String::from((&theme_dir).to_str().unwrap()),\n            })?;\n        let mut highlighter = Self {\n            syntax_set: SyntaxSet::load_defaults_newlines(),\n            theme_name: theme.into(),\n            theme_set,\n            theme_dir,\n        };\n        Ok(highlighter)\n    }\n    \n    fn highlight_code(&self, code: &str, extension: &str) -> Result<Vec<String>, Error> {\n        let mut colorized = Vec::new();\n        let extension = extension.split('.').nth(1).unwrap_or(\".txt\");\n        let syntax = self.syntax_set.find_syntax_by_extension(extension).ok_or(\n            LostTheWay::LanguageNotFound {\n                language: extension.into(),\n            },\n        )?;\n        let mut h = HighlightLines::new(syntax, &self.theme_set.themes[&self.theme_name]);\n        for line in LinesWithEndings::from(code) {\n            let ranges: Vec<(Style, &str)> = h.highlight(line, &self.syntax_set);\n            let escaped = as_24_bit_terminal_escaped(&ranges[..], false);\n            colorized.push(escaped);\n        }\n        Ok(colorized)\n    }\n}","extension":".rs","tags":["cli","syntect"],"date":"2020-05-14T00:00:00Z","updated":"2020-07-12T17:39:28.830857Z"}{"index":28,"description":"Take user input from the terminal","language":"rust","code":"use dialoguer::{theme, Input};\n/// Takes user input from terminal, optionally has a default and optionally displays it.\npub fn user_input(\n    message: &str,\n    default: Option<&str>,\n    show_default: bool,\n) -> Result<String, Error> {\n    match default {\n        Some(default) => Ok(Input::with_theme(&theme::ColorfulTheme::default())\n            .with_prompt(message)\n            .default(default.to_owned())\n            .show_default(show_default)\n            .interact()?\n            .trim()\n            .to_owned()),\n        None => Ok(\n            Input::<String>::with_theme(&theme::ColorfulTheme::default())\n                .with_prompt(message)\n                .interact()?\n                .trim()\n                .to_owned(),\n        ),\n    }\n}","extension":".rs","tags":["cli","dialoguer"],"date":"2020-10-22T10:03:30.806022Z","updated":"2020-10-22T10:03:36.103216Z"}{"index":3,"description":"Take user input from external editor","language":"rust","code":"use dialoguer::Editor;\n/// Gets input from external editor, optionally displays default text in editor\npub fn external_editor_input(default: Option<&str>, extension: &str) -> Result<String, Error> {\n    match Editor::new()\n        .extension(extension)\n        .edit(default.unwrap_or(\"\"))?\n    {\n        Some(input) => Ok(input),\n        None => Err(LostTheWay::EditorError.into()),\n    }\n}","extension":".rs","tags":["cli","dialoguer"],"date":"2020-05-14T07:38:53.725421Z","updated":"2020-07-12T17:39:28.830890Z"}{"index":30,"description":"Add a new language syntax to the-way","language":"sh","code":"wget <url=https://raw.githubusercontent.com/getzola/zola/master/sublime/syntaxes/><lang>.sublime-syntax && the-way themes language <lang>.sublime-syntax && rm <lang>.sublime-syntax","extension":".sh","tags":["the-way"],"date":"2020-10-22T10:18:17.585812Z","updated":"2020-10-22T10:18:17.585820Z"}{"index":4,"description":"Parse dates from English date expressions","language":"rust","code":"use chrono::{Date, Utc};\nuse chrono_english::{parse_date_string, Dialect};\n/// Makes a date from a string, can be colloquial like \"next Friday\"\npub fn parse_date(date_string: &str) -> Result<Date<Utc>, Error> {\n    if date_string.to_ascii_lowercase() == \"today\" {\n        Ok(Utc::now().date())\n    } else {\n        Ok(parse_date_string(date_string, Utc::now(), Dialect::Uk)?.date())\n    }\n}","extension":".rs","tags":["date","chrono-english"],"date":"2020-05-14T07:38:53.725438Z","updated":"2020-07-12T17:39:28.830907Z"}{"index":6,"description":"Plot an ROC curve","language":"python","code":"from matplotlib import cm\ncmap_colors = cm.tab20.colors\n\nplt.figure(figsize=(20, 10))\nlabels = [\"l1\", \"l2\", \"l3\"]\nmapping = dict(zip(labels, range(len(labels))))\ngroups = [mapping[x] for x in data_labels]\n\nfor i in range(len(labels)):\n    indices = np.where(np.array(groups) == i)[0]\n    plt.scatter(data[indices, 0], data[indices, 1], label=labels[i], color=cmap_colors[i])\nplt.legend()","extension":".py","tags":["plotting","matplotlib"],"date":"2020-07-14T00:00:00Z","updated":"2020-07-14T21:03:21.662302Z"}{"index":7,"description":"Hello world","language":"kotlin","code":"fun main(args: Array<String>) {\n    println(\"Hello World!\")\n}","extension":".kt","tags":["test"],"date":"2020-07-15T08:32:50.780421Z","updated":"2020-07-15T08:33:07.372478Z"}{"index":8,"description":"Copy some text to clipboard","language":"rust","code":"use clipboard::{ClipboardContext, ClipboardProvider};\n/// Set clipboard contents to text\npub fn copy_to_clipboard(text: String) -> Result<(), Error> {\n    let mut ctx: ClipboardContext =\n        ClipboardProvider::new().map_err(|_| LostTheWay::ClipboardError)?;\n    ctx.set_contents(text)\n        .map_err(|_| LostTheWay::ClipboardError)?;\n    Ok(())\n}","extension":".rs","tags":["cli","clipboard"],"date":"2020-05-14T07:38:53.725452Z","updated":"2020-07-12T17:39:28.830917Z"}{"index":9,"description":"Bump git and cargo version","language":"sh","code":"git tag v<version> && git push origin v<version> && cargo publish","extension":".sh","tags":["rust","git"],"date":"2020-10-08T21:21:56.180767Z","updated":"2020-10-08T21:21:56.180776Z"}