Jonah Lawrence

Jonah Lawrence

1605668508

How to Create Custom Snippets for Any Language in VS Code

One of the most important things for coding productively is having easy access to your code snippets.

Visual Studio Code and Emmet let you make snippets that write large blocks of code with tiny shortcuts.

In this tutorial, I will show you how to create custom code snippets for HTML and CSS using Emmet and also for all types of languages and files using VS Code User Snippets. You can create abbreviations for code in all of your favorite languages including JavaScript, React, PHP, Python, Markdown, and others.

You will learn how to create custom Emmet Abbreviations to type HTML structures and CSS properties faster, boilerplates for your favorite languages, function snippets with labeled and unlabeled tabstops, and how to use VS Code’s variables in your snippets.

Watch: https://youtu.be/gU7b5Vgnalw

📺 In this video:
0:00 - Intro
0:49 - Emmet Snippets
6:19 - VS Code User Snippets
13:30 - Snippet Variables
18:20 - Conclusion

I will be using Windows 10 with Visual Studio Code text editor (http://bit.ly/get-vscode) and Brave Browser (https://bit.ly/get-brave-browser). I use Brave Browser because it’s just like Chrome but it removes ads and trackers so you can browse privately and ad-free.

⚡ Learn more about Emmet Abbreviations:
https://youtu.be/5ecM9n7A_pY

🖥 More Web Development tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFFAErr_ZdK2FV7sklMm2K0J

👨‍💻 More VS Code Tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFGfI5CTIuhKgTLcWY4m1ZaO

💻 More tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFHTUP3vzq4UfQ76ScBnOi-9

❤ Subscribe: http://bit.ly/SubscribeDPT

#tutorial #vscode #vs-code #snippets #productivity #customization

What is GEEK

Buddha Community

How to Create Custom Snippets for Any Language in VS Code

Sam Elias

1605671321

✨ Amazing! Thanks so much!

Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Jonah Lawrence

Jonah Lawrence

1605668508

How to Create Custom Snippets for Any Language in VS Code

One of the most important things for coding productively is having easy access to your code snippets.

Visual Studio Code and Emmet let you make snippets that write large blocks of code with tiny shortcuts.

In this tutorial, I will show you how to create custom code snippets for HTML and CSS using Emmet and also for all types of languages and files using VS Code User Snippets. You can create abbreviations for code in all of your favorite languages including JavaScript, React, PHP, Python, Markdown, and others.

You will learn how to create custom Emmet Abbreviations to type HTML structures and CSS properties faster, boilerplates for your favorite languages, function snippets with labeled and unlabeled tabstops, and how to use VS Code’s variables in your snippets.

Watch: https://youtu.be/gU7b5Vgnalw

📺 In this video:
0:00 - Intro
0:49 - Emmet Snippets
6:19 - VS Code User Snippets
13:30 - Snippet Variables
18:20 - Conclusion

I will be using Windows 10 with Visual Studio Code text editor (http://bit.ly/get-vscode) and Brave Browser (https://bit.ly/get-brave-browser). I use Brave Browser because it’s just like Chrome but it removes ads and trackers so you can browse privately and ad-free.

⚡ Learn more about Emmet Abbreviations:
https://youtu.be/5ecM9n7A_pY

🖥 More Web Development tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFFAErr_ZdK2FV7sklMm2K0J

👨‍💻 More VS Code Tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFGfI5CTIuhKgTLcWY4m1ZaO

💻 More tutorials
https://www.youtube.com/playlist?list=PL9YUC9AZJGFHTUP3vzq4UfQ76ScBnOi-9

❤ Subscribe: http://bit.ly/SubscribeDPT

#tutorial #vscode #vs-code #snippets #productivity #customization

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Adam Jaco

Adam Jaco

1605010906

How to Create Custom Emmet Snippets in VS Code

Hello, my friends and fellow developers, in this video I have talked about a new feature in VS Code. That lets you create snippets for emmet, which is very helpful!

Let me know in the comments below if you want more VS Code videos or any other videos. And like the video, if you like it.

🔴 Subscribe here: https://bit.ly/2K5Ydaf

Github: https://github.com/max-programming/

#vs code #coding #programming

Jonah Lawrence

Jonah Lawrence

1605783262

Full Guide to Custom Snippets in VS Code

If you prefer to watch a video instead, click here.

The problem

I’ve been coding for quite a while now and one thing I’ve noticed is that I use the same code a lot. Whether it be a function using CURL to fetch url contents, CSS properties to apply material box-shadows, or simply create EventListeners in JavaScript. Usually this means I end up wasting time doing it again, or in some cases I look through my old projects to copy-paste the code I’ve written. I’ve come up with a few solutions to this problem such as using GitHub Gists, but VS Code Snippets is by far the best.

The solution

Visual Studio Code and Emmet let you make snippets that write large blocks of code with tiny shortcuts. You can access entire functions you’ve written with just a couple key presses.

Overview

In this tutorial, I will show you how to create custom code snippets for HTML and CSS using Emmet and also for all types of languages and files using VS Code User Snippets. You can create abbreviations for code in all of your favorite languages including JavaScript, React, PHP, Python, Markdown, and others.

You will learn how to create custom Emmet Abbreviations to type HTML structures and CSS properties faster, boilerplates for your favorite languages, function snippets with labeled and unlabeled tabstops, and how to use VS Code’s variables in your snippets.

Video tutorial

https://www.youtube.com/watch?v=gU7b5Vgnalw

Part 1: Emmet Abbreviations

If you don’t yet know, Emmet is an amazing tool that is built into VS Code that allows you to type complex HTML structures quickly and type CSS properties with abbreviations. You can learn more about it here.

Now that you know about Emmet Abbreviations, here’s how you can create your own abbreviations for HTML structures and CSS properties!

Create a snippets file

Find a place on your computer to store your snippets. I chose C:/Users/jonah/emmet/, but you can pick any folder you like.

Create a new JSON file and call it snippets.json.

Add the path to your settings

Open your user settings. You can do this by pressing F1 and searching for the command Preferences: Open Settings (JSON).

Add the emmet.extensionsPath

For me, this looks like:

{
   ...
   "emmet.extensionsPath": "C:\\Users\\jonah\\emmet",
}

Add your snippets

Use this template in your snippets.json to add abbreviations.

{
  "html": {
    "snippets": {
      // html snippets here
    }
  },
  "css": {
    "snippets": {
      // css snippets here
    }
  }
}

Here’s an example of snippets I have set up:

Symbols such as {$1} are tabstops and ${1:1px} is an example of a tabstop with a default value.

Watch how these work in the video.

{
  "html": {
    "snippets": {
      "ull": "ul>li.item${${1:Item $}}*3",
      "hsf": "header+section+footer",
      "gfont": "link[rel=preconnect][href=\"https://fonts.gstatic.com\"]+link[href=\"https://fonts.googleapis.com/css2?family=${1:Open+Sans}&display=swap\"]",
      "lbi": "label>input[class]",
      "lbc": "label>input:c[class]+{$1}"
    }
  },
  "css": {
    "snippets": {
      "bn": "border: none",
      "on": "outline: none",
      "bsd": "border: ${1:1px} solid ${2:red}",
      "cw": "color: white",
      "cb": "color: black",
      "tra": "transition: ${1:all} ${2:0.3s} ${3:cubic-bezier(0.25, 0.8, 0.25, 1)}",
      "teo": "transition: ${1:all} ${2:0.2s} ease-out",
      "tei": "transition: ${1:all} ${2:0.2s} ease-in",
      "fww": "flex-wrap: wrap",
      "cp": "cursor: pointer",
      "tt": "transform: translate(${1:0px}, ${2:0px})",
      "ttx": "transform: translateX(${1:0px})",
      "tty": "transform: translateY(${1:0px})",
      "tr": "transform: rotate(${1:90deg})",
      "pen": "pointer-events: none",
      "fdc": "flex-direction: column",
      "fdcr": "flex-direction: column-reverse",
      "fdr": "flex-direction: row",
      "fdrr": "flex-direction: row-reverse"
    }
  }
}

Part 2: VS Code User Snippets

Select User Snippets under File > Preferences (Code > Preferences on macOS).

Select the language you want to create snippets for or select “New Global Snippets file” to create snippets for all languages.

Each snippet is defined under a snippet name and has a prefix, body and description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted.

Placeholders: $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the same ids are connected.

Here is an example of my javascript.json snippets file:

// javascript.json

{
	"Document Query Selector": {
		"prefix": "dqs",
		"body": [
			"document.querySelector(\"$1\")"
		]
	},
	"Document Query Selector All": {
		"prefix": "dqsa",
		"body": [
			"document.querySelectorAll(\"$1\")"
		]
	},
	"Add Event Listener": {
		"prefix": "ael",
		"body": [
			"addEventListener(${1:\"click\"}, $2 , false);"
		]
	},
	"Add Event Listener Function": {
		"prefix": "aelf",
		"body": [
			"addEventListener(${1:\"click\"}, function () {",
			"\t$2",
			"} , false);"
		]
	},
}

You can also use snippets for boilerplates or awesome CSS shadows:

// css.json

{
	"CSS Boilerplate": {
		"prefix": "!",
		"body": [
			"html {",
			"\t-webkit-box-sizing: border-box;",
			"\t-moz-box-sizing: border-box;",
			"\tbox-sizing: border-box;",
			"}",
			"",
			"*,",
			"*:before,",
			"*:after {",
			"\t-webkit-box-sizing: inherit;",
			"\t-moz-box-sizing: inherit;",
			"\tbox-sizing: inherit;",
			"}",
		]
	},
	"Shadow Depth 1": {
		"prefix": "shadow1",
		"body": [
			"box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);"
		]
	},
	"Shadow Depth 2": {
		"prefix": "shadow2",
		"body": [
			"box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);"
		]
	},
	"Shadow Depth 3": {
		"prefix": "shadow3",
		"body": [
			"box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);"
		]
	},
	"Shadow Depth 4": {
		"prefix": "shadow4",
		"body": [
			"box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);"
		]
	},
	"Shadow Depth 5": {
		"prefix": "shadow5",
		"body": [
			"box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);"
		]
	}
}

Variables

VS Code also has variables you can use in your snippets.

  • TM_SELECTED_TEXT - Currently selected text

  • TM_CURRENT_LINE - Current line contents

  • TM_CURRENT_WORD - Word under the cursor

  • TM_LINE_INDEX - Zero-index based line number

  • TM_LINE_NUMBER - One-index based line number

  • TM_FILENAME - Filename of the current document

  • TM_FILENAME_BASE - Filename without extensions

  • TM_DIRECTORY - Directory of the current document

  • TM_FILEPATH - Full file path of the current document

  • CLIPBOARD - The contents of your clipboard

  • WORKSPACE_NAME - The name of the opened workspace or folder

  • CURRENT_YEAR - Current year

  • CURRENT_YEAR_SHORT - Last two digits of current year

  • CURRENT_MONTH - Month as two digits (ex. ‘03’)

  • CURRENT_MONTH_NAME - Full name of the month (ex. ‘March’)

  • CURRENT_MONTH_NAME_SHORT - 3-letter abbreviated month name (ex. ‘Mar’)

  • CURRENT_DATE - Day of the month

  • CURRENT_DAY_NAME - Name of day (example ‘Monday’)

  • CURRENT_DAY_NAME_SHORT - Short name of the day (example ‘Mon’)

  • CURRENT_HOUR - Current hour in 24-hour clock format

  • CURRENT_MINUTE - Current minute

  • CURRENT_SECOND - Current second

  • CURRENT_SECONDS_UNIX - Number of seconds since the Unix epoch

  • BLOCK_COMMENT_START - Example: <!-- in HTML, /* in JavaScript, PHP, etc.

  • BLOCK_COMMENT_END - Example: --> in HTML, */ in JavaScript, PHP, etc.

  • LINE_COMMENT - Example: // in JavaScript, PHP, etc.

Block comment example:

The following in global.code-snippets will insert a block comment in any language. It will insert <!-- | --> in HTML and /* | */ in JavaScript, PHP, etc. when you type cc. The $1 will place the cursor in the center when you press tab.

{
	"Block Comment": {
		"prefix": "cc",
		"body": [
			"$BLOCK_COMMENT_START $1 $BLOCK_COMMENT_END"
		]
	}
}

Date and time example:

The following in will insert the current date as YYYY-MM-DD. You can write the date in many different formats using a combination of variables from above.

{
	"Date": {
		"prefix": "date",
		"body": [
			"$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE"
		]
	}
}

Conclusion

Code snippets are a great way to type code faster and more productively. There is a great feeling to be able to access the code you want in less than a second. No more need to search through your old files to get the things you need!

I hope you learned something!

If you want to learn more coding tricks, subscribe to my channel!

Thanks for reading / watching!

#productivity #vscode #coding #programming #snippets #customization