Snippets Collections
function calculate(options) {
  const num1 = options.num1;
  const operator = options.operator;
  const num2 = options.num2;

  let sum;

  // if the operator does not equal to plus minus multiply or subtract
  switch (operator) {
    case "+":
      sum = num1 + num2;
      break;

    case "-":
      sum += num1 - num2;
      break;

    case "*":
      sum += num1 * num2;
      break;

    case "/":
      sum += num1 / num2;
      break;

    default:
      sum = "Sorry no operator assigned";
      break;
  }

  return sum; // dont forget to return sum after the switch has executed
}

console.log(
  calculate({
    num1: 3,
    operator: "+",
    num2: 4,
  })
);
prec = precision_score(y_test, (y_prob> threshold))
f1_sc = f1_score(y_test, (y_prob> threshold))

# Permutation feature importance
feature_importance_scores = []
for feature in X_train_required.columns:
    X_permuted = X_test_required.copy()
    X_permuted[feature] = np.random.permutation(X_permuted[feature])
    permuted_preds = cb_model.predict(X_permuted)
    permuted_prec = precision_score(y_test, permuted_preds)
    feature_importance = prec - permuted_prec
    feature_importance_scores.append((feature, feature_importance))
# feature_importance_scores.sort(key=lambda x: x[1], reverse=True)
feat=[]
imp=[]
for feature, importance in feature_importance_scores:
    feat.append(feature)
    imp.append(importance)   
    # print(f"Feature: {feature}, Importance: {importance}")
feature_imp = pd.DataFrame(columns=['Feature', 'Importance'])
feature_imp['Feature']=feat
feature_imp['Importance']=imp
feature_imp.sort_values(by='Importance', ascending=False, inplace=True)
feature_imp.to_csv('OMI-trans-perm.csv')
def prepare_master_datasets(df: pd.DataFrame, start_date: str = '2021-01-01', end_date:str = None, time_series_split: bool = True, test_start_date: str = '2021-01-01', test_end_date:str = None, test_size: float = 0.2, random_state: int = 42) -> pd.DataFrame:

	# function definition
    
# Funtion call

master_data, X_train_raw, X_test_raw = prepare_master_datasets(claims_data, 
                                                               start_date='2021-01-01', 
                                                               end_date='2022-12-31', 
                                                               time_series_split = True,
                                                               test_start_date = '2022-06-30', 
                                                               test_end_date = '2022-12-31',
                                                               test_size=0.2, random_state=SEED)
const prices = [400.50, 3000, 99.99, 35.99, 12.00, 9500];


// Sorting books by their rating: // use slice to copy the array
const acscendingsOrders = prices.slice().sort((a, b) => a.toFixed(2) - b.toFixed(2))
const descendingOrders = prices.slice().sort((a, b) => b.toFixed(2) - a.toFixed(2))

/** The indexOf() method
	Returns the position of the first occurrence of a value in a string.
	The indexOf() method returns -1 if the value is not found.
	The indexOf() method is case sensitive.
  */


function isValidPassword(password, username) {
	if (
		password.length < 8 ||
		password.indexOf(' ') !== -1 ||
		password.indexOf(username) !== -1
	) {
		return false;
	}
	return true;
}

/** or */


function isValidPassword(password, username) {
	const tooShort = password.length < 8;
	const hasSpace = password.indexOf(' ') !== -1;
	const tooSimilar = password.indexOf(username) !== -1;
	if (tooShort || hasSpace || tooSimilar) return false;
	return true;
}
function betweenYears(yearStart, yearEnd){
    return function(number){
          if(number >= yearStart && number <= yearEnd){
              return number
          }
          return false
    }
}

const myYear = betweenYears(1900, 1999);
myYear(1978);
const ages = [18, 20, 21, 30];

const agesPlusOne = ages.map(age => age + 1);
export const getElement = (selection) => {
  const element = document.querySelector(selection);
  if (element) {
    return element;
  }
  throw new Error(
    `Please check "${selection}" selector, no such element exists`
  );
}


