Snippets Collections
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search
                                
function greet(name)
{
    console.log("Hello "+name);
};

res = greet("john");
console.log(res);
import javax.swing.*;  
public class FirstSwingExample {  
public static void main(String[] args) {  
JFrame f=new JFrame();//creating instance of JFrame  
          
JButton b=new JButton("click");//creating instance of JButton  
b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
          
f.add(b);//adding button in JFrame  
          
f.setSize(400,500);//400 width and 500 height  
f.setLayout(null);//using no layout managers  
f.setVisible(true);//making the frame visible  
}  
}  
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
function full_stack_developer() {
    full_stack_developer();
}
document.addEventListener %28"keydown", function (zEvent%29 {
    if (zEvent.ctrlKey  &&  zEvent.altKey  &&  zEvent.key === "e") {  // case sensitive
        // DO YOUR STUFF HERE
    }
} );

                                
<html>

<input id="contact" name="address">

<script>

    var x = document.getElementById("contact").getAttribute('name');

</script>

</html>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>IDECodeSnippetCompletionPrefix</key>
	<string>snippetAlert</string>
	<key>IDECodeSnippetCompletionScopes</key>
	<array>
		<string>All</string>
	</array>
	<key>IDECodeSnippetContents</key>
	<string>let alertController = UIAlertController(title: &lt;#T##String?#&gt;, message: &lt;#T##String?#&gt;, preferredStyle: &lt;#T##UIAlertController.Style#&gt;)
let firstAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .default, handler: &lt;#T##((UIAlertAction) -&gt; Void)?##((UIAlertAction) -&gt; Void)?##(UIAlertAction) -&gt; Void#&gt;)
let cancelAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .cancel, handler: nil)

alertController.addAction(firstAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)</string>
	<key>IDECodeSnippetIdentifier</key>
	<string>8C458AD7-C631-457B-85CC-D2501E425D59</string>
	<key>IDECodeSnippetLanguage</key>
	<string>Xcode.SourceCodeLanguage.Swift</string>
	<key>IDECodeSnippetSummary</key>
	<string></string>
	<key>IDECodeSnippetTitle</key>
	<string>UIAlertController</string>
	<key>IDECodeSnippetUserSnippet</key>
	<true/>
	<key>IDECodeSnippetVersion</key>
	<integer>2</integer>
</dict>
</plist>
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">

<body>
	<textarea class="codemirror-textarea"></textarea>
</body>

<script>

$(document).ready(function(){
    var codeText = $(".codemirror-textarea")[0];
    var editor = CodeMirror.fromTextArea(codeText, {
        lineNumbers : true
    });
});

</script>

<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
 const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
hello(undefined);

// These will not
hello(null);
hello('David');
The idea here is that it uses default parameters, like how the b parameter here has a default if you don’t send it anything:
function multiply(a, b = 1) {
  return a * b;
}                               
                                
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
ip addr | grep eth0 | grep inet | awk '{print $2}' | awk -F '/' '{print $1}' | awk '{printf "%s:3000", $0}' | clip.exe
function copyToClipboard(){

    var codeToBeCopied = document.getElementById('code-snippet').innerText;
    var emptyArea = document.createElement('TEXTAREA');
    emptyArea.innerHTML = codeToBeCopied;
    const parentElement = document.getElementById('post-title');
    parentElement.appendChild(emptyArea);

    emptyArea.select();
    document.execCommand('copy');

    parentElement.removeChild(emptyArea);
    M.toast({html: 'Code copied to clipboard'})

    }
def addNums(a,b):
    summa = a + b
    return summa
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
var url = "http://scratch99.com/web-development/javascript/";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
import java.util.*;
import java.util.function.*;
import java.util.stream.Stream;
class Employee {
    String name;
    int salary;
    Employee(String name,int salary){
        this.name=name;
        this.salary=salary;
        }
        public String getName(){
            return name;
        }
        public int getSalary(){
            return salary;
        }
            public void setName(String name){
        this.name=name;
            }
            
        public void setSalary(int salary){
            this.salary=salary;
        }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("<");
        sb.append("name: ");
        sb.append(name);
        sb.append(" salary: ");
        sb.append("" + salary+">");
        return sb.toString();

    }
}
class EmployeeInfo{
    enum SortMethod {
        BYNAME,BYSALARY;
    };

