Trainee Web Developer here! I have created a password generator for a homework challenge - user can select password length and whether password contains numbers, special characters, upper or lower cased characters. I can generate a password but although user can select these options, the generated password doesn't always contain what they want or don't want.
I think that I may need to specify something else in the if statement but although I've played around with it, I can't see what I'm missing. I'd appreciate any pointers in the right direction please :)
// Get references to the #generate element
var generateBtn = document.querySelector('#generate');
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector('#password');
passwordText.value = password;
};
// Add event listener to generate button
generateBtn.addEventListener('click', writePassword);
// Array of special characters to be included in password
var specialCharacters = ["!\"#$%&'()*+,-./:;<=>?#[\]^_`{|}~"];
// Array of numeric characters to be included in password
var numericCharacters = ["0123456789"];
// Array of lowercase characters to be included in password
var lowerCasedCharacters = ["abcdefghijklmnopqrstuvwxyz"];
// // Array of uppercase characters to be included in password
var upperCasedCharacters = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
var chosenChars = "";
//Function that will eventually return the generated password
function generatePassword() {
var result = "";
//Prompt user for password length
var userChoice = prompt("How many characters would you like your password to contain (10-64)?");
if (userChoice < 10 || userChoice > 64) {
alert("Your password must contain between 10 and 64 characters. Please try again.")
return generatePassword()
}
//Prompt user for password options
var lower = confirm("Click OK to confirm if you would like to include lowercase letters.");
var upper = confirm("Click OK to confirm if you would like to include uppercase letters.");
var numChar = confirm("Click OK to confirm if you would like to include numeric characters.");
var specChar = confirm("Click OK to confirm if you would like to include special characters.");
//Prompts user to ensure they choose at least one character type
if(!lower && !upper && !numChar && !specChar) {
alert("Please choose at least one character type.")
return generatePassword()
}
//When user clicks ok, their choice will be saved in chosenChars variable
if (lower === true) {
chosenChars += lowerCasedCharacters
}
if (upper === true) {
chosenChars += upperCasedCharacters
}
if (numChar === true) {
chosenChars += numericCharacters
}
if (specChar === true) {
chosenChars += specialCharacters
}
//Takes result from chosenChars and selects at random based on user's choice of length
for (var i = 0; i < userChoice; i++) {
result +=chosenChars.charAt(Math.floor(Math.random() * chosenChars.length));
}
return result;
}
pa
Related
this is the problem
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
myCode
class Solution {
fun isPalindrome(s:String):Boolean {
var s1 = s.toLowerCase()
var myStringBuilder = StringBuilder()
var n = s1.length-1
var n1=myStringBuilder.length
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
for( i in 0 .. (n1/2)-1){
if(myStringBuilder[i] != myStringBuilder[n1-i-1]){
return false
}
}
return true
}
}
the first case passed
but this is not passed as per the result Input: s = "race a car result true expected is false
You're initialising n1 too early:
// create an -empty- StringBuilder
var myStringBuilder = StringBuilder()
...
// since it's empty, n1 == 0
var n1=myStringBuilder.length
You're setting it to the length of the StringBuilder contents before you've actually put anything in it. This is a simple value you're setting, it's not a reference to the length getter that will give the current value when you access it. You set it once and that's its value forever.
So your last loop, the one that checks if it's a palindrome or not, never actually runs:
// since n1 is 0, this is for (i in 0..0)
for( i in 0 .. (n1/2)-1){
You can fix it by initialising n1 when you've finished adding your content to the StringBuilder, so you can get its final length:
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
// StringBuilder is complete, grab its final length
var n1 = myStringBuilder.length
// now you can use it
for (i in 0..(n1/2)-1) {
Just fyi, there's also an until operator that works like .. except it doesn't include the last value of the range. So you can write
for (i in 0 until (n1/2))
if you want!
You can use this simple solution.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
for (i in 0..str.length/2 ){
if (str[i]!=str[str.length-i-1])
return false
}
return true
}
Edit:
By the #cactustictacs comment, you can do this in much more simple way.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
return str == str.reversed()
}
I'm trying to write a program for a log in system I coded. Basically the user enters a username and password to register and then can login. What I'm trying to do is to check the password for a set of conditions. Those are things like this password has to include more than 8 characters, has to include a capital, has to include a number, etc... . But I don't know how to do it. (I'm relatively new to c++, I only know the basics, and I am using Visual Studio 2022 Community) Thanks <3
more than 8 characters, has to include a capital, has to include a number
I’m assuming you have stored the password in a string, here are some examples:
using namespace std;
string input = “passWo1d!”;
int i, len = input.length();
bool long = false;
If (n > 8) { long = true; }
bool u = false, n = false;
bool l = false, s = false;
string c = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (i = 0; i < len; i++) {
if (isupper(input[i])) { u = true; }
if (isdigit(input[i])) { n = true; }
if (islower(input[i])) { l = true; }
size_t stmp = input.find_first_not_of(c);
if (stmp != string::npos) { s = true; }
}
can someone show me how to query an array of strings with realm in react-native?
assume i have an array like the following:
const preferences = ["automatic","suv","blue",eco]
What I want is to get realm results where ALL strings in the attribute "specifications" of Cars is in "preferences".
E.g.: If an instance of Cars.specifications contains ["automatic","suv"]
a result should be returned.
But if an instance of Cars.specifications contained ["automatic,"suv","green"] this instance shouldn't be returned.
The length of preferences can vary.
Thank you very much.
Update:
What i tried is the following:
const query = realm.objects("Cars").filtered('specifications = preferences[0] OR specifications = preferences[1]')
As you see it is an OR operator which is surely wrong and it is hardcoded. Looping with realm really confuses me.
This code will work!
const collection = realm.objects('Cars');
const preferences = ["automatic","suv","blue","eco"];
let queryString = 'ANY ';
for (let i = 0; i < preferences.length; i++) {
if (i === 0) {
queryString += `specifications CONTAINS '${preferences[i]}'`;
}
if (i !== 0 && i + 1 <= preferences.length) {
queryString += ` OR specifications CONTAINS '${preferences[i]}'`;
}
}
const matchedResult = collection.filtered(queryString);
example of function to test if a word is inside an array of word
function inArray(word, array) {
var lgth = array.length;
word = word.toLowerCase();
for (var i = 0; i < lgth; i++) {
array[i] = (array[i]).toLowerCase();
if (array[i] == word) return true;
}
return false;
}
const preferences = ["automatic","suv","blue","eco"];
const specifications = ["automatic","suv"] ;
const specifications2 = ["automatic","suv", "boat"] ;
function test(spec,pref){
for (var i in spec){
if(!inArray(spec[i],pref)){
return false ;
}
}
return true;
}
console.log(test(specifications,preferences));
console.log(test(specifications2,preferences));
https://jsfiddle.net/y1dz2gvu/
I have the following code where the user is prompted to enter his username and password in a form. The username and password are checked with the database and if correct the user is logged in. However this code can be easily SQL injected for example by typing:
UserName = 'x' and UserPwd = 'x' or 'x'
Can someone help me to modify the code to prevent SQL injection. Here is the code:
<%#LANGUAGE=Jscript%>
<%
// ----- GLOBALS DECLARATIONS ----------------------------------------------------------------------------
var CKEDir = "ckeditor/";
var DB = Server.MapPath("DB/CMS.MDB");
// ----- GENERAL PURPOSE FUNCTIONS -----------------------------------------------------------------------
// Uses regular expressions to change all single quotes in a string to the HTML
// entity ' and replaces all carriage return and newline characters to spaces.
// This ensures that the string can be incorporated in a SQL statement.
function cleanString(s) {
s = s.replace(/'/g, "'"); // SO syntax fix '
s = s.replace(/[\r\n]/g,' ');
return s;
}
// ----- DATABASE FUNCTIONS ------------------------------------------------------------------------------
// Creates a connection to the database named in the parameter,
function getDBConnection() {
var DBCon = Server.CreateObject("ADODB.Connection");
var DBasePath = DB;
var ConStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + DBasePath + ";Persist Security Info=False";
DBCon.Open(ConStr,"","");
return DBCon;
}
// Increments counter for current page (as identified by global variable PageID) in
// table Counters, and returns a string indicating number of times page was accessed.
function getAccess() {
var msg = '';
if (PageID) {
var DBConn = getDBConnection();
var Td = new Date();
var SQL = "SELECT * FROM Counters WHERE PageID=" + PageID ;
var RS = DBConn.Execute(SQL);
// Page counter does not yet exist - create it.
if (RS.Eof)
{
var AccessCount=1;
var AccessSince = new Date();
SQL="INSERT into Counters ([PageID]) VALUES ("+PageID+")";
}
// Page counter exists, increment it.
else
{
var AccessCount=RS("Hits")+1;
var AccessSince=RS("Created").value;
SQL="UPDATE Counters SET [Hits]="+AccessCount+" WHERE [PageID]="+PageID;
}
RS = DBConn.Execute(SQL)
DBConn.Close();
msg = AccessCount + " visits since " + AccessSince;
}
return msg;
}
// ----- LOGGING IN AND OUT FUNCTIONS --------------------------------------------------------------------
// Returns true if user is logged in.
function isLoggedIn() {
return Session("UserID");
}
// Checks given name and password in users database.
// No validation on the user input is performed, so this function is
// susceptible to SQL injection attacks.
function logInUser(name,pwd) {
var DBConn = getDBConnection();
var SQL = "SELECT * FROM Users WHERE UserName = '" + name + "' and UserPwd = '" + pwd + "'";
var RS = DBConn.Execute(SQL);
var valid = !RS.Eof;
if (valid) {
Session("UserID") = RS("UserID").value;
Session("UserName") = RS("UserName").value;
Session("UserFullName") = RS("UserFirstName").value + ' ' + RS("UserLastName").value;
}
DBConn.Close;
return valid;
}
// Logs out current user.
function logOutUser() {
Session("UserID") = 0;
}
// Returns full name of currently logged in user if any.
function loggedInUser() {
var msg = '';
if (Session("UserID")) msg = Session("UserFullName");
return msg;
}
// Returns true if current user can edit content.
// Currently allows any authenticated user to edit content.
function inEditMode() {
return isLoggedIn();
}
%>
Use parameterized queries. It prevents the SQL injections.
Click here for more documentation
It will prevent the SQL string being hijacked by malicious input.
Good luck!
I am new to ExtJS. I came across following piece of code:
Ext.String.format('{1}',value+"#abc.com",value);
Now this will create a mailto link. But my query is that how Ext.String.format works and what else can I use it for?
Ext.String.format:
Allows you to define a tokenized string and pass an arbitrary number
of arguments to replace the tokens. Each token must be unique, and
must increment in the format {0}, {1}, etc.
You can look at the source of the function and see it uses the formatRe regex (/\{(\d+)\}/g):
format: function(format) {
var args = Ext.Array.toArray(arguments, 1);
return format.replace(formatRe, function(m, i) {
return args[i];
});
}
Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique, and must increment in the format {0}, {1}, etc.
The following Ext.String.format is modified to accept formatters functions (Ext.util.Format)
e.g.
alert(Ext.String.format("{0} {1:usMoney} {2:date('Y-m-d')}", 10, 20, new Date()));
Here is modified code
Code:
Ext.String._formatRe = /{(\d+)(?:\:([\w.])(?:((.?)?))?)?}/g;
Ext.String._argRe = /(['"])(.?)\1\s(?:,|$)/g
Ext.String.format = function(format) {
var args = Ext.Array.toArray(arguments, 1),
fm = Ext.util.Format;
return format.replace(Ext.String._formatRe, function(m, idx, fn, fmArgs) {
var replaceValue = args[parseInt(idx, 10)],
values,
match;
if (fn) {
values = [replaceValue];
while (match = Ext.String._argRe.exec(fmArgs)) {
values.push(match[2]);
}
return fm[fn].apply(fm, values);
}
return replaceValue;
});
};