Snippets Collections
/*EX:.container {
    padding: 0 15px;
// 576px window width and more
    @include sm {
        padding: 0 20px;
    }
// 992px window width and more
    @include lg {
        margin-left: auto;
        margin-right: auto;
        max-width: 1100px;
    } */

// Small tablets and large smartphones (landscape view)
$screen-sm-min: 576px;

// Small tablets (portrait view)
$screen-md-min: 768px;

// Tablets and small desktops
$screen-lg-min: 992px;

// Large tablets and desktops
$screen-xl-min: 1200px;


// Small devices
@mixin sm {
   @media (min-width: #{$screen-sm-min}) {
       @content;
   }
}

// Medium devices
@mixin md {
   @media (min-width: #{$screen-md-min}) {
       @content;
   }
}

// Large devices
@mixin lg {
   @media (min-width: #{$screen-lg-min}) {
       @content;
   }
}

// Extra large devices
@mixin xl {
   @media (min-width: #{$screen-xl-min}) {
       @content;
   }
}
.border { 
    width: 400px;
    padding: 20px;
    border-top: 10px solid #FFFF00;
    border-bottom:10px solid #FF0000;
    background-image: 
        linear-gradient(#FFFF00, #FF0000),
        linear-gradient(#FFFF00, #FF0000)
    ;
    background-size:10px 100%;
    background-position:0 0, 100% 0;
    background-repeat:no-repeat;
}
.LikeButton button {
  margin: 1rem;
  transition: all 0.5s ease;
  transform: scale(1);
}

.LikeButton button:hover {
  cursor: pointer;
  transform: scale(1.25);
  filter: brightness(120%);
}
.text-gradient {
    background: linear-gradient(94.23deg,#5374fa 12.41%,#fd9179 52.55%,#ff6969 89.95%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicWidth(
        child: Column(
          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'),
            ),
          ],
        ),
      ),
    ),
  );
}
keys, values)) # {'a': 2, 'c': 4, 'b': 3}
 
 
#make a function: def is the keyword for the function:
def to_dictionary(keys, values):
 
 
#return is the keyword that tells program that function has to return value   
return dict(zip(keys, values))
 
  
 
# keys and values are the lists:
 
keys = ["a", "b", "c"]   
 
values = [2, 3, 4]
                                
                                
// models.py
from django.db.models.fields import FloatField

class Product(models.Model):
    title = models.CharField(max_length=225)
    price = models.FloatField()
    discount_percent = FloatField(default=0) # Assigning it a default value of 0 so it doesn't throw a 'NoneType' error when it's null.
  
    @property
    def discount(self):
        if self.discount_percent > 0:
            discounted_price = self.price - self.price * self.discount_percent / 100
            return discounted_price

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
	
	# get_total function has to be updated too to calculate using the correct current price
    @property
    def get_total(self):
        if self.product.discount_percent > 0:
            price_now = self.product.price - self.product.price * self.product.discount_percent / 100
        else:
            price_now = self.product.price

        total = price_now * self.quantity
        return total

// Your template
{% if product.discount_percent %}
                <h4 class="product__price--original">₾{{ product.price|floatformat:2 }}</h4>
                <h4 class="product__price--discounted">₾{{ product.discount|floatformat:2 }}</h4>
                {% else %}  
                <h4>₾{{ product.price|floatformat:2 }}</h4>
                {% endif %}
                
// Here's some Sass too, if you need it
.product__price {
  &--original {
    text-decoration: line-through;
  }
  &--discounted {
    color: green;
  }
}
<html>	
   
   <input id="contact" name="address">
 
 <script>

    document.getElementById("contact").attribute = "phone";
	
    //ALTERNATIVE METHOD TO CHANGE
    document.getElementById("contact").setAttribute('name', 'phone');	

  </script>

</html>
import java.io.*;
import java.util.*;

class GFG 
{
	static int maxCuts(int n, int a, int b, int c)
	{
		if(n == 0) return 0;
		if(n < 0)  return -1;

		int res = Math.max(maxCuts(n-a, a, b, c), 
		          Math.max(maxCuts(n-b, a, b, c), 
		          maxCuts(n-c, a, b, c)));

		if(res == -1)
			return -1;

		return res + 1; 
	}
  
