### Initialize and Start Dancer Standalone Server Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/perl.html This snippet demonstrates the instantiation of the Dancer standalone handler and the execution of the server process. It relies on the Dancer::Handler and HTTP::Server::Simple::PSGI base classes. ```perl use Dancer::Handler::Standalone; # Initialize and run the server $dancer->run(); ``` -------------------------------- ### Compare Collections with C++ 'equal' Algorithm Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/c++.html This C++ code snippet demonstrates the use of the standard library 'equal' algorithm to compare two collections. It checks if the elements in the first range are element-wise equal to the elements in the second range. ```C++ #include "algostuff.hpp" using namespace std; int main() { vector coll1; list coll2; float m = 40.0f; INSERT_ELEMENTS(coll1, 1, 7); INSERT_ELEMENTS(coll2, 3, 9); PRINT_ELEMENTS(coll1, "coll1: \n"); PRINT_ELEMENTS(coll2, "coll2: \n"); // check whether both collections are equal if (equal (coll1.begin(), coll1.end(), // first range coll2.begin())) { // second range cout << "coll1 == coll2" << endl; } /* TODO Shouldn't there be an 'else' case? */ // check for corresponding even and odd elements if (equal (coll1.begin(), coll1.end(), // first range coll2.begin(), // second range ``` -------------------------------- ### PickerStore Color Picker State Management with JavaScript Source: https://context7.com/stayradiated/terminal.sexy/llms.txt Manages the color picker's state, including the active color and throttling updates. It shows how to open the picker, get and set state, and handle color changes. ```javascript // lib/stores/picker.js var PickerStore = require('./stores/picker'); var actions = require('./actions'); // Open color picker for a specific color actions.pickColor('background'); // Open for background actions.pickColor(5); // Open for ANSI color 5 // Get picker state var state = PickerStore.getState(); // Returns: { // activeId: 5, // Currently editing color ID // color: Colr // Current color value // } // Get picker settings var settings = PickerStore.getSettings(); // Returns: { throttle: 100 } // Update picker settings actions.setPicker({ throttle: 50 }); // Handle color change from react-colorpicker PickerStore.onChange(newColrInstance); // Throttled call to actions.setColor(activeId, color) ``` -------------------------------- ### Define Function for Word Definitions Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/bash.html A bash function that takes a word as input, searches for its definition on Google using lynx, processes the results to extract the definition, and saves it to a temporary file. It requires lynx to be installed. ```bash define () { lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}" | grep -m 25 -w "*" | sed 's/;/ - /g' | cut -d- -f5 > /tmp/templookup.txt if [[ -s /tmp/templookup.txt ]] ; then until ! read response do cat /tmp/templookup.txt done < /tmp/templookup.txt fi } ``` -------------------------------- ### Run Dancer Application with Dancer::Handler::Standalone Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/perl.html This snippet demonstrates the core functionality of starting a Dancer application using the Dancer::Handler::Standalone module. It typically involves calling the 'run' method to initiate the HTTP server. No specific external dependencies are highlighted beyond the Dancer framework itself. ```perl package Dancer::Handler::Standalone; use strict; use warnings; use HTTP::Server::Simple::PSGI; use base 'Dancer::Handler', 'HTTP::Server::Simple::PSGI'; use Dancer::HTTP; # ... other code ... $dancer->run(); # ... other code ... ``` -------------------------------- ### Check Element Parity with C++ Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/c++.html This C++ function checks if two integers have the same parity (both even or both odd). It is used to compare elements within collections. ```C++ #include "algostuff.hpp" using namespace std; bool bothEvenOrOdd (int elem1, int elem2) { return elem1 % 2 == elem2 % 2; } ``` -------------------------------- ### Dancer Standalone Server Execution (Perl) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/perl.html This snippet demonstrates the core functionality of starting a Dancer application using the standalone handler. It shows the invocation of the 'run' method and the setup for printing startup information. ```perl package Dancer::Handler::Standalone; use strict; use warnings; use HTTP::Server::Simple::PSGI; use base 'Dancer::Handler', 'HTTP::Server::Simple::PSGI'; use Dancer::HTTP; # ... other code ... $dancer->run(); # ... other code ... sub print_startup_info { my $pid = shift; my $ipaddr = setting('server'); my $port = setting('port'); # we only print the info if we need to setting('startup_info') or return; # bare minimum print STDERR ">> Dancer $Dancer::VERSION server $pid listening " . "on http://$ipaddr:$port\n"; # all loaded plugins foreach my $module ( grep { $_ =~ m{^Dancer/Plugin/} } keys %INC ) { $module =~ s{/}{::}g; # change / to :: } } ``` -------------------------------- ### Compare Collections for Equality using C++ std::equal Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/c++.html Checks if two collections have the same elements in the same order using the std::equal algorithm. It requires iterators to the beginning and end of the first range and an iterator to the beginning of the second range. The collections must be of compatible types. ```c++.cpp #include #include #include #include // Assuming INSERT_ELEMENTS and PRINT_ELEMENTS are defined elsewhere // For demonstration purposes, let's define them simply: void INSERT_ELEMENTS(auto& container, int start, int end) { for (int i = start; i <= end; ++i) { container.push_back(i); } } void PRINT_ELEMENTS(const auto& container, const std::string& prefix) { std::cout << prefix; for (const auto& elem : container) { std::cout << elem << " "; } std::cout << std::endl; } bool bothEvenOrOdd (int elem1, int elem2) { return elem1 % 2 == elem2 % 2; } int main() { std::vector coll1; std::list coll2; INSERT_ELEMENTS(coll1, 1, 7); INSERT_ELEMENTS(coll2, 3, 9); PRINT_ELEMENTS(coll1, "coll1: \n"); PRINT_ELEMENTS(coll2, "coll2: \n"); // check whether both collections are equal if (std::equal (coll1.begin(), coll1.end(), // first range coll2.begin())) { // second range std::cout << "coll1 == coll2" << std::endl; } // check for corresponding even and odd elements if (std::equal (coll1.begin(), coll1.end(), // first range coll2.begin(), // second range bothEvenOrOdd)) { // binary predicate std::cout << "coll1 and coll2 have corresponding even/odd elements" << std::endl; } return 0; } ``` -------------------------------- ### Run Dancer Application with Dancer::Handler::Standalone (Perl) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/perl.html This snippet demonstrates how to run a Dancer application using the Dancer::Handler::Standalone module. It integrates with HTTP::Server::Simple::PSGI to handle incoming HTTP requests. The primary function shown is `$dancer->run()`, which starts the server. ```perl package Dancer::Handler::Standalone; use strict; use warnings; use HTTP::Server::Simple::PSGI; use base 'Dancer::Handler', 'HTTP::Server::Simple::PSGI'; use Dancer::HTTP; # ... other code ... $dancer->run(); # ... other code ... ``` -------------------------------- ### jQuery CSS Property Access and Manipulation Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/javascript.html This snippet defines how jQuery's `.css()` method handles both getting and setting CSS properties for elements. It includes logic for no-operation settings and delegates to `jQuery.access` for property management. Dependencies include the jQuery library. ```javascript jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; ``` -------------------------------- ### Compare STL Collections using std::equal Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/c++.html This snippet demonstrates how to compare two different STL containers (vector and list) using the std::equal algorithm. It checks if the elements in the first range are equal to the corresponding elements in the second range starting from the provided iterator. ```cpp #include "algostuff.hpp" using namespace std; bool bothEvenOrOdd (int elem1, int elem2) { return elem1 % 2 == elem2 % 2; } int main() { vector coll1; list coll2; INSERT_ELEMENTS(coll1,1,7); INSERT_ELEMENTS(coll2,3,9); PRINT_ELEMENTS(coll1,"coll1: \n"); PRINT_ELEMENTS(coll2,"coll2: \n"); if (equal (coll1.begin(), coll1.end(), coll2.begin())) { cout << "coll1 == coll2" << endl; } } ``` -------------------------------- ### Create HTML Name Submission Form Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/html.html This HTML snippet defines a form that collects first and last names from the user. It uses the GET method to send data to 'html_form_action.php' and includes a nested unordered list for hierarchical data display. ```html
First name >
Last name: >
  • Coffee & Tea
  • Tea
    • Black tea
    • Green tea
      • China
      • Africa