    public List<Employee> sort(List<Employee> emps, final SortMethod method){
        if(method.equals(method.BYNAME)){
         
             Collections.sort(emps,(e1,e2)->{return e1.name.compareTo(e2.name);
             });
        }
             else if(method.equals(method.BYSALARY)){
                 
                Collections.sort(emps,(e1,e2)->{
                int i =e1.salary - e2.salary;
                if(i==0) {
                    return e1.name.compareTo(e2.name);
                }
                else {
                    return i;
                }
            });
             }
             return emps;
    }
   public boolean isCharacterPresentInAllNames(Collection<Employee> entities, String character){
       Predicate<Employee> p1=s -> s.name.contains(character);
        boolean b1 = entities.stream().allMatch(p1);
        return b1;
   }


}
    btns = document.getElementsByClassName("saveBtn");
    for (var i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function () {
			//Add function here
        });
    }
  //split by separator and pick the first one. 
  //This has all the characters till null excluding null itself.
  retByteArray := bytes.Split(byteArray[:], []byte{0}) [0]

  // OR 

  //If you want a true C-like string including the null character
  retByteArray := bytes.SplitAfter(byteArray[:], []byte{0}) [0]
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
body{
    background-image: url("img_tree.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>
$ git status 
$ git add .
$ git commit -m "update information"
$ git push heroku master
$ git heroku open
for (let step = 0; step < 5; step++) {
  // Runs 5 times, with values of step 0 through 4.
  console.log('Walking east one step');
}
 foo += -bar + (bar += 5);
// foo and bar are now 15
                                
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
#include<iostream>
using namespace std;
bool issafe(int** arr,int x,int y,int n){
    for(int row=0;row<=x;row++){
        if(arr[x][y]==1){
            return false;
        }
    }
    int row=x;
    int col=y;
    while(row>=0 && col>=0){
        if(arr[row][col]==1){
            return false;
        }
        row--;
        col--;
    }
     row=x;
     col=y;
    while(row>=0 && col<n){
        if(arr[row][col]==1){
            return false;
        }
        row--;
        col++;
    }
    return true ;
}
bool nqueen(int** arr,int x,int n){
    if(x>=n){
        return true;
    }
    for(int col=0;col<=n;col++){
        if(issafe(arr,x,col,n)){
            arr[x][col]==1;
            if(nqueen(arr,x+1,n)){
                return true;
            }
            arr[x][col]=0;  //backtracking
            
        }
    }
    return false;
}
int main(){
    int n;
    cin>>n;
    int** arr=new int*[n];
    for(int i=0;i<n;i++){
        arr[i]=new int[n];
        for(int j=0;j<n;j++){
            arr[i][j]=0;

        }
    }
    if(nqueen(arr,0,n)){
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout<<arr[i][j]<<"";
            }cout<<endl;
        }
    }


    return 0;
}
axios.post('http://10.0.1.14:8001/api/logout',request_data, {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer '+token
          },      
      })      
      .then((response) => {
        console.log('response',response.data)

      })
      .catch((error) => {
        alert('error',error.response)
        dispatch(userUpdateProfileFail())

      })

  // console.log('----cheers---------',data)
dispatch(userUpdateProfileSuccess(data))
def faktorial(N):
    i=1
    fakt=1
    while i!=N+1:
        fakt = fakt*i        
        i += 1
    return fakt

print(faktorial(5))
//// Validate if Email field is spam
add_action( 'elementor_pro/forms/validation/email', function( $field, $record, $ajax_handler ) {
    // Looking if email found in spam array, you can add to the array
  $spamemails = array("ericjonesonline@outlook.com", "eric@talkwithwebvisitor.com");
    if ( in_array( $field['value'] , $spamemails) ) {
        $ajax_handler->add_error( $field['id'], 'אנחנו לא אוהבים ספאם, נסו מייל אחר' );
    }
}, 10, 3 );
<h2>Turbo Drive</h2>
<div>
  <a href="/greeting/?person=Josh">Click here to greet Josh (fast)</a>
</div>
<div>
    <a href="/greeting/?person=Josh&sleep=true">Click here to greet Josh (slow)</a>
</div>
#include <iostream>
#include<cmath>
#include<ctime>
#include<string>
#include <iomanip>
#include <fstream>

using namespace std;




void decToBinary(int n)
{
    // array to store binary number 
    int binaryNum[3][3];
    
    //converting to binary 
    for (int i = 0; i < 3; i++) 
    {
        for (int j = 0; j < 3; j++)
        {
            binaryNum[i][j] = n % 2;
            n = n / 2;

        }
     }       

    // printing binary> array in reverse order 
    for (int i = 3-1; i >= 0; i--){
        for (int j = 3 - 1; j >= 0; j--)
        {
            if (binaryNum[i][j] == 0)
                cout << "H" << " ";
            else
                cout << "T" << " ";
        }
        cout << endl;
    }
    
 }

int main()
{
    int n;
    cout << "Enter a decimal number between 1 and 512 ";
    cin >> n;

    decToBinary(n);
    return 0;
}