export const getAllElements = (elements) => {
    const allelements = document.querySelectorAll(elements);
    if(allelements){
      return allelements
    }
    throw new Error(`These ${elements} cannot be found`)
}
// place the codes in functions.php and call the function wherever you want.

function philosophy_pagination()
{
   global $wp_query;
   $links = paginate_links(array(
      'current'      => max(1, get_query_var('paged')),
      'total'        => $wp_query->max_num_pages,
      'type'         => 'list',
      'mid_size'     => 3,
   ));
   $links = str_replace('page-numbers', 'pgn__num', $links);
   $links = str_replace("<ul class='pgn__num'>", "<ul>", $links);
   $links = str_replace('next pgn__num', 'pgn__next', $links);
   $links = str_replace('prev pgn__num', 'pgn__prev', $links);
   echo wp_kses_post($links);
}
// Les briques de base que nous allons composer
const double = x => x + x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;

// Une fonction qui permet d'appliquer une composition
const pipe = (...functions) => input => functions.reduce(
    (acc, fn) => fn(acc),
    input
);

// On crée des fonctions pour multiplier par un facteur donné
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);

// Utilisation
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
#!/bin/bash
#####################################################################
#Author:Irfan Khan
#Description:this function will used to donwload & move that file to
#desired location
#####################################################################
download(){
    #$url=$1
    wget -cO - https://gist.github.com/chales/11359952/archive/25f48802442b7986070036d214a2a37b8486282d.zip > dbtest.zip
    if [[ -f dbtest.zip ]];
    then
        mv dbtest.zip ./mydb_data
        exit 0
    else
        echo "hey file not moved some thing went wrong.."
    fi
}

download  #calling the function
cell.cellButton.tag = indexPath.row
            cell.cellButton.addTarget(self, action: #selector(yourFunc(sender:)), for: UIControl.Event.touchUpInside)
                                                            
@objc func yourFunc(sender: UIButton){
    let buttonTag = sender.tag
}
const pipe = (...ops) => {
  const _pipe = (a, b) => (arg) => b(a(arg));
  let bundle = ops.reduce((prevOp, nextOp) => {
    return _pipe(prevOp,nextOp);
  });
  return bundle;
}
const textBlock = 0.37645448;
  const pageWidth = $('.container').width();
  const pageHeight = $('.container').height();
	
  if (pageWidth <= 1920 && pageHeight <= 1080) {
    $('.container').css()
  } else {
    $('.container').css('max-width', '100%')
  }
rmsval = df.loc[:, 'c1':'c4']
def getrms(row):  
  a = np.sqrt(sum(row**2/4))
  return a
df['rms'] = df.apply(getrms,axis=1)
df.head()
for c in df_drop.columns:
    df_drop[c] = df_drop[c].str.replace('[^\w\s]+', '')
df_drop = df_drop.astype(str)
df_drop.head()
add_action( 'wp_body_open', 'wpdoc_add_custom_body_open_code' );
 
function wpdoc_add_custom_body_open_code() {
    echo '<!-- Google Tag Manager (noscript) --> ... <!-- End Google Tag Manager (noscript) -->';
}
def byte_size(string):

  return(len(string.encode('utf-8')))

byte_size('😀’) # 4
byte_size('Hello World') # 11
Use functools.reduce() to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
from functools import reduce

1.def compose(*fns):
  2.return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
#define a function 
 Def cube(num)
      #write the formula of cube
      return num*num*num
     #give the number to calculate the cube 
     cube(3)
   # print the cube of that number simply by using print command
    print(cube(3))
     “return” keyword means that function have to return          value
 # give a name of function after def
 1.def sayhi():
      #put the statement in the function  
     2.print(“hello world”)
#call function by name:
3.sayhi()


Output: 
Hello world
#define function
defall_unique(lst):

   return len(lst) == len(set(lst))
   
x = [1,1,2,2,3,2,3,4,5,6]


y = [1,2,3,4,5]


all_unique(x) # False
all_unique(y) # True
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
   
#make a function:
def get_vowels(string):

#return is the keyword which means function have to return value: 
 return [each for each in string if each in 'aeiou']


#assign the words and function will return vowels words.
get_vowels('foobar') # ['o', 'o', 'a']


get_vowels('gym') # []
#define a function 
 1.Def cube(num)
      #write the formula of cube
      2.return num*num*num
     #give the number to calculate the cube 
     3.cube(3)
   # print the cube of that number simply by using print command
    4.print(cube(3))
     5.“return” keyword means that function have to return value         
def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
  
EXAMPLES
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) # 4
double_even_numbers(1) # 1
def unfold(fn, seed):
  def fn_generator(val):
    while True: 
      val = fn(val[1])
      if val == False: break
      yield val[0]
  return [i for i in fn_generator([None, seed])]
  
  
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40, -50]
from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)


EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
star

Thu May 02 2024 06:15:07 GMT+0000 (Coordinated Universal Time)

#switch #statement #function #object
star

Mon Sep 11 2023 05:02:11 GMT+0000 (Coordinated Universal Time)

#function #definition
star

Thu Aug 31 2023 03:49:22 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/python/recursive-function-in-python

#python #function
star

Thu Aug 10 2023 11:04:21 GMT+0000 (Coordinated Universal Time)

#function #definition
star

Wed Apr 12 2023 05:58:05 GMT+0000 (Coordinated Universal Time)

#function #return #values #filtering
star

Wed Apr 12 2023 01:00:20 GMT+0000 (Coordinated Universal Time)

#function #return #values #filtering
star

Wed Apr 12 2023 00:20:59 GMT+0000 (Coordinated Universal Time)

#function #return #values #filtering
star

Wed Apr 05 2023 16:01:56 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-apply-function-to-every-array-element-in-javascript/

#javascript #array #every #loop #function
star

Wed Mar 22 2023 00:46:04 GMT+0000 (Coordinated Universal Time)

#get #element #function
star

Sat May 14 2022 10:38:29 GMT+0000 (Coordinated Universal Time)

#pagination #function
star

Sat Feb 12 2022 14:41:52 GMT+0000 (Coordinated Universal Time) https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

#function #composition
star

Wed Feb 09 2022 12:29:41 GMT+0000 (Coordinated Universal Time)

#linux #shellscript #function #wget #download
star

Sun Dec 26 2021 19:54:30 GMT+0000 (Coordinated Universal Time) undefined

#javascript #pipe #function
star

Fri Jul 16 2021 16:32:57 GMT+0000 (Coordinated Universal Time)

#resize #jquery #function
star

Wed Jul 14 2021 15:19:10 GMT+0000 (Coordinated Universal Time)

#textpreprocessing #nlp #function #pandas
star

Wed Jul 14 2021 15:14:15 GMT+0000 (Coordinated Universal Time)

#textpreprocessing #nlp #pandas #function
star

Sat Mar 06 2021 03:42:11 GMT+0000 (Coordinated Universal Time) https://rckflr.com

#wordpress #google #tag #manager #function
star

Mon Apr 20 2020 13:45:46 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #function #bytesize #return
star

Mon Apr 20 2020 13:38:08 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/compose/

#python #python #function #composition
star

Mon Apr 20 2020 13:32:07 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #python #function #return
star

Mon Apr 20 2020 13:17:59 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #function #python #def
star

Tue Mar 31 2020 11:40:31 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #function #return #allunique
star

Tue Mar 31 2020 11:35:03 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #strings #vowels #function
star

Tue Mar 31 2020 05:43:21 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #function #returnfunction
star

Sat Jan 11 2020 20:54:48 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/when/

#python #function
star

Fri Jan 10 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/unfold/

#python #lists #function
star

Thu Jan 09 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/compose/

#python #function

Save snippets that work with our extensions

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