How to create a Password Generator using HTML5/CSS3/VANILLA JS

This is a simple password generator, follow and code , it’s really simple to do. You can add it and create more functionality to give more control over the strength and length of the passwords.

Source Code : https://github.com/BekBrace/password-generator

Subscribe : https://www.youtube.com/channel/UC7EVSn5inapL20oPSwAwEUg

#html #css #javascript

What is GEEK

Buddha Community

How to create a Password Generator using HTML5/CSS3/VANILLA JS

Create JavaScript Password Generator

If you are a beginner and want to create a JavaScript Password Generator then this tutorial is for you. Here I have shown step-by-step and shared complete information on how to create a password generator using JavaScript

JavaScript Password Generator will help you create the password of your choice. Earlier I showed you how to create JavaScript Random Password Generator. However, this design will give you the option to create a password manually.

This simple password generator will help you create the password you want. There are different options and controls. This will allow you to create the password you need.

JavaScript Password Generator

You need JavaScript enabled to view it to make it. Here I have used HTML CSS and some amount of JavaScript.

First, a box was created on the webpage. In that box, I first created a display where the generated passwords can be seen. 

Then an input box is created where you can control the width of the password. This means that the number of characters you want to create the password can be controlled by this slider.

Then there are the four smaller boxes. This select box created by the checkbox will help you to further customize your password. There is a button at the end of which clicks on which the password is generated and can be seen in the display.

How to create Password Generator using JavaScript

If you want to create this Password Generator JavaScript then you must have a basic idea about HTML, CSS, and javascript. 

But if you just want the source code then follow the part below the article. But if you are a beginner then follow the tutorial below.

This JavaScript Password Generator has a copy button. When you click on the Generate button, the password will be copied automatically.

1. Make a box on the webpage

I first created an area using the following HTML and CSS codes. In this area, you can see all the information of Password Generator with JavaScript.

<div id=”password-generator”>
</div>

The webpage has been designed using the following code. Here the background color of the webpage is blue.

* {
  box-sizing: border-box;
  font-family: sans-serif;
}
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  text-align: center;
  height: 100vh;
  background: #0976d5;
}
webpage has been designed

I have used the background color of this box as white and width: 500px. Box shadows have been used to enhance beauty.

#password-generator {
  padding: 2rem;
  margin: 0 auto;
  width: 500px;
  border-radius: 3px;
  box-shadow: 0 0 2px #1f1f1f;
  border: 3px solid #d5d4ff;
  position: relative;
  background: white;
  white-space: nowrap;
}
Make a box on the webpage

2. Create a password viewing display

Now we have created a display that will help to see the generated passwords. HTML’s input function has been used to create this box. 

Box-shadow has been used to enhance the background white color and beauty of the box. Its box has no specific size. It will determine its own size depending on the amount of padding.

<input value=”Password generator” id=”password-output”>
input {
  border: none;
  background: transparent;
  outline: none;
}
#password-output {
  text-align: center;
  font-size: 2rem;
  margin: 0 auto 1.2rem;
  width: 100%;
  color: rgb(2, 91, 164);
  padding: 5px;
  box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
Create a password viewing display

Create a password viewing display

3. Range slider and display created

Now a range slider has been created in this JavaScript Password Generator. I have used two input boxes here. The first input box to create the slider and the second input box to create the display. 

When you change the value of this range, the value in that display will change. The input boxes are connected to each other using JavaScript.

<div class=”range”>
   <input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
          oninput=”document.getElementById(‘display-password-length’).value=this.value”>
   <input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
          oninput=”document.getElementById(‘password-length’).value=this.value”>
 </div>
#password-generator .range {
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 60px;
  max-width: 70%;
  margin-left: 15%;
  padding: .4rem 1rem .8rem 2.5rem;
  border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
  -webkit-appearance: none;
  appearance: none;
  width: 40%;
  max-width: 100%;
  height: 15px;
  padding: 0px;
  background: #7a7a82;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
  box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
  border-radius: 10px;
  cursor: pointer;
  scroll-behavior: smooth;
  z-index: 1;
}
Range slider and display created

The Range Slider button has been designed using the following codes. Here I am using the background color blue of the button.

.range input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  background: rgb(9, 71, 222);
  cursor: pointer;
  border-radius: 18px;
  transition: 0.5s ease;
}

The size of the display is determined using the CSS below. Font-size: 1.4rem has been used to increase the display’s width: 80px and text size.

body #password-generator .range #display-password-length {
  text-align: center;
  font-size: 1.4rem;
  width: 80px;
  padding-top: 10px;
}

4. Select box to customize the password

The select options have been created using the following codes. Here four inputs and four labels are used. There is a label for each input. 

Those labels will help to understand which select box to select which value. You can customize your password using this select box.

<div class=”flex”>
  <input type=”checkbox” id=”lowercase” checked=”checked”>
  <label for=”lowercase”>a-z</label>
  <input type=”checkbox” id=”uppercase”>
  <label for=”uppercase”>A-Z</label>
  <input type=”checkbox” id=”numbers”>
  <label for=”numbers”>0-9</label>
  <input type=”checkbox” id=”symbols”>
  <label for=”symbols”>!-?</label>
</div>
.flex {
  margin: 1rem 1rem 2rem;
  display: flex;
  justify-content: space-between;
}
.flex input {
  display: none;
}
.flex input:checked + label {
  border: 2px solid rgb(205, 151, 12);
  background: rgb(173, 144, 82);
  filter: brightness(120%);
  transform: scale(1.1);
}
.flex label {
  border: 2px solid #0571bb;
  border-radius: 4px;
  padding: 0.6rem;
  cursor: pointer;
  font-size: 1.3rem;
  text-align: center;
  display: block;
  width: 80px;
  transition: 0.2s ease;
}
Select box to customize the password

5. Button to generate password

Now you need to create a button in Password Generator JavaScript. The password will be generated when the button is clicked. 

Here the button function is used. The button’s background color is blue and the text color is white.

<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
  outline: none;
  background: #0f6cc3;
  color: white;
  border: none;
  padding: 1rem 2rem;
  margin: 0.5rem 0;
  border-radius: 3px;
  box-shadow: 1px 1px 6px 1px #8f8a8a;
  text-transform: uppercase;
  font-size: 1.2rem;
  transition: 0.2s ease;
  cursor: pointer;
}
#password-generator button:hover {
   background: rgb(173, 118, 22);
}
Button to generate password

6. Activate JavaScript Password Generator

I have basically designed this JavaScript Password Generator above. Now it’s time to activate this password generator using JavaScript

JavaScript used here is a bit difficult. To understand these codes you need to have a basic idea about JavaScript.

//The global constant of the display id is set  
 const passwordOutput =  document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
  const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
  const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
  const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
  const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
 const data = [].concat(
      lowercase.checked ? dataLowercase : [],
      uppercase.checked ? dataUppercase : [],
      numbers.checked ? dataNumbers : [],
      symbols.checked ? dataSymbols : []
  );
//The value obtained from the range slider is stored in ‘password Length’
  let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
  let newPassword = ”;
//If you do not select a select box, you will see the following alert message
  if (data.length === 0) {
      passwordOutput.innerHTML = “Générateur de MDP”;
      alert(‘Please check at least one criteria’);
      return;
    }
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
  for (let i = 0; i < passwordLength; i++) {
      newPassword += data[Math.floor(Math.random() * data.length)];
    }
//Arrangements have been made to display the value of the new password in the display
   passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
  passwordOutput.select();
  document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
  generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
  setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
Activate JavaScript Password Generator

Source code of JavaScript Password Generator

There are many users who just want the source code. Below I have given all the source code for them together. If you want to take all the code of this JavaScript Password Generator together then use the section below. 

Here HTML, CSS, and javascript code are together. You copy those codes and add them to your HTML file. If you want previews and tutorials then follow the article above.

Hopefully using the above codes you have learned how to create this password generator using JavaScript. Earlier I shared a tutorial on Random Password Generator

If you want to create a simple password generator then you can follow that tutorial. Below is a button that allows you to download the source code. If there is any problem, you can let me know by commenting.

Original article source at: https://foolishdeveloper.com/

#javascript #password #generator 

Chloe  Butler

Chloe Butler

1667425440

Pdf2gerb: Perl Script Converts PDF Files to Gerber format

pdf2gerb

Perl script converts PDF files to Gerber format

Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.

The general workflow is as follows:

  1. Design the PCB using your favorite CAD or drawing software.
  2. Print the top and bottom copper and top silk screen layers to a PDF file.
  3. Run Pdf2Gerb on the PDFs to create Gerber and Excellon files.
  4. Use a Gerber viewer to double-check the output against the original PCB design.
  5. Make adjustments as needed.
  6. Submit the files to a PCB manufacturer.

Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).

See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.


pdf2gerb_cfg.pm

#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;

use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)


##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file

use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call

#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software.  \nGerber files MAY CONTAIN ERRORS.  Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG

use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC

use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)

#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1); 

#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
    .010, -.001,  #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
    .031, -.014,  #used for vias
    .041, -.020,  #smallest non-filled plated hole
    .051, -.025,
    .056, -.029,  #useful for IC pins
    .070, -.033,
    .075, -.040,  #heavier leads
#    .090, -.043,  #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
    .100, -.046,
    .115, -.052,
    .130, -.061,
    .140, -.067,
    .150, -.079,
    .175, -.088,
    .190, -.093,
    .200, -.100,
    .220, -.110,
    .160, -.125,  #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
    .090, -.040,  #want a .090 pad option, but use dummy hole size
    .065, -.040, #.065 x .065 rect pad
    .035, -.040, #.035 x .065 rect pad
#traces:
    .001,  #too thin for real traces; use only for board outlines
    .006,  #minimum real trace width; mainly used for text
    .008,  #mainly used for mid-sized text, not traces
    .010,  #minimum recommended trace width for low-current signals
    .012,
    .015,  #moderate low-voltage current
    .020,  #heavier trace for power, ground (even if a lighter one is adequate)
    .025,
    .030,  #heavy-current traces; be careful with these ones!
    .040,
    .050,
    .060,
    .080,
    .100,
    .120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);

#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size:   parsed PDF diameter:      error:
#  .014                .016                +.002
#  .020                .02267              +.00267
#  .025                .026                +.001
#  .029                .03167              +.00267
#  .033                .036                +.003
#  .040                .04267              +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
    HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
    RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
    SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
    RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
    TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
    REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};

#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
    CIRCLE_ADJUST_MINX => 0,
    CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
    CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
    CIRCLE_ADJUST_MAXY => 0,
    SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
    WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
    RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};

#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches

#line join/cap styles:
use constant
{
    CAP_NONE => 0, #butt (none); line is exact length
    CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
    CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
    CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
    
#number of elements in each shape type:
use constant
{
    RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
    LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
    CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
    CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
    rect => RECT_SHAPELEN,
    line => LINE_SHAPELEN,
    curve => CURVE_SHAPELEN,
    circle => CIRCLE_SHAPELEN,
);

#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions

# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?

#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes. 
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes

#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches

# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)

# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time

# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const

use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool

my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time

print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load


#############################################################################################
#junk/experiment:

#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html

#my $caller = "pdf2gerb::";

#sub cfg
#{
#    my $proto = shift;
#    my $class = ref($proto) || $proto;
#    my $settings =
#    {
#        $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
#    };
#    bless($settings, $class);
#    return $settings;
#}

#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;

#print STDERR "read cfg file\n";

#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names

#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }

Download Details:

Author: swannman
Source Code: https://github.com/swannman/pdf2gerb

License: GPL-3.0 license

#perl 

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 

创建 JavaScript 密码生成器

如果您是初学者并想创建一个JavaScript 密码生成器,那么本教程适合您。在这里,我逐步展示并分享了有关如何使用 JavaScript 创建密码生成器的完整信息。 

JavaScript 密码生成器将帮助您创建您选择的密码。之前我向您展示了如何创建JavaScript 随机密码生成器。但是,此设计将为您提供手动创建密码的选项。

这个简单的密码生成器将帮助您创建您想要的密码。有不同的选项和控件。这将允许您创建所需的密码。

JavaScript 密码生成器

您需要启用 JavaScript 才能查看它。这里我使用了 HTML CSS 和一些 JavaScript。

首先,在网页上创建了一个框。在那个框中,我首先创建了一个可以看到 生成的密码的显示。

然后创建一个输入框,您可以在其中控制密码的宽度。这意味着您可以通过此滑块控制要创建密码的字符数。

然后是四个较小的盒子。这个由复选框创建的选择框将帮助您进一步自定义您的密码。在其末尾有一个按钮,单击该按钮将生成密码并可以在显示屏上看到。

如何使用 JavaScript 创建密码生成器

如果你想创建这个密码生成器 JavaScript,那么你必须对 HTML、CSS 和 javascript 有基本的了解。 

但如果您只想要源代码,请按照文章下方的部分进行操作。但是,如果您是初学者,请按照下面的教程进行操作。

这个JavaScript 密码生成器有一个复制按钮。当您点击生成按钮时,密码将被自动复制。

1.在网页上做一个框

我首先使用以下 HTML 和 CSS 代码创建了一个区域。在此区域中,您可以看到 Password Generator with JavaScript 的所有信息。

<div id=”password-generator”>
</div>

该网页是使用以下代码设计的。这里网页的背景颜色是蓝色。

* {
  box-sizing: border-box;
  font-family: sans-serif;
}
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  text-align: center;
  height: 100vh;
  background: #0976d5;
}
网页已设计

我使用这个框的背景颜色为白色和宽度:500px。盒子阴影已被用来增强美感。

#password-generator {
  padding: 2rem;
  margin: 0 auto;
  width: 500px;
  border-radius: 3px;
  box-shadow: 0 0 2px #1f1f1f;
  border: 3px solid #d5d4ff;
  position: relative;
  background: white;
  white-space: nowrap;
}
在网页上做一个框

2.创建密码查看展示

现在我们已经创建了一个显示,可以帮助查看生成的密码。HTML 的输入功能已用于创建此框。 

box-shadow 已被用来增强盒子的背景白色和美感。它的盒子没有具体的尺寸。它将根据填充量确定自己的大小。

<input value=”Password generator” id=”password-output”>
input {
  border: none;
  background: transparent;
  outline: none;
}
#password-output {
  text-align: center;
  font-size: 2rem;
  margin: 0 auto 1.2rem;
  width: 100%;
  color: rgb(2, 91, 164);
  padding: 5px;
  box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
创建密码查看显示

创建密码查看显示

3. 创建范围滑块和显示

现在,已在此JavaScript 密码生成器中创建了一个范围滑块。我在这里使用了两个输入框。第一个输入框创建滑块,第二个输入框创建显示。 

当您更改此范围的值时,该显示中的值将更改。输入框使用 JavaScript 相互连接。

<div class=”range”>
   <input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
          oninput=”document.getElementById(‘display-password-length’).value=this.value”>
   <input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
          oninput=”document.getElementById(‘password-length’).value=this.value”>
 </div>
#password-generator .range {
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 60px;
  max-width: 70%;
  margin-left: 15%;
  padding: .4rem 1rem .8rem 2.5rem;
  border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
  -webkit-appearance: none;
  appearance: none;
  width: 40%;
  max-width: 100%;
  height: 15px;
  padding: 0px;
  background: #7a7a82;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
  box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
  border-radius: 10px;
  cursor: pointer;
  scroll-behavior: smooth;
  z-index: 1;
}
已创建范围滑块和显示

Range Slider 按钮是使用以下代码设计的。这里我使用了按钮的背景色蓝色。

.range input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  background: rgb(9, 71, 222);
  cursor: pointer;
  border-radius: 18px;
  transition: 0.5s ease;
}

显示的大小是使用下面的 CSS 确定的。字体大小:1.4rem 已用于增加显示宽度:80px 和文本大小。

body #password-generator .range #display-password-length {
  text-align: center;
  font-size: 1.4rem;
  width: 80px;
  padding-top: 10px;
}

4.选择框自定义密码

选择选项是使用以下代码创建的。这里使用了四个输入和四个标签。每个输入都有一个标签。 

这些标签将有助于理解哪个选择框选择哪个值。您可以使用此选择框自定义您的密码

<div class=”flex”>
  <input type=”checkbox” id=”lowercase” checked=”checked”>
  <label for=”lowercase”>a-z</label>
  <input type=”checkbox” id=”uppercase”>
  <label for=”uppercase”>A-Z</label>
  <input type=”checkbox” id=”numbers”>
  <label for=”numbers”>0-9</label>
  <input type=”checkbox” id=”symbols”>
  <label for=”symbols”>!-?</label>
</div>
.flex {
  margin: 1rem 1rem 2rem;
  display: flex;
  justify-content: space-between;
}
.flex input {
  display: none;
}
.flex input:checked + label {
  border: 2px solid rgb(205, 151, 12);
  background: rgb(173, 144, 82);
  filter: brightness(120%);
  transform: scale(1.1);
}
.flex label {
  border: 2px solid #0571bb;
  border-radius: 4px;
  padding: 0.6rem;
  cursor: pointer;
  font-size: 1.3rem;
  text-align: center;
  display: block;
  width: 80px;
  transition: 0.2s ease;
}
选择框自定义密码

5.生成密码按钮

现在您需要在密码生成器 JavaScript 中创建一个按钮。单击按钮时将生成密码。 

这里使用了按钮功能。按钮的背景颜色为蓝色,文本颜色为白色。

<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
  outline: none;
  background: #0f6cc3;
  color: white;
  border: none;
  padding: 1rem 2rem;
  margin: 0.5rem 0;
  border-radius: 3px;
  box-shadow: 1px 1px 6px 1px #8f8a8a;
  text-transform: uppercase;
  font-size: 1.2rem;
  transition: 0.2s ease;
  cursor: pointer;
}
#password-generator button:hover {
   background: rgb(173, 118, 22);
}
生成密码的按钮

6.激活JavaScript密码生成器

我基本上已经设计了上面的这个JavaScript密码生成器。现在是时候使用 JavaScript激活这个密码生成器了。 

这里使用的 JavaScript 有点难。要理解这些代码,您需要对 JavaScript 有一个基本的了解

//The global constant of the display id is set  
 const passwordOutput =  document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
  const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
  const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
  const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
  const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
 const data = [].concat(
      lowercase.checked ? dataLowercase : [],
      uppercase.checked ? dataUppercase : [],
      numbers.checked ? dataNumbers : [],
      symbols.checked ? dataSymbols : []
  );
//The value obtained from the range slider is stored in ‘password Length’
  let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
  let newPassword = ”;
//If you do not select a select box, you will see the following alert message
  if (data.length === 0) {
      passwordOutput.innerHTML = “Générateur de MDP”;
      alert(‘Please check at least one criteria’);
      return;
    }
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
  for (let i = 0; i < passwordLength; i++) {
      newPassword += data[Math.floor(Math.random() * data.length)];
    }
//Arrangements have been made to display the value of the new password in the display
   passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
  passwordOutput.select();
  document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
  generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
  setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
激活 JavaScript 密码生成器

JavaScript 密码生成器的源代码

有很多用户只想要源代码。下面我把它们的所有源码都一并给出了。如果您想将此 JavaScript密码生成器的所有代码放在一起,请使用下面的部分。 

这里 HTML、CSS 和 javascript 代码在一起。您复制这些代码并将它们添加到您的 HTML 文件中。如果您想要预览和教程,请按照上面的文章进行操作。

希望通过上面的代码,您已经了解了如何使用 JavaScript 创建此密码生成器。早些时候我分享了一个关于随机密码生成器的教程。 

如果您想创建一个简单的密码生成器,那么您可以按照该教程进行操作。下面是一个允许您下载源代码的按钮。如果有任何问题,您可以通过评论让我知道。

文章原文出处:https: //foolishdeveloper.com/

#javascript #password #generator 

Создать генератор паролей JavaScript

Если вы новичок и хотите создать генератор паролей JavaScript , то это руководство для вас. Здесь я пошагово показал и поделился полной информацией о том, как создать генератор паролей с помощью JavaScript

Генератор паролей JavaScript поможет вам создать пароль по вашему выбору. Ранее я показал вам, как создать генератор случайных паролей JavaScript . Однако этот дизайн даст вам возможность создать пароль вручную.

Этот простой генератор паролей поможет вам создать пароль, который вы хотите. Есть разные опции и элементы управления. Это позволит вам создать пароль, который вам нужен.

Генератор паролей JavaScript

У вас должен быть включен JavaScript, чтобы просмотреть его, чтобы сделать это. Здесь я использовал HTML CSS и немного JavaScript.

Сначала на веб-странице был создан ящик. В этом поле я сначала создал дисплей, на котором можно увидеть  сгенерированные пароли .

Затем создается поле ввода, в котором вы можете контролировать ширину пароля. Это означает, что количество символов, которые вы хотите создать в пароле, можно контролировать с помощью этого ползунка.

Затем идут четыре меньших коробки. Это поле выбора, созданное флажком, поможет вам дополнительно настроить свой пароль. В конце есть кнопка, при нажатии на которую генерируется пароль, который можно увидеть на дисплее.

Как создать генератор паролей с помощью JavaScript

Если вы хотите создать этот JavaScript-генератор паролей , у вас должно быть базовое представление о HTML, CSS и javascript. 

Но если вам просто нужен исходный код, следуйте инструкциям ниже. Но если вы новичок, следуйте инструкциям ниже.

Этот генератор паролей JavaScript имеет кнопку копирования. При нажатии на кнопку «Создать» пароль будет скопирован автоматически.

1. Сделайте поле на веб-странице

Сначала я создал область, используя следующие коды HTML и CSS. В этой области вы можете увидеть всю информацию о генераторе паролей с JavaScript.

<div id=”password-generator”>
</div>

Веб-страница была разработана с использованием следующего кода. Здесь цвет фона веб-страницы синий.

* {
  box-sizing: border-box;
  font-family: sans-serif;
}
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  text-align: center;
  height: 100vh;
  background: #0976d5;
}
веб-страница была разработана

Я использовал цвет фона этого поля как белый и ширину: 500 пикселей. Коробчатые тени использовались для усиления красоты.

#password-generator {
  padding: 2rem;
  margin: 0 auto;
  width: 500px;
  border-radius: 3px;
  box-shadow: 0 0 2px #1f1f1f;
  border: 3px solid #d5d4ff;
  position: relative;
  background: white;
  white-space: nowrap;
}
Сделать коробку на веб-странице

2. Создайте экран просмотра пароля

Теперь мы создали дисплей, который поможет увидеть сгенерированные пароли. Для создания этого поля использовалась функция ввода HTML. 

Box-shadow был использован для улучшения белого цвета фона и красоты блока. Его коробка не имеет определенного размера. Он сам определит свой размер в зависимости от количества отступов.

<input value=”Password generator” id=”password-output”>
input {
  border: none;
  background: transparent;
  outline: none;
}
#password-output {
  text-align: center;
  font-size: 2rem;
  margin: 0 auto 1.2rem;
  width: 100%;
  color: rgb(2, 91, 164);
  padding: 5px;
  box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
Создайте экран просмотра пароля

Создайте экран просмотра пароля

3. Ползунок диапазона и отображение созданы

Теперь в этом генераторе паролей JavaScript создан ползунок диапазона . Здесь я использовал два поля ввода. Первое поле ввода для создания ползунка и второе поле ввода для создания дисплея. 

Когда вы измените значение этого диапазона, значение на этом дисплее изменится. Поля ввода связаны друг с другом с помощью JavaScript.

<div class=”range”>
   <input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
          oninput=”document.getElementById(‘display-password-length’).value=this.value”>
   <input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
          oninput=”document.getElementById(‘password-length’).value=this.value”>
 </div>
#password-generator .range {
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 60px;
  max-width: 70%;
  margin-left: 15%;
  padding: .4rem 1rem .8rem 2.5rem;
  border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
  -webkit-appearance: none;
  appearance: none;
  width: 40%;
  max-width: 100%;
  height: 15px;
  padding: 0px;
  background: #7a7a82;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
  box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
  border-radius: 10px;
  cursor: pointer;
  scroll-behavior: smooth;
  z-index: 1;
}
Ползунок диапазона и отображение созданы

Кнопка Range Slider была разработана с использованием следующих кодов. Здесь я использую синий цвет фона кнопки.

.range input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  background: rgb(9, 71, 222);
  cursor: pointer;
  border-radius: 18px;
  transition: 0.5s ease;
}

Размер дисплея определяется с помощью приведенного ниже CSS. Размер шрифта: 1.4rem был использован для увеличения ширины экрана: 80 пикселей и размера текста.

body #password-generator .range #display-password-length {
  text-align: center;
  font-size: 1.4rem;
  width: 80px;
  padding-top: 10px;
}

4. Установите флажок, чтобы настроить пароль