// Android Studio 4.0
android {
    buildFeatures {
        viewBinding = true
    }
}
static void Main(string[] args)
{
    using (WordprocessingDocument doc =
        WordprocessingDocument.Open(“Test.docx”, false))
    {
        foreach (var f in doc.MainDocumentPart.Fields())
            Console.WriteLine(“Id: {0} InstrText: {1}”, f.Id, f.InstrText);
    }
}
var express = require("express");
var app = express();
const session = require('express-session');
var MemcachedStore = require('connect-memjs')(session);

// configure sessions
var store = new MemcachedStore({servers: [process.env.MEMCACHEDCLOUD_SERVERS], username: process.env.MEMCACHEDCLOUD_USERNAME, password: process.env.MEMCACHEDCLOUD_PASSWORD});
app.use(session({ secret: 'keyboard cat',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true }, 
   store: store
}))
List<String> songList = new ArrayList<>();
songList.add("Some song"); //Repeat until satisfied

System.out.println("\n\tWelcome! Please choose a song!");
String songChoice = scan.nextLine();
while (!songList.contains(songChoice)) {
    //Do stuff when input is not a recognised song
}
The TypeConverter class is under namespace CsvHelper.TypeConversion

The TypeConverterAttribute is under namespace CsvHelper.Configuration.Attributes

    public class ToIntArrayConverter : TypeConverter
    {
        public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            string[] allElements = text.Split(',');
            int[] elementsAsInteger = allElements.Select(s => int.Parse(s)).ToArray();
            return new List<int>(elementsAsInteger);
        }

        public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return string.Join(',', ((List<int>)value).ToArray());
        }
    }
To use this converter, simply add the following TypeConverterAttribute annotations on top of your properties:
To use this converter, simply add the following TypeConverterAttribute annotations on top of your properties:

    public class Names
    {
        [Name("name")]
        public string Name { get; set; }

        [Name("numbersA")]
        [TypeConverter(typeof(ToIntArrayConverter))]
        public List<int> NumbersA { get; set; }

        [Name("numbersB")]
        [TypeConverter(typeof(ToIntArrayConverter))]
        public List<int> NumbersB { get; set; }
    }
<style>

 .circle:before {
                    content: ' \25CF';
                    font-size: 50px;
                    color: black;
                }
</style>

<span class="circle"></span>
from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
double AttackerSuccessProbability(double q, int z)
{
    double p = 1.0 - q;
    double lambda = z * (q / p);
    double sum = 1.0;
    int i, k;
    for (k = 0; k <= z; k++)
    {
        double poisson = exp(-lambda);
        for (i = 1; i <= k; i++)
            poisson *= lambda / i;
        sum -= poisson * (1 - pow(q / p, z - k));
    }
    return sum;
}
<?php 
function count_num_finger( $n ) 
{ 
	$r = $n % 8; 
	if ($r == 1) 
		return $r; 
	if ($r == 5) 
		return $r; 
	if ($r == 0 or $r == 2) 
		return 2; 
	if ($r == 3 or $r == 7) 
		return 3; 
	if ($r == 4 or $r == 6) 
		return 4; 
}	 

// Driver Code 
$n = 30; 
echo(count_num_finger($n)); 
 
?> 
<?php 
// PHP program to find nth 
// magic number 

// Function to find nth 
// magic number 
function nthMagicNo($n) 
{ 
	$pow = 1; 
	$answer = 0; 

	// Go through every bit of n 
	while ($n) 
	{ 
	$pow = $pow * 5; 

	// If last bit of n is set 
	if ($n & 1) 
		$answer += $pow; 

	// proceed to next bit 
	$n >>= 1; // or $n = $n/2 
	} 
	return $answer; 
} 

// Driver Code 
$n = 5; 
echo "nth magic number is ", 
	nthMagicNo($n), "\n"; 

// This code is contributed by Ajit. 
?> 
star

Fri May 01 2020 11:13:14 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

@FlowerFine #javascript

star

Fri Jul 09 2021 17:17:41 GMT+0000 (UTC)

@buildadev

star

Sun Jan 12 2020 17:40:37 GMT+0000 (UTC) https://slate.com/technology/2019/10/consequential-computer-code-software-history.html

@chrissyjones #historicalcode #numbers

star

Wed Jan 01 2020 19:00:00 GMT+0000 (UTC) https://www.javatpoint.com/java-swing

@price_the_ice #java #howto #interviewquestions #mobile

star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

@mishka #javascript #nodejs #commandline

star

https://docs.mongodb.com/manual/reference/operator/update/push/

#javascript #nodejs
star

Mon Mar 08 2021 22:02:08 GMT+0000 (UTC)