``` -------------------------------- ### jQuery CSS Property Access and Manipulation Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/javascript.html This snippet defines how jQuery handles setting and getting CSS properties for elements. It utilizes jQuery.access for generalized property access and jQuery.style/jQuery.css for specific property operations. It includes checks for undefined values and handles various CSS property types. ```javascript var ralpha = /alpha\(\[^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /(\[A-Z\]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^(\[\-+\])=(\[\-+\de\]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; ``` -------------------------------- ### Initialize Redis Pub/Sub Clients Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/hybrid/coffeescript.html Parses configuration, creates authenticated Redis clients, and sets up separate instances for publishing and subscribing. It uses Promises to handle asynchronous connection states and ensures only one initialization occurs. ```CoffeeScript Promise = require('bluebird') redis = require('redis') url = require('url') log = require('log_')('redis', 'green') initiated = false cSub = null cPub = null parseConfig = (config) -> if typeof config.redis_config is 'string' {port, hostname, auth} = url.parse(config.redis_config) auth = auth.split(':')[1] else port = config.redis_config.port hostname = config.redis_config.host return {port, hostname, auth} createClient = (config) -> deferred = Promise.defer() client = redis.createClient(config.port, config.hostname, max_attempts: 3) if config.auth then client.auth(config.auth) client.on 'error', (err) -> log.warn(err) deferred.reject(null) client.on 'ready', -> deferred.resolve(client) return deferred.promise init = (config) -> return if initiated initiated = true config = parseConfig(config) Promise.all [ createClient(config) createClient(config) ] .spread (_pub, _sub) -> cPub = _pub cSub = _sub ``` -------------------------------- ### Repository Asset Loading and Caching with JavaScript Source: https://context7.com/stayradiated/terminal.sexy/llms.txt Demonstrates how to use a generic repository to fetch and cache assets. It shows initialization, retrieval from cache or server, and depositing user-created content to localStorage. ```javascript // lib/utils/repository.js var Repository = require('./utils/repository'); // Create a repository for color schemes var schemeRepo = new Repository({ id: 'scheme', // Storage key prefix folder: 'schemes', // Server folder path ext: '.json', // File extension dataType: 'json', // jQuery ajax dataType parseFn: importScheme // Transform function }); // Initialize with ranger store for file browsing schemeRepo.init(rangerStore, function() { console.log('Index loaded'); }); // Retrieve an asset (from cache or server) schemeRepo.retrieve('/base16/ocean', function(scheme) { console.log(scheme.colors); }); // Deposit user content to localStorage schemeRepo.deposit('/my-schemes/night', { name: 'night', author: 'user', foreground: '#ffffff', background: '#000000', color: [/* 16 hex colors */] }); // Access cached content directly var cached = schemeRepo.cache['/base16/ocean']; ``` -------------------------------- ### Python Decorator to Dump Function Arguments Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/python.html A Python decorator that prints the arguments passed to a function before executing it. It uses introspection to get argument names and values. This can be useful for debugging. ```python def dump_args(func): """This decorator dumps out the arguments passed to a function before calling it""" argnames = func.func_code.co_varnames[:func.func_code.co_argcount] fname = func.func_name def echo_func(*args, **kwargs): print fname, ":", ', '.join( '%s=%r' % entry for entry in zip(argnames,args) + kwargs.items()) return func(*args, **kwargs) return echo_func @dump_args def f1(a,b,c): print a + b + c f1(1, 2, 3) ``` -------------------------------- ### Create New Session Request (Go) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/hybrid/go.html Constructs a new HTTP request object for the session. It initializes the request URL, method, and session details. The request body includes method, header information (client, revision, privacy, country, UUID, session ID, and token), and parameters. ```go func NewRequest(session *Session, method string, parameters interface{}) (request *Request) { request = &Request{ Url: "http://grooveshark.com/more.php?" + method, Method: method, Session: session, } body := &Body{ Method: &(*request).Method, Parameters: parameters, Header: &Header{ Client: session.Client, ClientRevision: session.ClientRevision, Privacy: 0, Country: session.Country, UUID: session.UUID, SessionId: session.SessionId, }, } request.Body = body return request } ``` -------------------------------- ### Print Dancer Startup Information Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/perl.html This function, 'print_startup_info', within Dancer::Handler::Standalone is responsible for displaying essential server startup details. It outputs the process ID (PID), IP address, and port the server is listening on. Additionally, it iterates through loaded Dancer plugins and prints their names, formatted with '::' separators. This information is conditionally displayed based on the 'startup_info' setting. ```perl sub print_startup_info { my $pid = shift; my $ipaddr = setting('server'); my $port = setting('port'); # we only print the info if we need to setting('startup_info') or return; # bare minimum print STDERR ">> Dancer $Dancer::VERSION server $pid listening " . "on http://$ipaddr:$port\n"; # all loaded plugins foreach my $module ( grep { $_ =~ m{^Dancer/Plugin/} } keys %INC ) { $module =~ s{/}{::}g; # change / to :: } } ``` -------------------------------- ### Manage Application State with AppStore Source: https://context7.com/stayradiated/terminal.sexy/llms.txt Demonstrates how to retrieve the current color scheme state and integrate it into React components using Reflux's ListenerMixin to trigger re-renders on state changes. ```javascript var AppStore = require('./stores/app'); var state = AppStore.getState(); var Reflux = require('reflux'); var MyComponent = React.createClass({ mixins: [Reflux.ListenerMixin], componentDidMount: function() { this.listenTo(AppStore, this._onChange); }, _onChange: function() { var colors = AppStore.getState().colors; this.forceUpdate(); } }); ``` -------------------------------- ### Display Dancer Startup Information Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/perl.html This function prints server startup details to STDERR, including the PID, host, port, and loaded Dancer plugins. It checks the 'startup_info' setting before outputting to ensure configuration-based visibility. ```perl sub print_startup_info { my $pid = shift; my $ipaddr = setting('server'); my $port = setting('port'); setting('startup_info') or return; print STDERR ">> Dancer $Dancer::VERSION server $pid listening " . "on http://$ipaddr:$port\n"; foreach my $module ( grep { $_ =~ m{^Dancer/Plugin/} } keys %INC ) { $module =~ s{/}{::}g; } } ``` -------------------------------- ### Print Dancer Startup Information (Perl) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/perl.html This function, `print_startup_info`, is part of the Dancer::Handler::Standalone module. It prints essential startup details for a Dancer server, including the process ID (PID), IP address, and port. It also iterates through loaded Dancer plugins and prints their names, formatting them for display. ```perl sub print_startup_info { my $pid = shift; my $ipaddr = setting('server'); my $port = setting('port'); # we only print the info if we need to setting('startup_info') or return; # bare minimum print STDERR ">> Dancer $Dancer::VERSION server $pid listening " . "on http://$ipaddr:$port\n"; # all loaded plugins foreach my $module ( grep { $_ =~ m{^Dancer/Plugin/} } keys %INC ) { $module =~ s{/}{::}g; # change / to :: # ... further processing of module name ... } } ``` -------------------------------- ### Import Color Schemes from Text and XML Source: https://context7.com/stayradiated/terminal.sexy/llms.txt This snippet demonstrates importing color schemes from Xresources text format and iTerm2 XML format using the 'termcolors' library. It includes filling missing colors with defaults and applying the imported colors via actions. ```javascript // lib/components/import.react.jsx var termcolors = require('termcolors'); var actions = require('./actions'); // Import from text content var xresourcesText = "*background: #1d1f21 *foreground: #c5c8c6 *color0: #282a2e *color1: #a54242 ..."; var colors = termcolors.xresources.import(xresourcesText); colors = termcolors.defaults.fill(colors); // Fill missing colors actions.setAllColors('imported', colors); // Supported import formats: // - iterm: iTerm2 .itermcolors XML // - termite: Termite config format // - terminalapp: macOS Terminal.app .terminal // - xresources: X11 .Xresources format // Example iTerm import: var itermXml = '...'; var colors = termcolors.iterm.import(itermXml); actions.setAllColors('from-iterm', colors); ``` -------------------------------- ### jQuery CSS Property Access and Manipulation Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/javascript.html This JavaScript code extends jQuery's functionality to provide a method for accessing and setting CSS properties on elements. It utilizes `jQuery.access` to handle both getting and setting values, abstracting the underlying `jQuery.style` and `jQuery.css` functions. This allows for a unified interface for CSS operations. ```javascript jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; ``` -------------------------------- ### Handle terminal templates with TemplateStore Source: https://context7.com/stayradiated/terminal.sexy/llms.txt TemplateStore manages HTML representations of terminal output for previewing color schemes. It supports preloading templates and importing custom templates from file streams for ANSI parsing. ```javascript var TemplateStore = require('./stores/template'); var actions = require('./actions'); actions.openTemplate('/vim/decent/javascript'); TemplateStore.preload('/vim/vivify/python', function(html) { console.log(html); }); var fileStream = require('filereader-stream')(fileInput); actions.importTemplate('/my-templates/custom', fileStream); ``` -------------------------------- ### Send Session Request (Go) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/hybrid/go.html Sends the prepared session request over HTTP and unmarshals the JSON response. It marshals the request body into JSON, creates an HTTP POST request, reads the response body, and then attempts to unmarshal the response into the provided interface. Error handling is included for JSON marshaling, HTTP posting, reading the response, and JSON unmarshaling. ```go func (r *Request) Send(resp interface{}) error { data, err := json.Marshal(*r.Body) if err != nil { return err } body := bytes.NewReader(data) res, err := http.Post(r.Url, "application/json", body) if err != nil { return err } resBody, err := ioutil.ReadAll(res.Body) if err != nil { return err } err = json.Unmarshal(resBody, &resp) if err != nil { fmt.Printf("%+v\n", res) fmt.Println(string(resBody)) return err } return nil } ``` -------------------------------- ### Manage color schemes with SchemeStore Source: https://context7.com/stayradiated/terminal.sexy/llms.txt SchemeStore handles the lifecycle of color schemes including loading from repositories, caching, and persisting custom user schemes to localStorage. It works in conjunction with actions to trigger UI updates. ```javascript var SchemeStore = require('./stores/scheme'); var actions = require('./actions'); actions.openScheme('/base16/monokai'); var scheme = SchemeStore.get('/base16/monokai'); SchemeStore.load('/solarized/dark', function(scheme) { console.log(scheme.colors); }); actions.saveScheme('/my-schemes/custom', 'Your Name'); ``` -------------------------------- ### Persist application state with LocalStore Source: https://context7.com/stayradiated/terminal.sexy/llms.txt LocalStore provides a simplified interface for interacting with browser localStorage. It is used to save and retrieve application settings, user-defined schemes, and template indices. ```javascript var LocalStore = require('./utils/local'); LocalStore.save('app::settings', { font: { name: 'Fira Code', size: '16px', line: '24px', web: true } }); var settings = LocalStore.load('app::settings'); LocalStore.clear('app::settings'); ``` -------------------------------- ### Create Table SQL Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/sql.html Defines the structure for a new SQL table named 'My_table' with specified fields and a composite primary key. Ensures data integrity through field types and constraints. ```sql CREATE TABLE My_table( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1, my_field2) ); ``` -------------------------------- ### Exporting Color Schemes to Multiple Formats with JavaScript Source: https://context7.com/stayradiated/terminal.sexy/llms.txt Supports exporting color schemes to various terminal emulator formats using the 'termcolors' library. It lists supported formats and shows how to export to each. ```javascript // lib/components/export.react.jsx var termcolors = require('termcolors'); var AppStore = require('./stores/app'); // Get current colors var colors = AppStore.getState().colors; // Export to various formats: var xresources = termcolors.xresources.export(colors); var iterm = termcolors.iterm.export(colors); var gnome = termcolors.gnome.export(colors); var putty = termcolors.putty.export(colors); var konsole = termcolors.konsole.export(colors); var mintty = termcolors.mintty.export(colors); var termite = termcolors.termite.export(colors); var terminalapp = termcolors.terminalapp.export(colors); var alacritty = termcolors.alacritty.export(colors); var chromeshell = termcolors.chromeshell.export(colors); // Supported export formats: // - alacritty: Alacritty YAML config // - chromeshell: Chrome Secure Shell // - gnome: Gnome Terminal dconf // - guake: Guake Terminal // - iterm: iTerm2 .itermcolors XML // - konsole: KDE Konsole // - linux: Linux console escape codes // - mintty: MinTTY config // - putty: Windows registry (.reg) // - st: Simple Terminal (suckless) // - terminalapp: macOS Terminal.app // - terminator: Terminator config // - termite: Termite config // - xfce: XFCE4 Terminal // - xshell: Xshell .xcs // - xresources: X11 .Xresources // - json: JSON scheme format // - textmate: Sublime Text (experimental) ``` -------------------------------- ### Sign Session Request (Go) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/hybrid/go.html Generates a signature for a session request to ensure authenticity. It concatenates the request method, session token, session salt, and a random nonce. This string is then hashed using SHA1 and encoded into a hexadecimal string, which is appended to the request header as a token. ```go func (r *Request) Sign() { // get the session token token := r.Session.Token() // generate random nonce nonceBytes := make([]byte, 3) rand.Read(nonceBytes) nonce := hex.EncodeToString(nonceBytes) // concat values together input := strings.Join([]string{ r.Method, string(token), r.Session.Salt, nonce, }, ":") // hash with sha1 hash := sha1.New() hash.Write([]byte(input)) // convert to hex signature := hex.EncodeToString(hash.Sum(nil)) // add to header header := (*r.Body).Header (*header).Token = RequestSignature(nonce + signature) } ``` -------------------------------- ### Calculate Power and Evaluate Function in Ruby Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/ruby.html Implements a binary exponentiation algorithm for efficient power calculation and a custom function f(x) involving square roots and cubic powers. It reads 11 integers from standard input, processes them, and prints the result or 'TOO LARGE' if the output is infinite. ```ruby def power(x,n) result = 1 while n.nonzero? if n[0].nonzero? result *= x n -= 1 end x *= x n /= 2 end return result end def f(x) Math.sqrt(x.abs) + 5*x ** 3 end (0...11).collect{ gets.to_i }.reverse.each do |x| y = f(x) puts "#{x} #{y.infinite? ? 'TOO LARGE' : y}" end ``` -------------------------------- ### Bash Aliases and Prompt Configuration Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/bash.html This section defines several aliases for common commands to enhance productivity and sets up a customized bash prompt with hostname, time, and date information. It also exports the EDITOR variable to 'vim'. ```bash # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi # aliases alias grpe=grep alias grep='grep --color --line-number' alias vim="vim -p" alias rebash="source ~/.bashrc" alias install='sudo apt-get -y install' alias search='apt-cache search' alias purge='sudo apt-get purge' export EDITOR=vim # set up the prompt to the hostname shopt -s checkwinsize PS1="\e[1;35m[\w] --- \@ \d \n$ >\[\e[0m\]" PS2="\e[1;35m->\[\e[0m\]" ``` -------------------------------- ### Define Dictionary Lookup Function Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/bash.html This function uses lynx to fetch dictionary definitions from Google search results. It processes the output using grep and sed to format the text, saving the result to a temporary file for display. ```bash define () { lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}" | grep -m 25 -w "*" | sed 's/;/ -/g' | cut -d- -f5 > /tmp/templookup.txt if [[ -s /tmp/templookup.txt ]] ;then until ! read response done fi } ``` -------------------------------- ### Configure Gulp Build Tasks Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/gulpfile.js.html Defines tasks for asset compilation, module bundling, and development server management. It utilizes Gulp plugins to handle SCSS, React transformation, and automatic browser refreshing. ```javascript var gulp = require('gulp'); var brfs = require('brfs'); var source = require('vinyl-source-stream'); var connect = require('gulp-connect'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var reactify = require('reactify'); var browserify = require('browserify'); var watchify = require('watchify'); var uglify = require('gulp-uglify'); gulp.task('default', ['lib', 'style'], function () { gulp.watch('./stylesheets/**/*.scss', ['style']); return connect.server({ root: ['dist'], port: 8000, livereload: true }); }); gulp.task('lib', function () { var bundler = watchify(browserify({ cache: {}, packageCache: {}, fullPaths: true, extensions: '.jsx' })); bundler.add('./lib/init.js'); bundler.transform(reactify); bundler.transform(brfs); bundler.on('update', rebundle); function rebundle () { console.log('rebundling'); return bundler.bundle() .on('error', function (err) { console.log(err.message); }) .pipe(source('main.js')) .pipe(gulp.dest('./dist/js')) .pipe(connect.reload()); } return rebundle(); }); gulp.task('style', function () { return gulp.src('./stylesheets/main.scss') .pipe(sass({errLogToConsole: true, outputStyle: 'compressed'})) .pipe(autoprefixer()) .pipe(gulp.dest('./dist/css')) .pipe(connect.reload()); }); gulp.task('minify', function () { return gulp.src('./dist/js/*') .pipe(uglify()) .pipe(gulp.dest('./dist/js')); }); ``` -------------------------------- ### Sign Request with SHA1 in Go Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/gotham/go.html The Sign method generates a request signature using SHA1 hashing. It concatenates the request method, session token, session salt, and a random nonce, then hashes the result. The nonce and signature are appended to the request header's token field, ensuring request authenticity. ```go func (r *Request) Sign() { // get the session token token := r.Session.Token() // generate random nonce nonceBytes := make([]byte, 3) rand.Read(nonceBytes) nonce := hex.EncodeToString(nonceBytes) // concat values together input := strings.Join([]string{ r.Method, string(token), r.Session.Salt, nonce, }, ":") // hash with sha1 hash := sha1.New() hash.Write([]byte(input)) // convert to hex signature := hex.EncodeToString(hash.Sum(nil)) // add to header header := (*r.Body).Header (*header).Token = RequestSignature(nonce + signature) } ``` -------------------------------- ### Select Book Titles and Author Count SQL Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/sql.html Retrieves the titles of books and counts the number of authors associated with each book by joining the 'Book' and 'Book_author' tables. It groups the results by book title. ```sql SELECT Book.title, COUNT(*) AS Authors FROM Book JOIN Book_author ON Book.isbn = Book_author.isbn GROUP BY Book.title; ``` -------------------------------- ### Manage Database Schema and Permissions Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/sql.html Demonstrates the creation of a table with a composite primary key, altering an existing table to add a column, and managing user access rights. These commands are essential for defining database structure and enforcing security policies. ```sql CREATE TABLE My_table( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1, my_field2) ); ALTER TABLE My_table ADD my_field4 NUMBER(3) NOT NULL; GRANT SELECT, UPDATE ON My_table TO some_user, another_user; REVOKE SELECT, UPDATE ON My_table FROM some_user, another_user; ``` -------------------------------- ### Bash Aliases for Common Commands Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/bash.html Defines convenient shortcuts for frequently used commands like grep, vim, and apt package management. These aliases simplify command-line operations. ```bash alias grpe=grep alias grep='grep --color --line-number' alias vim="vim -p" alias rebash="source ~/.bashrc" alias install='sudo apt-get -y install' alias search='apt-cache search' alias purge='sudo apt-get purge' ``` -------------------------------- ### Send HTTP Request and Unmarshal Response in Go Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/gotham/go.html The Send method dispatches the constructed request over HTTP POST and handles the response. It marshals the request body to JSON, sends it to the specified URL, reads the response body, and unmarshals it into the provided interface. Error handling is included for network issues and JSON processing. ```go func (r *Request) Send(resp interface{}) error { data, err := json.Marshal(*r.Body) if err != nil { return err } body := bytes.NewReader(data) res, err := http.Post(r.Url, "application/json", body) if err != nil { return err } resBody, err := ioutil.ReadAll(res.Body) if err != nil { return err } err = json.Unmarshal(resBody, &resp) if err != nil { fmt.Printf("%+v\n", res) fmt.Println(string(resBody)) return err } return nil } ``` -------------------------------- ### Define Word Function using Google Search Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/bash.html This bash function 'define' takes a word as an argument, searches for its definition on Google, processes the results to extract relevant information, and saves it to a temporary file. It then checks if the temporary file has content before proceeding. ```bash #-------------------------------------------------- # grabs some definitions from google #-------------------------------------------------- define () { lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}" | grep -m 25 -w "*" | sed 's/;/ -/g' | cut -d- -f5 > /tmp/templookup.txt if [[ -s /tmp/templookup.txt ]] ; then until ! read response do ``` -------------------------------- ### Configure Bash Environment Aliases and Prompt Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/bash.html This snippet sets up common command-line aliases for improved productivity, such as colorized grep and shortcut package management commands. It also customizes the PS1 and PS2 shell prompts with color codes and timestamp information. ```bash if [ -f /etc/bashrc ]; then . /etc/bashrc; fi alias grpe=grep alias grep='grep --color --line-number' alias vim="vim -p" alias rebash="source ~/.bashrc" alias install='sudo apt-get -y install' alias search='apt-cache search' alias purge='sudo apt-get purge' export EDITOR=vim shopt -s checkwinsize PS1="\e[1;35m[\w] --- \@ \d \n$>\e[0m" PS2="\e[1;35m->\e[0m" ``` -------------------------------- ### Implement Window Resizing Handles Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/hybrid/scss.html Defines the interactive resize handles for the window manager, including south-east, south-west, east, and west resizing cursors. It uses SCSS mixins and variables to position handles precisely at the edges of the window container. ```SCSS .resize { $size: 10px; @include abs(auto, auto, 0, 0); &.se-resize, &.sw-resize { width: $size; height: $size; bottom: 0; } &.se-resize { right: 0; cursor: se-resize; } &.sw-resize { left: 0; cursor: sw-resize; } &.e-resize, &.w-resize { width: $size; top: $window_header_height; bottom: 0; cursor: ew-resize; } &.e-resize { right: 0; } } ``` -------------------------------- ### Map Color Names to Hex Codes in Ruby Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/ruby.html Defines a constant hash mapping common color names to their short-form hexadecimal string representations. ```ruby COLORS = { :black => "000", :red => "f00", :green => "0f0", :yellow => "ff0", :blue => "00f", :magenta => "f0f", :cyan => "0ff" } ``` -------------------------------- ### Create New Request in Go Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/gotham/go.html The NewRequest function constructs a new HTTP request object. It takes a session, method, and parameters, initializing the request URL, method, and body with session-specific details and default header information. This function is crucial for preparing outgoing API calls. ```go func NewRequest(session *Session, method string, parameters interface{}) (request *Request) { request = &Request{ Url: "http://grooveshark.com/more.php?" + method, Method: method, Session: session, } body := &Body{ Method: &(\*request).Method, Parameters: parameters, Header: &Header{ Client: session.Client, ClientRevision: session.ClientRevision, Privacy: 0, Country: session.Country, UUID: session.UUID, SessionId: session.SessionId, }, } request.Body = body return request } ``` -------------------------------- ### Create My_table with Primary Key Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/sql.html Defines the structure for 'My_table' with three fields: an integer 'my_field1', a VARCHAR 'my_field2', and a non-nullable DATE 'my_field3'. It establishes a composite primary key using 'my_field1' and 'my_field2'. ```sql CREATE TABLE My_table( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1, my_field2) ); ``` -------------------------------- ### Create and Alter SQL Table Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/sql.html Defines the structure of 'My_table' with initial fields and adds a new numeric field. It specifies data types, nullability, and primary keys. ```sql CREATE TABLE My_table( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1, my_field2) ); ALTER TABLE My_table ADD my_field4 NUMBER(3) NOT NULL; ``` -------------------------------- ### Compare STL Collections using std::equal Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/c++.html Demonstrates comparing two collections for equality or custom parity conditions using the C++ Standard Template Library. It utilizes helper macros INSERT_ELEMENTS and PRINT_ELEMENTS to manage and display collection data. ```cpp #include "algostuff.hpp" using namespace std; bool bothEvenOrOdd (int elem1, int elem2) { return elem1 % 2 == elem2 % 2; } int main() { vector coll1; list coll2; float m = 40.0f; INSERT_ELEMENTS(coll1,1,7); INSERT_ELEMENTS(coll2,3,9); PRINT_ELEMENTS(coll1,"coll1: \n"); PRINT_ELEMENTS(coll2,"coll2: \n"); if (equal (coll1.begin(), coll1.end(), coll2.begin())) { cout << "coll1 == coll2" << endl; } if (equal (coll1.begin(), coll1.end(), coll2.begin(), bothEvenOrOdd)) { // Custom parity check logic } } ``` -------------------------------- ### Configure Terminal Preview Font Settings Source: https://context7.com/stayradiated/terminal.sexy/llms.txt This JavaScript snippet shows how to configure the font settings for the terminal preview component using the 'actions' module. It allows setting the font family, size, line height, and whether to load from Google Web Fonts. ```javascript // lib/components/settings.react.jsx var actions = require('./actions'); // Update font settings actions.setFont({ name: 'Fira Code', // Font family name size: '16px', // Font size with unit line: '24px', // Line height with unit web: true // Load from Google Web Fonts }); // Settings are persisted to localStorage // and applied to the template preview CSS // Supported Google Web Fonts examples: // - 'Droid Sans Mono' // - 'Fira Code' // - 'Source Code Pro' // - 'Ubuntu Mono' // - 'Inconsolata' ``` -------------------------------- ### Precondition and Postcondition Utility Functions (Python) Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default/python.html Utility functions to define preconditions and postconditions for functions. These functions help in creating conditions that must be met before or after a function's execution. They utilize a `conditions` class to manage these states. ```python def precondition(precondition, use_conditions=DEFAULT_ON): return conditions(precondition, None, use_conditions) def postcondition(postcondition, use_conditions=DEFAULT_ON): return conditions(None, postcondition, use_conditions) class conditions(object): __slots__ = ('__precondition', '__postcondition') def __init__(self, pre, post, use_conditions=DEFAULT_ON): if not use_conditions: pre, post = None, None ``` -------------------------------- ### Bash Function to Define Words Using Google Search Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/shblah/bash.html This bash function, 'define', takes a word as an argument and uses lynx to search for its definition on Google. It then processes the search results to extract and display relevant definitions, saving temporary output to '/tmp/templookup.txt'. ```bash #-------------------------------------------------- # grabs some definitions from google #-------------------------------------------------- define () { lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}" | grep -m 25 -w "*" | sed 's/;/ -/g' | cut -d- -f5 > /tmp/templookup.txt if [[ -s /tmp/templookup.txt ]] ; then until ! read response do ~ fi } ``` -------------------------------- ### Read Integer Input from Terminal in Java Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/default-bright/java.html This Java code reads a line of text from the standard input (keyboard), tokenizes it, and attempts to parse the first token as an integer. It uses BufferedReader for efficient input reading and StringTokenizer for splitting the input into tokens. The loop continues until a valid integer is successfully parsed or an error occurs. ```java import java.io.*; import java.util.*; public class KeyboardIntegerReader { public static void main(String[] args) throws java.io.IOException { String s1; String s2; int num = 0; // set up the buffered reader to read from the keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean cont = true; while (cont) { System.out.print("Enter an integer:"); s1 = br.readLine(); StringTokenizer st = new StringTokenizer(s1); s2 = ""; while (cont && st.hasMoreTokens()) { try { s2 = st.nextToken(); num = Integer.parseInt(s2); cont = false; } catch (NumberFormatException e) { // Handle cases where the token is not a valid integer System.out.println("Invalid input. Please enter an integer."); cont = true; // Continue to prompt for input break; // Exit inner while loop to re-prompt } } if (cont && s1.isEmpty()) { // Handle empty input line System.out.println("No input provided. Please enter an integer."); cont = true; } } System.out.println("You entered: " + num); } } ``` -------------------------------- ### Calculate Power and Mathematical Transformation in Ruby Source: https://github.com/stayradiated/terminal.sexy/blob/master/dist/templates/vim/stayrad/ruby.html Provides a custom exponentiation function using binary exponentiation logic and a mathematical function combining square roots and cubic powers. These utilities are designed for numerical processing of input sequences. ```ruby def power(x,n) result = 1 while n.nonzero? if n[0].nonzero? result *= x n -= 1 end x *= x n /= 2 end return result end def f(x) Math.sqrt(x.abs) + 5*x ** 3 end ```