    public static void main(String [] args) 
    {
    	int n = 5, a = 2, b = 1, c = 5;
    	
    	System.out.println(maxCuts(n, a, b, c));
    }
}
git log --all --graph --decorate
$w.onReady(function () {
	$w('#collapsedelement').collapse();
    $w('#closebtn').hide();
});

export function openbtn_click(event) {
	let $item = $w.at(event.context);

	if ($item("#collapsedelement").collapsed) {
		$item("#collapsedelement").expand();
		$item('#openbtn').hide();
		$item('#closebtn').show();

	} else {
		$item("#collapsedelement").collapse();
		$item('#openbtn').show();
		$item('#closebtn').hide();
	}
}

export function closebtn_click(event) {
	let $item = $w.at(event.context);

	if ($item("#collapsedelement").collapsed) {
		$item("#collapsedelement").expand();
		$item('#openbtn').hide();
		$item('#closebtn').show();

	} else {
		$item("#collapsedelement").collapse();
		$item('#openbtn').show();
		$item('#closebtn').hide();
	}
}
import java.util.Stack;

/**
 * Java Program to implement a binary search tree. A binary search tree is a
 * sorted binary tree, where value of a node is greater than or equal to its
 * left the child and less than or equal to its right child.
 * 
 * @author WINDOWS 8
 *
 */
public class BST {

    private static class Node {
        private int data;
        private Node left, right;

        public Node(int value) {
            data = value;
            left = right = null;
        }
    }

    private Node root;

    public BST() {
        root = null;
    }

    public Node getRoot() {
        return root;
    }

    /**
     * Java function to check if binary tree is empty or not
     * Time Complexity of this solution is constant O(1) for
     * best, average and worst case. 
     * 
     * @return true if binary search tree is empty
     */
    public boolean isEmpty() {
        return null == root;
    }

    
    /**
     * Java function to return number of nodes in this binary search tree.
     * Time complexity of this method is O(n)
     * @return size of this binary search tree
     */
    public int size() {
        Node current = root;
        int size = 0;
        Stack<Node> stack = new Stack<Node>();
        while (!stack.isEmpty() || current != null) {
            if (current != null) {
                stack.push(current);
                current = current.left;
            } else {
                size++;
                current = stack.pop();
                current = current.right;
            }
        }
        return size;
    }


    /**
     * Java function to clear the binary search tree.
     * Time complexity of this method is O(1)
     */
    public void clear() {
        root = null;
    }

}
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
public <T> List<Class<? extends T>> findAllMatchingTypes(Class<T> toFind) {
    foundClasses = new ArrayList<Class<?>>();
    List<Class<? extends T>> returnedClasses = new ArrayList<Class<? extends T>>();
    this.toFind = toFind;
    walkClassPath();
    for (Class<?> clazz : foundClasses) {
        returnedClasses.add((Class<? extends T>) clazz);
    }
    return returnedClasses;
}
(function(){
    //
    var $posts = $('#posts li');
    var $search = $('#search');
    var cache = [];

    $posts.each(function(){
        cache.push({
            element: this,
            title: this.title.trim().toLowerCase(),
        });
    });

    function filter(){
        var query = this.value;
        console.log("query is "+query);
        cache.forEach(function(post){
            var index = 0;

            if (query) {
                index = post.title.indexOf(query);

            }
            var results = document.getElementsByClassName('search-results');
            results.innerHTML = "<li>"+cache.title+"</li>";
            post.element.style.display = index === -1 ? 'none' : '';
        });
    }

   if ('oninput' in $search[0]){
        $search.on('input', filter);
    } else {
        $search.on('keyup', filter);
    }

}());
var d = new Date();
var n = d.getFullYear();
const renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );
EXAMPLES
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
                             
                                
                                package com.rizki.mufrizal.belajar.spring.boot.domain

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.core.mapping.Field

/**
 *
 * @Author Rizki Mufrizal <mufrizalrizki@gmail.com>
 * @Web <https://RizkiMufrizal.github.com>
 * @Since 12 January 2017
 * @Time 10:13 PM
 * @Project Belajar-Spring-Boot
 * @Package com.rizki.mufrizal.belajar.spring.boot.domain
 * @File Barang
 *
 */
@Document(collection = "tb_barang")
class Barang implements Serializable {

    @Id
    @Field(value = "id_barang")
    String idBarang

    @Field(value = "nama_barang")
    String namaBarang

    @Field(value = "jenis_barang")
    JenisBarang jenisBarang