@rajesh #javascript

star

Mon May 04 2020 23:28:55 GMT+0000 (UTC) https://stackoverflow.com/questions/37557990/detecting-combination-keypresses-control-alt-shift

@sid

star

Sun Dec 29 2019 19:53:43 GMT+0000 (UTC) https://github.com/mjurfest/ios-xcode-snippets/blob/master/8C458AD7-C631-457B-85CC-D2501E425D59.codesnippet

@0musicon0 #ios #swift #howto #appdevelopment #apps

star

Tue May 05 2020 04:59:33 GMT+0000 (UTC) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

@sid #javascript

star

Fri Apr 24 2020 11:32:35 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/

@Dimples #javascript #javascript #functions #parameters

star

Fri Dec 27 2019 13:19:35 GMT+0000 (UTC) https://dev.to/codeluggage/today-i-wrote-a-handy-little-snippet-to-easily-access-ubuntu-from-windows-in-wsl2-19l

@swellcuban #commandline #interesting #windows #ubuntu #linux

star

Sun May 16 2021 13:28:29 GMT+0000 (UTC)

@anvarbek

star

Sat May 09 2020 19:43:38 GMT+0000 (UTC) https://api.jquery.com/jquery.post/

@prince333 #javascript #jquery

star

https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

@bravocoder #python

star

Fri Jan 10 2020 22:36:50 GMT+0000 (UTC) http://scratch99.com/web-development/javascript/how-to-get-the-domain-from-a-url/

@saint_r0ses #javascript #promises #howto

star

Mon Jul 19 2021 13:23:44 GMT+0000 (UTC)

@BHUPSAHU

star

Mon May 11 2020 14:52:46 GMT+0000 (UTC) https://stackoverflow.com/questions/14230145/how-to-convert-a-zero-terminated-byte-array-to-string

@tigran #go

star

Wed Jan 22 2020 18:43:41 GMT+0000 (UTC) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

@loop_ifthen #dart #flutter #layouts

star

https://www.w3schools.com/CSSref/pr_background-attachment.asp

@mishka #css #html

star

https://getbootstrap.com/docs/4.0/getting-started/introduction/

@mishka #html

star

Wed May 27 2020 01:44:35 GMT+0000 (UTC) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

@bob #javascript

star

Fri May 01 2020 11:34:52 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/add-number-two-variables/

@AngelGirl #javascript

star

https://developer.apple.com/documentation/uikit/uibutton

@mishka #ios #swift

star

Fri Jul 02 2021 17:34:27 GMT+0000 (UTC)

@rushi #c++

star

Sun Jun 20 2021 06:06:30 GMT+0000 (UTC) https://stackoverflow.com/questions/53495922/error-request-failed-with-status-code-401-axios-in-react-js

@Avirup #javascript

star

Sun May 16 2021 13:40:50 GMT+0000 (UTC)

@anvarbek

star

Fri May 07 2021 18:14:11 GMT+0000 (UTC)

@Alz #php

star

Mon Jan 11 2021 03:36:21 GMT+0000 (UTC)

@delitescere

star

Sat Jan 09 2021 02:24:44 GMT+0000 (UTC) http://cpp.sh/

@mahmoud hussein #c++

star

Wed Dec 30 2020 07:30:31 GMT+0000 (UTC)

@swalia ##kotlin,#java,#android

star

Sun Jun 21 2020 06:38:54 GMT+0000 (UTC) http://www.ericwhite.com/blog/retrieving-fields-in-open-xml-wordprocessingml-documents/

@ourexpertize

star

Wed Apr 01 2020 11:31:57 GMT+0000 (UTC) https://stackoverflow.com/questions/60967832/insert-arraylist-into-while-condition

@SunLoves #java #java #arraylists #while-loops #equala

star

Wed Apr 01 2020 08:42:17 GMT+0000 (UTC) https://stackoverflow.com/questions/60966194/using-csvhelper-to-read-cell-content-into-list-or-array

@Anier #C#

star

Mon Mar 02 2020 22:07:43 GMT+0000 (UTC)

@carlathemarla #css #shapes

star

Wed Jan 22 2020 18:52:28 GMT+0000 (UTC) https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

@logicloss01 #python #dates #functions #python3.8

star

Thu Dec 26 2019 15:18:45 GMT+0000 (UTC) https://www.geeksforgeeks.org/program-count-numbers-fingers/

@vasquezthefez #php #interesting #interviewquestions #logic

star

Wed Dec 25 2019 13:48:42 GMT+0000 (UTC) https://www.geeksforgeeks.org/find-nth-magic-number/

@marshmellow #php #interviewquestions #makethisbetter

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension