### Setup and Run TestChat Server (Python)
Source: https://github.com/felixhageloh/uebersicht/blob/master/Pods/SocketRocket/README.rst
Instructions to set up the Python virtual environment and run the TestChat server. This involves activating a virtual environment, installing the Tornado library, and then starting the chatroom server script.
```bash
source .env/bin/activate
pip install git+https://github.com/tornadoweb/tornado.git
python TestChatServer/py/chatroom.py
```
--------------------------------
### Perform Network Requests with isomorphic-fetch
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/isomorphic-fetch/README.md
Example demonstrating how to initialize the polyfill and perform a GET request to an API endpoint, handling the response and parsing JSON data.
```javascript
require('es6-promise').polyfill();
require('isomorphic-fetch');
fetch('//offline-news-api.herokuapp.com/stories')
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(stories) {
console.log(stories);
});
```
--------------------------------
### Install React and React DOM
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/react-dom/README.md
Command to install the required React dependencies via npm. This is the standard setup for projects using React.
```bash
npm install react react-dom
```
--------------------------------
### Install Promise Library
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/promise/Readme.md
Instructions for installing the promise library on the server using npm. For client-side usage, browserify or a pre-compiled script can be used.
```bash
$ npm install promise
```
--------------------------------
### Install isomorphic-fetch via Package Managers
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/isomorphic-fetch/README.md
Instructions for installing the library and the required ES6 Promise polyfill using NPM or Bower.
```bash
npm install --save isomorphic-fetch es6-promise
```
```bash
bower install --save isomorphic-fetch es6-promise
```
--------------------------------
### Configure Build Environment
Source: https://github.com/felixhageloh/uebersicht/blob/master/ClassicWidgets.md
Setup commands for building the project and configuring Git to handle Unicode characters correctly.
```bash
brew install node
npm install
git config core.precomposeunicode false
```
--------------------------------
### Widget Lifecycle: init
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
The init function handles one-time setup tasks such as WebSocket connections or event listener registration when a widget loads.
```APIDOC
## init(dispatch)
### Description
Initializes the widget environment. This function is called once upon widget load.
### Parameters
- **dispatch** (function) - Required - The dispatcher function used to send actions to the widget state reducer.
### Example
```javascript
export const init = (dispatch) => {
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('message', (event) => {
dispatch({ type: 'MESSAGE_RECEIVED', data: JSON.parse(event.data) });
});
};
```
```
--------------------------------
### Install React 15.3.0+ and prop-types (Shell)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/prop-types/README.md
This shell command installs React and ReactDOM versions compatible with React 15.3.0 and higher, along with the prop-types package. This is the recommended installation for newer React versions.
```shell
npm install --save react@^15.3.0 react-dom@^15.3.0
```
--------------------------------
### Promise.all Example
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/promise/Readme.md
Example demonstrating Promise.all, which returns a promise for an array. It resolves with a copy of the input array, replacing any promises with their fulfilled values.
```javascript
Promise.all([Promise.resolve('a'), 'b', Promise.resolve('c')])
.then(function (res) {
assert(res[0] === 'a')
assert(res[1] === 'b')
assert(res[2] === 'c')
})
```
--------------------------------
### Install is-stream
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/is-stream/readme.md
Installation instructions for the is-stream package using the npm package manager.
```bash
$ npm install --save is-stream
```
--------------------------------
### Install prop-types using npm
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/prop-types/README.md
This command installs the prop-types package as a dependency for your project.
```shell
npm install --save prop-types
```
--------------------------------
### Implement a Full-Featured System Monitor Widget
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
A comprehensive example of a widget that executes shell commands, manages state, and uses styled components for UI rendering. It displays the top CPU-consuming processes on the desktop.
```jsx
import { css, styled } from "uebersicht";
export const command = "ps axo \"pcpu,comm\" | sort -nr | head -n5 | tail -n4";
export const refreshFrequency = 2000;
export const initialState = {
processes: [],
error: null
};
export const updateState = (event, previousState) => {
if (event.error) {
return { ...previousState, error: event.error };
}
const processes = event.output
.trim()
.split('\n')
.map(line => {
const match = line.trim().match(/^([\d.]+)\s+(.+)$/);
if (match) {
return { cpu: parseFloat(match[1]), name: match[2] };
}
return null;
})
.filter(Boolean);
return { processes, error: null };
};
const Container = styled("div")`
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 12px;
color: #fff;
`;
const Title = styled("h1")`
font-size: 14px;
margin: 0 0 10px 0;
opacity: 0.8;
`;
const ProcessRow = styled("div")`
display: flex;
justify-content: space-between;
padding: 4px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;
const CpuBar = styled("div")(props => ({
width: "60px",
height: "4px",
backgroundColor: "rgba(255, 255, 255, 0.2)",
borderRadius: "2px",
overflow: "hidden",
"&::after": {
content: '""',
display: "block",
width: `${Math.min(props.percent, 100)}%`,
height: "100%",
backgroundColor: props.percent > 50 ? "#ff6b6b" : "#51cf66"
}
}));
export const className = `
top: 20px;
left: 20px;
width: 220px;
padding: 15px;
background: rgba(0, 0, 0, 0.6);
border-radius: 10px;
backdrop-filter: blur(10px);
`;
export const render = ({ processes, error }) => {
if (error) {
return Error: {String(error)};
}
return (
Top CPU Processes
{processes.map((proc, idx) => (
{proc.name.slice(0, 20)}{proc.cpu.toFixed(1)}%
))}
);
};
```
--------------------------------
### Initialize Widget with WebSocket Connection (JavaScript)
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
The init function is used for one-time setup tasks when a widget loads, such as establishing WebSocket connections for real-time updates. It dispatches actions based on connection status, messages, and errors.
```jsx
export const init = (dispatch) => {
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
dispatch({ type: 'SOCKET_CONNECTED' });
});
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
dispatch({ type: 'MESSAGE_RECEIVED', data: data });
});
socket.addEventListener('error', (error) => {
dispatch({ type: 'SOCKET_ERROR', error: error.message });
});
};
```
--------------------------------
### Porting Buffer Calls to Modern API
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Readme.md
This example shows the recommended way to port existing Buffer API calls to their modern equivalents. It replaces older 'Buffer()' and 'new Buffer()' calls with 'Buffer.alloc()' and 'Buffer.from()', which are safer and more explicit. This is a necessary step before using the safer-buffer polyfill.
```javascript
// Old way:
// const buf = new Buffer(10)
// const buf = Buffer(10)
// New way:
const buf = Buffer.alloc(10)
const buf2 = Buffer.from('hello')
```
--------------------------------
### Building Übersicht
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Provides instructions for building the Übersicht application, including setting up the required Node.js version, installing dependencies, and configuring Git for Unicode characters.
```APIDOC
## Building Übersicht
To build Übersicht you will need to have NodeJS and a few dependencies installed:
### Setup
Currently, the project supports node 8.
If you already have node, you'll have to
```bash
brew unlink node
```
Now, install node 8 using homebrew
```bash
brew install node@8 && brew link --force node@8
```
then run
```bash
npm install
```
### Git and Unicode Characters
Git might not like the umlaut (ü) in some of the path names and will constantly show them as untracked files. To get rid of this issue, I had to use
```bash
git config core.precomposeunicode false
```
However, the common advice is to set this to `true`. It might depend on the OS and git version which one to use.
### Building
The code base consists of two parts, a cocoa app and a NodeJS app inside `server/`. To build the node app separately, use `npm run release`. This happens automatically every time you build using XCode.
The node app can be run standalone using
```coffeescript
coffee server/server.coffee -d -p
```
```
--------------------------------
### GET Request (HTML/JSON)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/whatwg-fetch/README.md
Demonstrates how to perform a GET request to retrieve HTML or JSON content using the fetch API.
```APIDOC
## GET /resource
### Description
Fetches a resource from the server and parses the response body as text or JSON.
### Method
GET
### Endpoint
/resource
### Request Example
fetch('/users.json')
### Response
#### Success Response (200)
- **response** (Object) - The response object containing methods like .json() or .text().
#### Response Example
{
"id": 1,
"name": "Hubot"
}
```
--------------------------------
### Install React 0.14.9 and prop-types (Shell)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/prop-types/README.md
This shell command installs specific versions of React and ReactDOM compatible with React 0.14.9, along with the prop-types package. It's intended for users still on React 0.14.
```shell
# ATTENTION: Only run this if you still use React 0.14!
npm install --save react@^0.14.9 react-dom@^0.14.9
```
--------------------------------
### Initialize Widget with WebSocket Listener (JavaScript)
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Provides an initialization function that is called when the widget first loads. This example demonstrates setting up a WebSocket connection to listen for messages and dispatching actions to update the state. It's useful for real-time updates without relying on periodic commands.
```jsx
export const init = (dispatch) => {
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('message', (event) => {
dispatch({type: 'MESSAGE_RECEIVED', data: event.data});
});
}
```
--------------------------------
### Control Widgets via AppleScript
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
Provides examples for automating Übersicht widgets using AppleScript. Commands include refreshing, listing, and toggling the visibility of specific widgets.
```applescript
-- Refresh all widgets
tell application id "tracesOf.Uebersicht" to refresh
-- Refresh a specific widget by ID
tell application id "tracesOf.Uebersicht" to refresh widget id "cpu-monitor"
-- List all widgets
tell application id "tracesOf.Uebersicht" to every widget
-- Hide a widget
tell application id "tracesOf.Uebersicht" to set hidden of widget id "weather-widget" to true
-- Show a widget
tell application id "tracesOf.Uebersicht" to set hidden of widget id "weather-widget" to false
```
--------------------------------
### Install object-assign using npm
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/object-assign/readme.md
This command installs the object-assign package as a dependency for your project using npm. It is typically used in the project's root directory.
```bash
$ npm install --save object-assign
```
--------------------------------
### Install Encoding Module via npm
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/encoding/README.md
This snippet shows how to install the encoding module using npm. It's a prerequisite for using the module in your Node.js project.
```bash
npm install encoding
```
--------------------------------
### Fetch HTML Content
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/whatwg-fetch/README.md
Demonstrates how to perform a GET request to retrieve HTML content and inject it into the document body.
```javascript
fetch('/users.html').then(function(response) { return response.text() }).then(function(body) { document.body.innerHTML = body })
```
--------------------------------
### Demonstrating Regex and Division Collision
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/js-tokens/README.md
Examples showing how identical syntax can be interpreted as either division or a regex literal depending on context, which poses challenges for simple tokenizers.
```javascript
var g = 9.82;
var number = bar / 2/g;
var regex = / 2/g;
```
```javascript
foo /= 2/g;
foo(/= 2/g);
```
--------------------------------
### Run SocketRocket Tests (Makefile)
Source: https://github.com/felixhageloh/uebersicht/blob/master/Pods/SocketRocket/README.rst
Commands to execute the testing suite for the SocketRocket project. It includes options for running short tests or all tests, which may involve dependency installation. The makefile also handles opening test results in a browser.
```makefile
make test
make test_all
```
--------------------------------
### Usage of object-assign for property assignment
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/object-assign/readme.md
Demonstrates how to use the object-assign package to merge properties from source objects into a target object. It shows examples of assigning properties from single and multiple sources, handling key overwrites, and ignoring null/undefined sources.
```javascript
const objectAssign = require('object-assign');
objectAssign({foo: 0}, {bar: 1});
//=> {foo: 0, bar: 1}
// multiple sources
objectAssign({foo: 0}, {bar: 1}, {baz: 2});
//=> {foo: 0, bar: 1, baz: 2}
// overwrites equal keys
objectAssign({foo: 0}, {foo: 1}, {foo: 2});
//=> {foo: 2}
// ignores null and undefined sources
objectAssign({foo: 0}, null, {bar: 1}, undefined);
//=> {foo: 0, bar: 1}
```
--------------------------------
### Extending Regex Patterns with UAParser
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/ua-parser-js/readme.md
This example shows how to extend the default regex patterns of UAParser.js to include custom browser or device matching rules. It demonstrates creating a new UAParser instance with custom regexes for a hypothetical browser.
```javascript
var myOwnRegex = [[/(myownbrowser)\/([\w\.]+)/i], [UAParser.BROWSER.NAME, UAParser.BROWSER.VERSION]];
var myParser = new UAParser({ browser: myOwnRegex });
var uaString = 'Mozilla/5.0 MyOwnBrowser/1.3';
console.log(myParser.setUA(uaString).getBrowser());
```
--------------------------------
### Build FBJS Project
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/fbjs/README.md
Commands to build the FBJS project. It can be built using Gulp or an npm script. Ensure Gulp is installed globally if using the direct Gulp command.
```shell
gulp
```
```shell
npm run build
```
--------------------------------
### Convert Text Encoding using encoding.convert()
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/encoding/README.md
This example shows the core functionality of the encoding module: converting text from one character set to another. The function accepts a string or Buffer, the target charset, and an optional source charset. The output is always a Buffer.
```javascript
var resultBuffer = encoding.convert(text, toCharset, fromCharset);
```
```javascript
var result = encoding.convert("ÕÄÖÜ", "Latin_1");
console.log(result); //
```
--------------------------------
### Node.js: Safe String to Base64 Encoding with Buffer.from
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Porting-Buffer.md
This example demonstrates a secure way to convert a string to Base64 using Buffer.from. Unlike the deprecated Buffer constructor, Buffer.from handles different input types more predictably, throwing errors for unexpected inputs like numbers, thus preventing potential security exploits.
```javascript
function stringToBase64(req, res) {
// The request body should have the format of `{ string: 'foobar' }`
// Using Buffer.from for safer initialization
const rawBytes = Buffer.from(req.body.string)
const encoded = rawBytes.toString('base64')
res.end({ encoded: encoded })
}
```
--------------------------------
### Illustrative Code Snippet (JavaScript)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/loose-envify/README.md
This example demonstrates a common scenario where loose-envify might be used to replace process.env variables. It shows a template string that, due to loose-envify's limitations, would not have process.env.NODE_ENV replaced.
```javascript
console.log(`the current env is ${process.env.NODE_ENV}`);
```
--------------------------------
### Controlling Übersicht with AppleScript
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Provides examples of how to control Übersicht using AppleScript. It covers refreshing all widgets, refreshing a specific widget by ID, listing all widgets, and showing or hiding widgets by ID. These commands are sent to the application using its application ID.
```applescript
tell application id "tracesOf.Uebersicht" to refresh
```
```applescript
tell application id "tracesOf.Uebersicht" to refresh widget id "my-widget"
```
```applescript
tell application id "tracesOf.Uebersicht" to every widget
```
```applescript
tell application id "tracesOf.Uebersicht" to set hidden of widget id "top-cpu-coffee" to false
```
--------------------------------
### Using jQuery/Zepto with $.ua
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/ua-parser-js/readme.md
This snippet demonstrates how to use the UAParser.js library with jQuery or Zepto. It automatically creates a $.ua object for parsing user agent strings and provides methods to get and set the user agent. It also shows how to add CSS classes to the body based on browser and device type.
```javascript
console.log($.ua.device);
console.log($.ua.os);
console.log($.ua.os.name);
console.log($.ua.get());
$.ua.set('Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; Xoom Build/HWI69) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13');
console.log($.ua.browser.name);
console.log($.ua.engine.name);
console.log($.ua.device);
console.log(parseInt($.ua.browser.version.split('.')[0], 10));
$('body').addClass('ua-browser-' + $.ua.browser.name + ' ua-devicetype-' + $.ua.device.type);
```
--------------------------------
### Set X-Request-URL Header in Ruby
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/whatwg-fetch/README.md
Provides a Ruby on Rails controller example to set the 'X-Request-URL' response header. This is a workaround to ensure a reliable 'response.url' value in older browsers that may not handle HTTP redirects correctly with the fetch API.
```ruby
# Ruby on Rails controller example
response.headers['X-Request-URL'] = request.url
```
--------------------------------
### Get Response Body as Buffer with Node-Fetch
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/node-fetch/README.md
Shows how to retrieve the entire response body as a Buffer using node-fetch's `buffer()` method. This is useful when you need to process binary data in memory, such as determining file types. Note that `buffer()` is a node-fetch specific API.
```javascript
var fetch = require('node-fetch');
var fileType = require('file-type');
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(function(res) {
return res.buffer();
}).then(function(buffer) {
fileType(buffer);
});
```
--------------------------------
### Node.js HTTP Server User-Agent Parsing with UASparser.js
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/ua-parser-js/readme.md
This example shows how to integrate UASparser.js into a Node.js HTTP server to parse the 'User-Agent' header from incoming requests. It listens on port 1337 and responds with the JSON representation of the parsed user-agent string. Requires 'ua-parser-js' to be installed via npm.
```javascript
var http = require('http');
var parser = require('ua-parser-js');
http.createServer(function (req, res) {
// get user-agent header
var ua = parser(req.headers['user-agent']);
// write the result as response
res.end(JSON.stringify(ua, null, ' '));
})
.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
```
--------------------------------
### Run TestChat Server (Go)
Source: https://github.com/felixhageloh/uebersicht/blob/master/Pods/SocketRocket/README.rst
Instructions to run the Go implementation of the TestChat server. This involves navigating to the Go server directory and executing the chatroom.go file using the 'go run' command.
```bash
cd TestChatServer/go
go run chatroom.go
```
--------------------------------
### Benchmark Execution (Shell)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/loose-envify/README.md
These shell commands show how to run benchmarks for both 'envify' and 'loose-envify'. The commands iterate five times to provide an average performance comparison.
```shell
for i in {1..5}; do node bench/bench.js 'envify'; done
```
```shell
for i in {1..5}; do node bench/bench.js '../'; done
```
--------------------------------
### Running Shell Commands
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Demonstrates how to run shell commands asynchronously using the `run` function imported from the `uebersicht` module. The output or any errors are handled via Promises.
```APIDOC
## Running Shell Commands
If need to run extra shell commands without using the [command](#command) property, you can import the `run` function from the `uebersicht` module.
It returns a Promise, which will resolve to the output of the command (stdout) or reject if any error occurred.
### Request Example
```jsx
import { run } from 'uebersicht'
export const render => (props, dispatch) {
return (
);
}
```
> Note that in order to receive click events you need to configure an interaction shortcut and give Übersicht accessibility access.
```
--------------------------------
### Basic Encoding and Decoding
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/iconv-lite/README.md
Demonstrates how to convert between buffers and strings using the iconv-lite library and verify if an encoding is supported.
```javascript
var iconv = require('iconv-lite');
// Convert from an encoded buffer to js string.
str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251');
// Convert from js string to an encoded buffer.
buf = iconv.encode("Sample input string", 'win1251');
// Check if encoding is supported
iconv.encodingExists("us-ascii")
```
--------------------------------
### Resolving Ambiguity via Flag Validation
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/js-tokens/README.md
Example showing how invalid regex flags help the tokenizer correctly identify division operations.
```javascript
var number = bar / 2/e;
```
--------------------------------
### Create a New Promise
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/promise/Readme.md
Demonstrates how to create a new Promise instance using the 'promise' library. The constructor takes a function with 'resolve' and 'reject' arguments to handle asynchronous operations.
```javascript
var Promise = require('promise');
var promise = new Promise(function (resolve, reject) {
get('http://www.google.com', function (err, res) {
if (err) reject(err);
else resolve(res);
});
});
```
--------------------------------
### Execute Task with Raw ASAP and Domain Binding
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/asap/README.md
Uses the 'asap/raw' module for faster execution without error checking. Includes logic to bind the task to the current Node.js domain if one exists, ensuring proper context.
```javascript
if (process.domain) {
task = process.domain.bind(task);
}
rawAsap(task);
```
--------------------------------
### Define Initial Widget State
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
The initialState property provides the starting state for the widget before any commands have run, ensuring the render function has data on the first pass.
```jsx
export const initialState = { output: 'Loading...' };
export const initialState = {
weather: null,
location: null,
loading: true,
error: null,
lastUpdated: null
};
```
--------------------------------
### Run Shell Commands with Übersicht
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Demonstrates how to execute shell commands asynchronously using the `run` function imported from the `uebersicht` module. It returns a Promise that resolves with the command's stdout or rejects on error. This is useful for integrating external command-line tools into your widgets.
```jsx
import { run } from 'uebersicht'
export const render => (props, dispatch) {
return (
);
}
```
--------------------------------
### Configure Rejection Tracking Options
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/promise/Readme.md
Demonstrates configuring the rejection tracking with custom options such as 'allRejections', 'whitelist' for specific error types, and custom 'onUnhandled'/'onHandled' callbacks.
```javascript
// Example of custom options for rejection tracking:
// rejection-tracking.enable({
// allRejections: true,
// whitelist: [Error],
// onUnhandled: function(id, error) { console.error('Unhandled:', id, error); },
// onHandled: function(id, error) { console.log('Handled:', id, error); }
// });
```
--------------------------------
### React Component with PropTypes Validation
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/prop-types/README.md
An example of using PropTypes to define and validate the types of props passed to a React component, including various validator types and required props.
```javascript
import React from 'react';
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
// ... do things with the props
}
}
MyComponent.propTypes = {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
// A React element.
optionalElement: PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: PropTypes.func.isRequired,
// A value of any data type
requiredAny: PropTypes.any.isRequired,
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `'
+ propName + '` supplied to'
+ ' `' + componentName + '`. Validation failed.'
);
}
},
// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
if (!/matchme/.test(propValue[key])) {
return new Error(
'Invalid prop `'
+ propFullName + '` supplied to'
+ ' `' + componentName + '`. Validation failed.'
);
}
})
};
```
--------------------------------
### Code Snippet with Comments (JavaScript)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/loose-envify/README.md
This example illustrates another limitation of loose-envify: it does not handle oddly-spaced or commented expressions when replacing process.env variables. The commented version of accessing process.env.NODE_ENV will not be processed.
```javascript
console.log(process./*won't*/env./*work*/NODE_ENV);
```
--------------------------------
### SRWebSocket Initialization and Connection
Source: https://github.com/felixhageloh/uebersicht/blob/master/Pods/SocketRocket/README.rst
How to initialize and open a WebSocket connection using the SRWebSocket class.
```APIDOC
## [Objective-C] SRWebSocket Initialization
### Description
Initializes a new WebSocket instance with a URL request and opens the connection.
### Method
N/A (Class Method/Instance Method)
### Endpoint
SRWebSocket
### Parameters
#### Request Body
- **request** (NSURLRequest) - Required - The URL request containing the WebSocket endpoint URL.
### Request Example
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://example.com/chat"]];
SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURLRequest:request];
webSocket.delegate = self;
[webSocket open];
```
--------------------------------
### Update Widget DOM (CoffeeScript)
Source: https://github.com/felixhageloh/uebersicht/blob/master/ClassicWidgets.md
A function called after rendering to perform DOM manipulations or one-time setups. Receives the command output and a reference to the rendered DOM element. If not provided, 'render' is called instead.
```coffeescript
# we don't care about output here
render: (_) -> """
"""
update: (output, domEl) ->
$(domEl).find('.bar').css height: output+'%'
```
--------------------------------
### Migrate Buffer Constructors to Buffer.alloc/from
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Porting-Buffer.md
This section outlines the recommended replacements for deprecated Buffer constructor usages. It details how to convert calls like `new Buffer(number)` to `Buffer.alloc(number)`, and `new Buffer(string)` to `Buffer.from(string)`. This ensures compatibility with modern Node.js versions and avoids deprecation warnings.
```javascript
// Replace new Buffer(number) with Buffer.alloc(number)
// Example: const buf = new Buffer(10);
const buf = Buffer.alloc(10);
// Replace new Buffer(string) or new Buffer(string, encoding) with Buffer.from(string) or Buffer.from(string, encoding)
// Example: const bufFromString = new Buffer('hello');
const bufFromString = Buffer.from('hello');
// For other rarer cases, use Buffer.from(...arguments)
// Example: const bufOther = new Buffer(someArray, 'base64');
const bufOther = Buffer.from(someArray, 'base64');
```
--------------------------------
### Build Node.js App with npm
Source: https://github.com/felixhageloh/uebersicht/blob/master/ClassicWidgets.md
Command to build the Node.js application separately using npm. This is automatically handled when building with Xcode.
```bash
npm run release
```
--------------------------------
### React DOM Server Rendering
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/react-dom/README.md
Demonstrates how to use react-dom/server for server-side rendering of React components.
```APIDOC
## React DOM Server Rendering
### Description
This section details how to use `react-dom/server` for server-side rendering of React components, generating HTML strings.
### Method
`ReactDOMServer.renderToString()`
`ReactDOMServer.renderToStaticMarkup()`
### Endpoint
N/A (Server-side rendering)
### Parameters
#### Request Body
- **Component** (ReactElement) - Required - The React element to render.
### Request Example
```javascript
var React = require('react');
var ReactDOMServer = require('react-dom/server');
class MyComponent extends React.Component {
render() {
return
"
```
### Response
#### Success Response (200)
- **htmlString** (string) - The rendered HTML string of the component.
#### Response Example
```json
{
"example": "
Hello World
"
}
```
```
--------------------------------
### Import PropTypes in JavaScript
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/prop-types/README.md
Demonstrates how to import the PropTypes library in both ES6 and ES5 JavaScript environments.
```javascript
import PropTypes from 'prop-types'; // ES6
```
```javascript
var PropTypes = require('prop-types'); // ES5 with npm
```
--------------------------------
### Access Response Meta Information with Node-Fetch
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/node-fetch/README.md
Illustrates how to access metadata of a fetch response, including status, status text, and headers. It shows how to check if the response was successful (`res.ok`), get the status code, status text, and retrieve all headers or a specific header value.
```javascript
var fetch = require('node-fetch');
fetch('https://github.com/')
.then(function(res) {
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers.raw());
console.log(res.headers.get('content-type'));
});
```
--------------------------------
### React DOM Browser Rendering
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/react-dom/README.md
Demonstrates how to use react-dom for rendering React components in the browser.
```APIDOC
## React DOM Browser Rendering
### Description
This section details how to use `react-dom` to render React components within a web browser.
### Method
`ReactDOM.render(, DOMNode)`
### Endpoint
N/A (Client-side rendering)
### Parameters
#### Request Body
- **Component** (ReactElement) - Required - The React element to render.
- **DOMNode** (HTMLElement) - Required - The DOM node to which the component will be rendered.
### Request Example
```javascript
var React = require('react');
var ReactDOM = require('react-dom');
class MyComponent extends React.Component {
render() {
return
Hello World
;
}
}
var node = document.getElementById('app');
ReactDOM.render(, node);
```
### Response
#### Success Response (200)
N/A (DOM manipulation)
#### Response Example
N/A
```
--------------------------------
### Setting up Git for Unicode Characters
Source: https://github.com/felixhageloh/uebersicht/blob/master/README.md
Addresses an issue where Git might not handle umlauts (ü) in path names correctly, causing them to appear as untracked files. It suggests configuring `git config core.precomposeunicode false` to resolve this, noting that the common advice is often to set it to `true` depending on the OS and Git version.
```git
git config core.precomposeunicode false
```
--------------------------------
### POST Request with Simple Body using Node-Fetch
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/node-fetch/README.md
Demonstrates how to make a POST request with a simple string body using node-fetch. The request is sent to `http://httpbin.org/post`, and the JSON response, which includes the request details, is logged to the console.
```javascript
var fetch = require('node-fetch');
fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
```
--------------------------------
### Node.js: Deprecated Buffer Constructor Usage Example
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Porting-Buffer.md
This code snippet illustrates the usage of the deprecated Buffer constructor, which can lead to security vulnerabilities. Passing a string initializes a buffer with its UTF-8 representation, but passing a number can result in uninitialized memory being used or large memory allocations, depending on the Node.js version.
```javascript
function stringToBase64(req, res) {
// The request body should have the format of `{ string: 'foobar' }`
// Using the deprecated Buffer constructor, which is unsafe
const rawBytes = new Buffer(req.body.string)
const encoded = rawBytes.toString('base64')
res.end({ encoded: encoded })
}
```
--------------------------------
### Command-Line Interface Usage of UASparser.js
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/ua-parser-js/readme.md
This section details how to use the UASparser.js script directly from the command line. It covers parsing single or multiple user-agent strings, processing piped input, and reading from a log file. This is useful for batch processing or quick checks without a full Node.js server setup.
```bash
$ node ua-parser.min.js "Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)"
# multiple args
$ node ua-parser.min.js "Opera/1.2" "Opera/3.4"
# piped args
$ echo "Opera/1.2" | node ua-parser.min.js
# log file
$ cat ua.log | node ua-parser.min.js
```
--------------------------------
### safe-buffer Masking Unsafe Buffer Allocation (Console)
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Readme.md
This example demonstrates how requiring 'safe-buffer' and then using its Buffer constructor can suppress linter warnings, even though the underlying behavior of allocating uninitialized memory persists on older Node.js versions (like 6.x). This highlights a significant footgun where 'safe-buffer' appears to fix the issue but does not.
```bash
$ cat example.safe-buffer.js
const Buffer = require('safe-buffer').Buffer
console.log(Buffer(20))
$ standard example.safe-buffer.js
$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js
```
--------------------------------
### Import js-tokens and matchToToken
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/js-tokens/README.md
Illustrates how to import the js-tokens library and its utility function `matchToToken`. This function converts regex matches into structured token objects, providing type and value information.
```javascript
import jsTokens from "js-tokens"
// or:
var jsTokens = require("js-tokens").default
```
```javascript
import {matchToToken} from "js-js-tokens"
// or:
var matchToToken = require("js-tokens").matchToToken
```
--------------------------------
### Using Safer Buffer in JavaScript
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/safer-buffer/Readme.md
Demonstrates how to import and use Safer Buffer as an alternative to the native Buffer in Node.js. This approach avoids overriding the global Buffer and provides safer methods for buffer operations, though it requires explicit use of SaferBuffer.from and SaferBuffer.alloc.
```javascript
var SaferBuffer = require('safer-buffer').Buffer;
// Use SaferBuffer.from and SaferBuffer.alloc instead of Buffer.from and Buffer.alloc
const buffer = SaferBuffer.alloc(10);
const fromBuffer = SaferBuffer.from('hello');
```
--------------------------------
### UAParser.js Constructor
Source: https://github.com/felixhageloh/uebersicht/blob/master/node_modules/ua-parser-js/readme.md
Initializes a new instance of the UAParser.js library. It can optionally take a user-agent string and extensions as arguments.
```APIDOC
## Constructor
* `new UAParser([uastring][,extensions])`
* returns new instance
* `UAParser([uastring][,extensions])`
* returns result object `{ ua: '', browser: {}, cpu: {}, device: {}, engine: {}, os: {} }`
```
--------------------------------
### Shell Command Execution: run
Source: https://context7.com/felixhageloh/uebersicht/llms.txt
The run function allows widgets to execute shell commands programmatically, enabling interaction with the OS.
```APIDOC
## run(command)
### Description
Executes a shell command asynchronously and returns a promise resolving to the command output.
### Parameters
- **command** (string) - Required - The shell command to execute.
### Response
- **Promise** (string) - Resolves with the standard output of the command.
### Example
```javascript
import { run } from 'uebersicht';
run('date').then(output => console.log(output));
```
```