    @Field(value = "tanggal_kadaluarsa")
    Date tanggalKadaluarsa

    @Field(value = "harga_satuan_barang")
    BigDecimal hargaSatuanBarang

    @Field(value = "jumlah_barang_tersedia")
    Integer jumlahBarangTersedia

}
                                
amount
	.toFixed(2)
    .toString()
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    
// or

amount
	.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
//Replace the closeSelf() function in iframe page to the following

function closeSelf() {
   parent.window.postMessage("removetheiframe", "*");
}

//and on the parent page, add the following code to listen when the iframe sends a message :

function receiveMessage(event){
   if (event.data=="removetheiframe"){
      var element = document.getElementById('iframe-element');
      element.parentNode.removeChild(element);
   }
}
window.addEventListener("message", receiveMessage, false);
   var Person = mongoose.model('Person', yourSchema);
   // find each person with a name contains 'Ghost'
   Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } },
          function (err, person) {
                 if (err) return handleError(err);
                 console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);

   });
const { useState } = React;

function PageComponent() {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1)
  }

  return (
    <div className="App">
      <ChildComponent onClick={increment} count={count} />         
      <h2>count {count}</h2>
      (count should be updated from child)
    </div>
  );
}

const ChildComponent = ({ onClick, count }) => {
  return (
    <button onClick={onClick}>
       Click me {count}
    </button>
  )
};

ReactDOM.render(<PageComponent />, document.getElementById("root"));
const buff_to_base64 = (buff) => btoa(String.fromCharCode.apply(null, buff));

const base64_to_buf = (b64) =>
  Uint8Array.from(atob(b64), (c) => c.charCodeAt(null));

const enc = new TextEncoder();
const dec = new TextDecoder();

const getPasswordKey = (password) =>
  window.crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, [
    "deriveKey",
  ]);

const deriveKey = (passwordKey, salt, keyUsage) =>
  window.crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: salt,
      iterations: 250000,
      hash: "SHA-256",
    },
    passwordKey,
    {
      name: "AES-GCM",
      length: 256,
    },
    false,
    keyUsage
  );

export async function encrypt(secretData, password) {
  try {
    const salt = window.crypto.getRandomValues(new Uint8Array(16));
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    const passwordKey = await getPasswordKey(password);
    const aesKey = await deriveKey(passwordKey, salt, ["encrypt"]);
    const encryptedContent = await window.crypto.subtle.encrypt(
      {
        name: "AES-GCM",
        iv: iv,
      },
      aesKey,
      enc.encode(secretData)
    );

    const encryptedContentArr = new Uint8Array(encryptedContent);
    let buff = new Uint8Array(
      salt.byteLength + iv.byteLength + encryptedContentArr.byteLength
    );
    buff.set(salt, 0);
    buff.set(iv, salt.byteLength);
    buff.set(encryptedContentArr, salt.byteLength + iv.byteLength);
    const base64Buff = buff_to_base64(buff);
    return base64Buff;
  } catch (e) {
    console.log(`Error - ${e}`);
    return "";
  }
}