Опции выбора были созданы с использованием следующих кодов. Здесь используются четыре входа и четыре метки. Для каждого входа есть метка. 

Эти метки помогут понять, в каком поле выбора выбрать какое значение. Вы можете настроить свой пароль , используя это поле выбора.

<div class=”flex”>
  <input type=”checkbox” id=”lowercase” checked=”checked”>
  <label for=”lowercase”>a-z</label>
  <input type=”checkbox” id=”uppercase”>
  <label for=”uppercase”>A-Z</label>
  <input type=”checkbox” id=”numbers”>
  <label for=”numbers”>0-9</label>
  <input type=”checkbox” id=”symbols”>
  <label for=”symbols”>!-?</label>
</div>
.flex {
  margin: 1rem 1rem 2rem;
  display: flex;
  justify-content: space-between;
}
.flex input {
  display: none;
}
.flex input:checked + label {
  border: 2px solid rgb(205, 151, 12);
  background: rgb(173, 144, 82);
  filter: brightness(120%);
  transform: scale(1.1);
}
.flex label {
  border: 2px solid #0571bb;
  border-radius: 4px;
  padding: 0.6rem;
  cursor: pointer;
  font-size: 1.3rem;
  text-align: center;
  display: block;
  width: 80px;
  transition: 0.2s ease;
}
Установите флажок, чтобы настроить пароль

5. Кнопка для генерации пароля

Теперь вам нужно создать кнопку в генераторе паролей JavaScript. Пароль будет сгенерирован при нажатии на кнопку. 

Здесь используется функция кнопки. Цвет фона кнопки — синий, а цвет текста — белый.

<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
  outline: none;
  background: #0f6cc3;
  color: white;
  border: none;
  padding: 1rem 2rem;
  margin: 0.5rem 0;
  border-radius: 3px;
  box-shadow: 1px 1px 6px 1px #8f8a8a;
  text-transform: uppercase;
  font-size: 1.2rem;
  transition: 0.2s ease;
  cursor: pointer;
}
#password-generator button:hover {
   background: rgb(173, 118, 22);
}
Кнопка для генерации пароля

6. Активируйте генератор паролей JavaScript

Я в основном разработал этот генератор паролей JavaScript выше. Теперь пришло время активировать этот генератор паролей с помощью JavaScript

Используемый здесь JavaScript немного сложен. Чтобы понять эти коды, вам нужно иметь базовое представление о JavaScript .

//The global constant of the display id is set  
 const passwordOutput =  document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
  const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
  const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
  const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
  const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
 const data = [].concat(
      lowercase.checked ? dataLowercase : [],
      uppercase.checked ? dataUppercase : [],
      numbers.checked ? dataNumbers : [],
      symbols.checked ? dataSymbols : []
  );
//The value obtained from the range slider is stored in ‘password Length’
  let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
  let newPassword = ”;
//If you do not select a select box, you will see the following alert message
  if (data.length === 0) {
      passwordOutput.innerHTML = “Générateur de MDP”;
      alert(‘Please check at least one criteria’);
      return;
    }
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
  for (let i = 0; i < passwordLength; i++) {
      newPassword += data[Math.floor(Math.random() * data.length)];
    }
//Arrangements have been made to display the value of the new password in the display
   passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
  passwordOutput.select();
  document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
  generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
  setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
Активировать генератор паролей JavaScript

Исходный код генератора паролей JavaScript

Есть много пользователей, которые просто хотят исходный код. Ниже я привел весь исходный код для них вместе. Если вы хотите собрать весь код этого генератора паролей JavaScript вместе, воспользуйтесь разделом ниже. 

Здесь HTML, CSS и код javascript объединены. Вы копируете эти коды и добавляете их в свой HTML-файл. Если вам нужны предварительные просмотры и учебные пособия, следуйте статье выше.

Надеюсь, используя приведенные выше коды, вы научились создавать этот генератор паролей с помощью JavaScript. Ранее я поделился туториалом по генератору случайных паролей

Если вы хотите создать простой генератор паролей , вы можете следовать этому руководству. Ниже находится кнопка, позволяющая загрузить исходный код. Если есть какие-либо проблемы, вы можете сообщить мне, комментируя.

Оригинальный источник статьи: https://foolishdeveloper.com/

#javascript #password #generator