export async function decrypt(encryptedData, password) {
  const encryptedDataBuff = base64_to_buf(encryptedData);
  const salt = encryptedDataBuff.slice(0, 16);
  const iv = encryptedDataBuff.slice(16, 16 + 12);
  const data = encryptedDataBuff.slice(16 + 12);
  const passwordKey = await getPasswordKey(password);
  const aesKey = await deriveKey(passwordKey, salt, ["decrypt"]);
  const decryptedContent = await window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: iv,
    },
    aesKey,
    data
  );
  return dec.decode(decryptedContent);
}
let now = new Date();
alert( now ); // показывает текущие дату и время
function my_scripts() {
     if(!is_admin() {
          wp_deregister_script('jquery');
          wp_enqueue_script('jquery', '//code.jquery.com/jquery-latest.min.js');
     }
}
add_action('wp_enqueue_scripts', 'my_scripts');


//Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.

function boolToWord( bool ){
const str = bool === true ? "Yes" : "No"
return str
  }
[
   {
      "mostrar":"in,out",
      "label":"CURSO DE FORMAÇÃO EM TERAPEUTA AYURVEDA",
      "campo":"cursotitulo",
      "tipo":"titulo6",
      "colunas_in":"12",
      "colunas_out":"12"
   },
   {
      "mostrar":"in,out",
      "label":"Nome Completo",
      "campo":"nomecompleto",
      "tipo":"text",
      "colunas_in":"12",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Data de nascimento",
      "campo":"data_nasc",
      "tipo":"data",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"CPF",
      "campo":"nrocpf",
      "tipo":"cpf",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Estado Civil",
      "campo":"estado_civil",
      "tipo":"select_valor",
      "colunas_in":"6",
      "colunas_out":"4",
      "opcoes":[
         "Casado",
         "Solteiro",
         "Separado",
         "Viuvo"
      ],
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Profissão",
      "campo":"profi",
      "tipo":"text",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Email",
      "campo":"email",
      "tipo":"text",
      "colunas_in":"12",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Telefone Celular",
      "campo":"telcelular",
      "tipo":"text",
      "placeholder":"(xx) x xxxx-xxxx",
      "colunas_in":"6",
      "colunas_out":"6",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Telefone Residencial",
      "campo":"telresidencial",
      "tipo":"text",
      "placeholder":"(xx) x xxxx-xxxx",
      "colunas_in":"6",
      "colunas_out":"6"
   },
   {
      "mostrar":"in,out",
      "label":"Endereço",
      "campo":"logradouro",
      "tipo":"text",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"Cidade",
      "campo":"cid",
      "tipo":"text",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"CEP",
      "campo":"cep_user",
      "tipo":"text",
      "colunas_in":"6",
      "colunas_out":"4",
      "requerido":"1"
   },
   {
      "mostrar":"in,out",
      "label":"PAGAMENTO",
      "campo":"pagamento",
      "tipo":"titulo6",
      "colunas_in":"12",
      "colunas_out":"12"
   },
   {
      "mostrar":"in,out",
      "label":"Forma de Pagamento",
      "campo":"forma_pagamento",
      "tipo":"select_valor",
      "colunas_in":"6",
      "colunas_out":"6",
      "requerido":"1",
      "opcoes":[
         "À vista",
         "À prazo",
         "Boleto",
         "Cheque"
      ],
      "conditions":[
         {
            "when":"equal",
            "value":"À prazo",
            "action":{
               "show":[
                  "parcelas"
               ],
               "required":[
                  "parcelas"
               ]
            }
         }
      ]
   },
   {
      "mostrar":"in,out",
      "label":"Em quantas parcelas?",
      "campo":"parcelas",
      "tipo":"number",
      "colunas_in":"12",
      "colunas_out":"12",
      "classe":"hide"
   },
   {
      "mostrar":"in,out",
      "label":"Escola",
      "campo":"escola",
      "tipo":"select_valor",
      "colunas_in":"12",
      "colunas_out":"12",
      "requerido":"1",
      "opcoes":[
         "Semente da Paz",
         "Leveza do Ser",
         "Beija Flor",
         "La vie",
         "Karina Gomes"
      ],
      "aceita_recategorizar":"1"
   },
   {
      "mostrar":"in,out",
      "label":"TERMO DE AUTORIZAÇÃO",
      "campo":"termo",
      "tipo":"titulo6",
      "colunas_in":"12",
      "colunas_out":"12"
   },
   {
      "mostrar":"in,out",
      "campo":"autori",
      "tipo":"texto",
      "valor_padrao":"Eu, autorizo a gravar (minha imagem em vídeo ou fotografia) e veicular minha imagem e depoimentos em qualquer meios de comunicação para fins didáticos, de pesquisa e divulgação de conhecimento científico sem quaisquer ônus e restrições. Fica ainda autorizada, de livre e espontânea vontade, para os mesmos fins, a cessão de direitos da veiculação, não recebendo para tanto qualquer tipo de remuneração. ",
      "colunas_in":"12",
      "colunas_out":"12"
   },
   {
      "mostrar":"in,out",
      "label":"Eu concordo e autorizo",
      "campo":"concordancia",
      "tipo":"checkbox",
      "colunas_in":"12",
      "colunas_out":"12",
      "requerido":"1"
   }
]
val sheetState = rememberModalBottomSheetState(
    initialValue = ModalBottomSheetValue.Hidden,
    confirmStateChange = { it != ModalBottomSheetValue.HalfExpanded }
)
function processSQLFile(fileName) {

  // Extract SQL queries from files. Assumes no ';' in the fileNames
  var queries = fs.readFileSync(fileName).toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' ') // excess white space
    .split(";") // split into all statements
    .map(Function.prototype.call, String.prototype.trim)
    .filter(function(el) {return el.length != 0}); // remove any empty ones

  // Execute each SQL query sequentially
  queries.forEach(function(query) {
    batch.push(function(done) {
      if (query.indexOf("COPY") === 0) { // COPY - needs special treatment
        var regexp = /COPY\ (.*)\ FROM\ (.*)\ DELIMITERS/gmi;
        var matches = regexp.exec(query);
        var table = matches[1];
        var fileName = matches[2];
        var copyString = "COPY " + table + " FROM STDIN DELIMITERS ',' CSV HEADER";
        var stream = client.copyFrom(copyString);
        stream.on('close', function () {
          done();
        });
        var csvFile = __dirname + '/' + fileName;
        var str = fs.readFileSync(csvFile);
        stream.write(str);
        stream.end();
      } else { // Other queries don't need special treatment
        client.query(query, function(result) {
          done();
        });
      }
    });
  });
}
import { MatDialogModule } from "@angular/material";
 Save has now changed to

import { MatDialogModule } from "@angular/material/dialog";

You have to reference the actual module inside the material folder:
v
User Object Cheat Sheet
N

o matter what system you’re working in, it is always critical to be able to identify information about the user who is accessing that system. Being able to identify who the user is, what their groups and/or roles are, and what other attributes their user record has are all important pieces of information that allow you to provide that user with a good experience (without giving them information they don’t need to have or shouldn’t have). ServiceNow gives administrators some pretty simple ways to identify this information in the form of a couple of user objects and corresponding methods. This article describes the functions and methods you can use to get information about the users accessing your system.



GlideSystem User Object

The GlideSystem (gs) user object is designed to be used in any server-side JavaScript (Business rules, UI Actions, System security, etc.). The following table shows how to use this object and its corresponding functions and methods.

Function/Method	Return Value	Usage
gs.getUser()	Returns a reference to the user object for the currently logged-in user.	var userObject = gs.getUser();
gs.getUserByID()	Returns a reference to the user object for the user ID (or sys_id) provided.	var userObject = gs.getUser().getUserByID('employee');
gs.getUserName()	Returns the User ID (user_name) for the currently logged-in user.
e.g. 'employee'	var user_name = gs.getUserName();
gs.getUserDisplayName()	Returns the display value for the currently logged-in user.
e.g. 'Joe Employee'	var userDisplay = gs.getUserDisplayName();
gs.getUserID()	Returns the sys_id string value for the currently logged-in user.	var userID = gs.getUserID();
getFirstName()	Returns the first name of the currently logged-in user.	var firstName = gs.getUser().getFirstName();
getLastName()	Returns the last name of the currently logged-in user.	var lastName = gs.getUser().getLastName();
getEmail()	Returns the email address of the currently logged-in user.	var email = gs.getUser().getEmail();
getDepartmentID()	Returns the department sys_id of the currently logged-in user.	var deptID = gs.getUser().getDepartmentID();
getCompanyID()	Returns the company sys_id of the currently logged-in user.	var companyID = gs.getUser().getCompanyID();
getCompanyRecord()	Returns the company GlideRecord of the currently logged-in user.	var company = gs.getUser().getCompanyRecord();
getLanguage()	Returns the language of the currently logged-in user.	var language = gs.getUser().getLanguage();
getLocation()	Returns the location of the currently logged-in user.	var location = gs.getUser().getLocation();
getDomainID()	Returns the domain sys_id of the currently logged-in user (only used for instances using domain separation).	var domainID = gs.getUser().getDomainID();
getDomainDisplayValue()	Returns the domain display value of the currently logged-in user (only used for instances using domain separation).	var domainName = gs.getUser().getDomainDisplayValue();
getManagerID()	Returns the manager sys_id of the currently logged-in user.	var managerID = gs.getUser().getManagerID();
getMyGroups()	Returns a list of all groups that the currently logged-in user is a member of.	var groups = gs.getUser().getMyGroups();
isMemberOf()	Returns true if the user is a member of the given group, false otherwise.	Takes either a group sys_id or a group name as an argument.

if(gs.getUser().isMemberOf(current.assignment_group)){
//Do something...
}

var isMember = gs.getUser().isMemberOf('Hardware');

To do this for a user that isn't the currently logged-in user...

var user = 'admin';
var group = "Hardware";
if (gs.getUser().getUserByID(user).isMemberOf(group)){
gs.log( gr.user_name + " is a member of " + group);
}

else{
gs.log( gr.user_name + " is NOT a member of " + group);
}
gs.hasRole()	Returns true if the user has the given role, false otherwise.	if(gs.hasRole('itil')){ //Do something... }
gs.hasRole()	Returns true if the user has one of the given roles, false otherwise.	if(gs.hasRole('itil,admin')){
//If user has 'itil' OR 'admin' role then Do something...
}
hasRoles()	Returns true if the user has any roles at all, false if the user has no role (i.e. an ess user).	if(!gs.getUser().hasRoles()){
//User is an ess user...
}
It is also very simple to get user information even if the attribute you want to retrieve is not listed above by using a ‘gs.getUser().getRecord()’ call as shown here…

//This script gets the user's title
gs.getUser().getRecord().getValue('title');


g_user User Object

The g_user object can be used only in UI policies and Client scripts. Contrary to its naming, it is not truly a user object. g_user is actually just a handful of cached user properties that are accessible to client-side JavaScript. This eliminates the need for most GlideRecord queries from the client to get user information (which can incur a fairly significant performance hit if not used judiciously).

g_user Property or Method	Return value
g_user.userName	User name of the current user e.g. employee
g_user.firstName	First name of the current user e.g. Joe
g_user.lastName	Last name of the current user e.g. Employee
g_user.userID	sys_id of the current user e.g. 681ccaf9c0a8016400b98a06818d57c7
g_user.hasRole()	True if the current user has the role specified, false otherwise. ALWAYS returns true if the user has the 'admin' role.

Usage: g_user.hasRole('itil')
g_user.hasRoleExactly()	True if the current user has the exact role specified, false otherwise, regardless of 'admin' role.

Usage: g_user.hasRoleExactly('itil')
g_user.hasRoles()	True if the current user has at least one role specified, false otherwise.

Usage: g_user.hasRoles('itil','admin')
It is often necessary to determine if a user is a member of a given group from the client as well. Although there is no convenience method for determining this from the client, you can get the information by performing a GlideRecord query. Here’s an example…

//Check to see if assigned to is a member of selected group
var grpName = 'YOURGROUPNAMEHERE';
var usrID = g_form.userID; //Get current user ID
var grp = new GlideRecord('sys_user_grmember');
grp.addQuery('group.name', grpName);
grp.addQuery('user', usrID);
grp.query(groupMemberCallback);
   
function groupMemberCallback(grp){
//If user is a member of selected group
    if(grp.next()){
        //Do something
        alert('Is a member');
    }
    else{
        alert('Is not a member');
    }
}
To get any additional information about the currently logged-in user from a client-script or UI policy, you need to use a GlideRecord query. If at all possible, you should use a server-side technique described above since GlideRecord queries can have performance implications when initiated from a client script. For the situations where there’s no way around it, you could use a script similar to the one shown below to query from the client for more information about the currently logged in user.

//This script gets the user's title
var gr = new GlideRecord('sys_user');
gr.get(g_user.userID);
var title = gr.title;
alert(title);


Useful Scripts

There are quite a few documented examples of some common uses of these script methods. These scripts can be found on the ServiceNow wiki.
>>> from enum import Enum
>>> class Build(Enum):
...   debug = 200
...   build = 400
... 

Build['debug']

my_list = [27, 5, 9, 6, 8]

def RemoveValue(myVal):
    if myVal not in my_list:
        raise ValueError("Value must be in the given list")
    else:
        my_list.remove(myVal)
    return my_list

print(RemoveValue(27))
print(RemoveValue(27))
from pandas_profiling import ProfileReport
profile = ProfileReport(df, title="Pandas Profiling Report")
profile.to_file("your_report.html")
import streamlit as st

st.header('''Temperature Conversion App''')

st.write('''Slide to convert value to Fahrenheit''')
value = st.slider('Temperature in Fahrenheit')

st.write(value, '°F is ', (value * 9/5) + 32, '°C')

#Converting temperature to Fahrenheit
st.write('''Slide to convert value to Fahrenheit''')
value = st.slider('Temperature in Celcius')

st.write(value, '° is ', (value - 32) * 5/9, '°C')
new_stocks = {symbol: price * 1.02 for (symbol, price) in stocks.items()}

Code language: Python (python)
library(ggplot2)
library("ggpubr")
theme_set(
  theme_bw() +
    theme(legend.position = "top")
  )
puts ShopifyAPI::Order.find(:all, :params => {:status => 'any', :limit => 250})
import org.apache.spark.sql.functions._

val sc: SparkContext = ...
val sqlContext = new SQLContext(sc)

import sqlContext.implicits._

val input = sc.parallelize(Seq(
  ("a", 5, 7, 9, 12, 13),
  ("b", 6, 4, 3, 20, 17),
  ("c", 4, 9, 4, 6 , 9),
  ("d", 1, 2, 6, 8 , 1)
)).toDF("ID", "var1", "var2", "var3", "var4", "var5")

val columnsToSum = List(col("var1"), col("var2"), col("var3"), col("var4"), col("var5"))

val output = input.withColumn("sums", columnsToSum.reduce(_ + _))

output.show()
{
    // Debugger Tool for Firefox has to be installed: https://github.com/firefox-devtools/vscode-firefox-debug
    // And Remote has to be enabled: https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging/Debugging_Firefox_Desktop#enable_remote_debugging
    "version": "0.2.0",
    "configurations": [
        {
            "type": "firefox",
            "request": "launch",
            "name": "Launch Firefox against localhost",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}",
            "enableCRAWorkaround": true,
            "reAttach": true,
            "reloadOnAttach": true,
            "reloadOnChange": {
                "watch": "${workspaceFolder}/**/*.ts",
                "ignore": "**/node_modules/**"
            }
        }
    ]
}
post_max_size = 750M 
upload_max_filesize = 750M   
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
private Entity RetrieveEntityById(IOrganizationService service, string strEntityLogicalName, Guid guidEntityId)

       {

           Entity RetrievedEntityById= service.Retrieve(strEntityLogicalname, guidEntityId, newColumnSet(true)); //it will retrieve the all attrributes

           return RetrievedEntityById;

       }

How to call?

Entity entity = RetrieveEntityById(service, "account", guidAccountId);
$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});
star

Tue Oct 27 2020 05:31:31 GMT+0000 (Coordinated Universal Time)

@abeerIbrahim #css

star

Fri Feb 26 2021 19:33:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2717127/gradient-borders

@MAI #css

star

Wed Jun 30 2021 08:18:15 GMT+0000 (Coordinated Universal Time)

@hisam #css

star

Fri Sep 03 2021 08:50:14 GMT+0000 (Coordinated Universal Time) https://www.matuzo.at/blog/element-diversity/

@gorlanova #css

star

Fri Apr 08 2022 16:10:51 GMT+0000 (Coordinated Universal Time)

@Mazen #css

star

Tue May 12 2020 11:02:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48893935/how-to-remove-debug-banner-in-flutter-on-android-emulator

@bassel #dart #flutter

star

Mon Mar 08 2021 13:00:55 GMT+0000 (Coordinated Universal Time) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

@Hackerman_max #dart #flutter

star

Mon Nov 01 2021 11:23:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/68015014/flutter-error-filesystemexception-creation-failed-path-storage-emulated-0

@awaisab171 #dart

star

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

@TrickyMind #python #python #lists #dictionary

star

Sun Mar 29 2020 07:06:35 GMT+0000 (Coordinated Universal Time) https://gist.github.com/trantorLiu/5924389

@billion_bill #javascript #nodejs #handlebars #express

star

Sun Feb 06 2022 21:32:20 GMT+0000 (Coordinated Universal Time)

@Uttam #java #gfg #geeksforgeeks #lecture #recursion #rope cutting

star

Wed Nov 17 2021 14:07:48 GMT+0000 (Coordinated Universal Time)

@swina #git

star

Thu Jan 02 2020 19:00:00 GMT+0000 (Coordinated Universal Time)

@mishka #wix #howto

star

Sun Dec 29 2019 20:06:50 GMT+0000 (Coordinated Universal Time) https://javarevisited.blogspot.com/2015/10/how-to-implement-binary-search-tree-in-java-example.html#axzz4wnEtnNB3

@frogblog #java #interviewquestions #search

star

https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array

#java
star

https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map

#java
star

Tue May 11 2021 05:06:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/9991253/finding-all-classes-implementing-a-specific-interface

@anoopsugur #java

star

https://www.amazon.com/JavaScript-JQuery-Interactive-Front-End-Development/dp/1118531647

@mishka #javascript

star

https://www.w3schools.com/jsref/jsref_getfullyear.asp

@mishka #javascript

star

Wed May 06 2020 11:46:54 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/js/s/rename-keys/

@Glowing #javascript

star

Sat May 09 2020 07:01:41 GMT+0000 (Coordinated Universal Time) https://rizkimufrizal.github.io/membuat-restful-web-service-dengan-framework-spring-boot/

@hanatakaruki #javascript

star

Fri May 15 2020 06:24:00 GMT+0000 (Coordinated Universal Time) https://css-tricks.com/snippets/javascript/1024x768-bookmarklet/

@RedQueen #javascript

star

Mon Jun 08 2020 10:26:33 GMT+0000 (Coordinated Universal Time)

@salitha.pathi #javascript

star

Tue May 12 2020 11:23:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21881901/how-do-i-remove-iframe-within-itself-by-using-javascript

@mishka #javascript

star

Wed Jun 10 2020 12:20:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38497650/how-to-find-items-using-regex-in-mongoose/38498075

@mishka #javascript #mongoose #mongodb #mean

star

Wed Oct 06 2021 21:25:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/55726886/react-hook-send-data-from-child-to-parent-component

@richard #javascript

star

Wed Dec 22 2021 03:34:04 GMT+0000 (Coordinated Universal Time) https://explosion-scratch.github.io/blog/0-knowledge-auth/

@Explosion #javascript

star

Fri Nov 24 2023 10:05:35 GMT+0000 (Coordinated Universal Time) https://learn.javascript.ru/date

@jimifi4494 #javascript

star

Sat Nov 25 2023 07:59:24 GMT+0000 (Coordinated Universal Time) https://www.thepixelpixie.com/how-to-properly-enqueue-jquery-in-a-wordpress-site/

@dmsearnbit #javascript

star

Tue Apr 12 2022 13:25:38 GMT+0000 (Coordinated Universal Time)

@Luduwanda #javascriptreact

star

Tue May 18 2021 15:14:20 GMT+0000 (Coordinated Universal Time)

@zlucxie #json #premaom

star

Mon Dec 13 2021 08:42:45 GMT+0000 (Coordinated Universal Time)

@GoodRequest. #kotlin

star

Fri Nov 27 2020 18:42:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/22636388/import-sql-file-in-node-js-and-execute-against-postgresql

@robertjbass #sql #nodejs

star

Tue Dec 15 2020 17:13:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/58594311/angular-material-index-d-ts-is-not-a-module

@dedicatedking #nodejs,angular

star

Fri Dec 11 2020 17:35:23 GMT+0000 (Coordinated Universal Time) https://servicenowguru.com/scripting/user-object-cheat-sheet/

@nhord2007@yahoo.com #servicenow #user #object

star

Sun Aug 30 2020 18:34:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41407414/convert-string-to-enum-in-python

@arielvol #python

star

Sun Mar 28 2021 06:58:45 GMT+0000 (Coordinated Universal Time)

@FlorianC #python

star

Wed Jan 26 2022 02:55:52 GMT+0000 (Coordinated Universal Time)

@jmbenedetto #python

star

Wed Feb 28 2024 07:51:24 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-dictionary-comprehension/

@viperthapa #python

star

Sun Mar 21 2021 10:33:11 GMT+0000 (Coordinated Universal Time) https://www.datanovia.com/en/lessons/combine-multiple-ggplots-into-a-figure/

@ztlee042 #r

star

Mon Jun 22 2020 16:12:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23824715/how-to-retrieve-orders-from-shopify-through-the-shopify-api-gem

@ayazahmadtarar #rb

star

Mon Apr 05 2021 18:00:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/37624699/adding-a-column-of-rowsums-across-a-list-of-columns-in-spark-dataframe

@anoopsugur #scala

star

Thu Sep 02 2021 14:15:48 GMT+0000 (Coordinated Universal Time)

@jolo #setting #vscode

star

Thu Dec 09 2021 20:15:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57110542/how-to-write-a-nvmrc-file-which-automatically-change-node-version

@richard #sh

star

Tue May 26 2020 11:49:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1263680/maximum-execution-time-in-phpmyadmin

@Ali Raza

star

Tue May 26 2020 18:32:44 GMT+0000 (Coordinated Universal Time) https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/157766/simple-c-code-to-retrieve-an-entity-record

@sabih53

star

Thu May 28 2020 15:25:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link

@dyaneld

Save snippets that work with our extensions

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