Confounded by special CSS case - javascript

I was watching this video, it's a short demo for the Brackets IDE. I'm new to web development so I anticipate being confused by the code I see but there was something in there that I really don't get. Around the 8 minute mark the guy brings up the css line .galleryItem:nth-child(4n+1) Saying that it will only affect the first item in each row in a grid because of the :nth-child(4n+1) can some one please explain the syntax of this line and how it can be used.
P.S. For you Bret Victor fans out there, Brackets seems to do some of his stuff.

The idea here is simply that there are probably four items in each row, so using 4n+1 will affect the first item in each row because it is targeting 1st, 5th, 9th, etc. overall.
I think the 4n part can be thought of as a modulo division matcher (matches everywhere that mod 4 = 0) and the +1 simply shifts that 1 to the right. Thus it includes all the multiples of 4, each with 1 added. And since 0 is technically a multiple of 4, the 1st item is included in this list as well.

Related

Can you force a string to split into 'n' lines?

On a website I'm designing, I have a page with rows of categories thumbnails and their titles.
The problem is : some category titles are long, other are shorts... depending on the monitor width some will take 2 lines of text, or even 3, but not the others, creating ugly staircases.
I've managed to identify the highest title and min-height every other one accordingly with javascript.
But, it's still ugly. To make it better, I'd want every title to break into as many lines than the longest one.
That's where I come short... I couldn't find a way to do that so far.
Here's how it is now :
Here's the intended result :
Any idea how I could accomplish this ?
If you want to do that with a javascript solution you can count characters or words and add <br> after n amount. Here is a sample that will add a line break after every 20 characters:
var string = document.getElementById('text');
string.innerHTML = string.textContent.replace(/(.{20})/g, "$1<be>");
Then you can create a function with a loop for each element and do some if statement logic there. For example - add a break if the character count is more than...

Auto-increment dates in two cells if date has passed

Overview:
I'm not a programmer but I managed to get some serious coding into a Gsheets to track my teams project, so we have multiple-variable dropdown menus and integration with google calendar to track projects development and all that.
Why I'm at stackoverflow:
I kind of lack the knowledge to start the code from the scratch, I usually find spare parts of code through forums on the internet and clue them together and it usually works surprisingly well, but this time I couldn't find much informtation.
What I need:
I have 5 cells, and we can put as below,
Date start - Date end - date code* - number** - Priority***
*script to add the date range to gcalendar
** & *** The number is an array that's based on the word written on the priority cell, for example: If priority is written Weekly them
the number colunm will show 7 on the cell to the left and them it
goes. (monthly = 30 and blablabla...)
So I'd like to know if someone could give a hand with a script that would work (at least in my head) as following:
If I set the priority to weekly, it will show 7 on the number colunm and them, every time the "Date end" has passed, it will automatically add 7 days to the "Date start" and "Date end" again.
That way I could keep the projects on a loop where I'll be able to track them constatly.
Thanks in advance for any insights provided,
ps: I've seen some posts about this on sql, but I have no idea also on how to take advantage of the proposals that were presented there.
Edit:
Spreadsheet picture
eDIT2:
Spreadsheet with a increment colunm
Pertinent to the data set and description, you probably do not need any VBA as the increment could be achieved by adding +1 to the reference pointing to previous cell. For example, assuming cell A1 is formatted as Date, enter in cell B1: =A1+1 , then in cell C1: =B1+1 and so on. The result should be as shown below
A B C
9/1/2017 9/2/2017 9/3/2017
It could be further extended with simple logic allowing do display incremented value only if the previous cell is not empty, like : =IF(A1,A1+1,"")
In your case, it could be cell F1 containing =IF(E1,E1+1,"").
FYI, the underlying value of Date is just an Integer value (Time is represented as decimal part), so the arithmetic operations could be applied.
More generic solution would be based on the Excel DATE() Worksheet formula as shown in sample shown below (adding 1 mo. to the date entered in cell A1):
=DATE(YEAR(A1), MONTH(A1)+1, DAY(A1))
In order to implement additional logic, you may consider using Excel Worksheet IF() statement like for example, cell B1 containing:
=A1+IF(C1="week",7,1)
A B C
9/1/2017 9/8/2017 week
so based on the IF() condition it will add either 7 days if C1 contains the word "week" or 1 day otherwise. It could be further extended with nested IF().
Hope this will help.

Map markers become inaccurate when past accumulation of 10 properties

I forked an interesting map application with sidebar information for a different purpose.
However, I noticed today that every time I go past 10 parklets from this repository:
http://mick.github.io/jekyllmap/ or (https://github.com/mick/jekyllmap), it starts getting slightly wonky.
I've poked around in mapping.js from assets/js to see where the problem may be coming from.
I can't figure out where it is coming from.
The markers in my application, when past 10 parklets, the markers get stuck, don't change color, or point to the wrong info.
Any advice on how to get this to work for about 26 properties?
Thanks!
ps.to make it clear, the links above are not my github accounts. figured it would be simpler to link to the original account from which i forked from.
mapping.js line 7
var point = parseInt($(this).attr('data-target').substr(1));
or
var point = parseInt($(this).attr('data-target').substring(1));
and not
var point = parseInt($(this).attr('data-target').substr(1,1));
Edit:
Sorry no need to use substring instead of substr. Just delete second parameter.
As said in substr doc : str.substr(start[, length])
If you set the second parameter .substr(1,1)
The string return is from character 1 (the second in the string as the index starts at 0) for a length of 1.
For #1 and #10 or #11 .substr(1,1) returns 1.
If you don't pass the second parameter .substr(1) you get the original string from character string[0] to the end of the string.
For #1 .substr(1) returns 1.
For #100 .substr(1) returns 100.
For #19298298928 .substr(1) returns 19298298928.
And if you're curious difference between substr and substring is here

Search string for numbers

I have a javascript chat bot where a person can type into an input box any question they like and hope to get an accurate answer. I can do this but I know I'm going about this all wrong because I don't know what position the number will appear in the sentence. If a person types in exactly:
what's the square root of 5 this works fine.
If he types in things like this it doesn't.
what is the square root of the 5
the square root of 5 is what
do you know what the square root of 5 is
etc
I need to be able to determine where the number appears in the sentence then do the calculation from there. Note the line below is part of a bigger working chatbot. In the line below I'm just trying to be able to answer any square root question regardless of where the number appears in the sentence. I also know there are many pitfalls with an open ended input box where a person can type anything such as spelling errors etc. This is just for entertainment not a serious scientific project. :)
if(
(word[0]=="what's") &&
(word[1]=="the") &&
(word[2]=="square") &&
(word[3]=="root") &&
(word [4]=="of") &&
(input.search(/\d{1,10}/)!=-1) &&
(num_of_words==6)
){
var root= word[5];
if(root<0){
document.result.result.value = "The square root of a negative number is not possible.";
}else{
word[5] = Math.sqrt(root);
word[5] = Math.round(word[5]*100)/100
document.result.result.value = "The square root of "+ root +" is "+ word[5] +".";
}
return true;
}
Just to be clear the bot is written using "If statemments" for a reason. If the input in this case doesn't include the words "what" and "square root" and "some number" the line doesn't trigger and is answered further down by the bot with a generic "I don't know type of response". So I'm hoping any answer will fit the format I am using. Be kind, I'm new here. I like making bots but I'm not much of a programmer. Thanks.
You can do this using a regular expression.
"What is the sqrt of 5?".match(/\d+/g);
["5"]
The output is an array containing all of the numbers found in the string. If you have more than one, like "Is the square root of 100 10?" then it will be
"Is the square root of 100 10?".match(/\d+/g);
["100", "10"]
so you can pick what number you want to use in your script.
You will need to use regular expressions, if you do not know what they are you should look them up as it would take too long to explain them in this response. Here is a useful website for regular expressions in JavaScript https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions.
Assuming that you know regular expressions you should first search for numbers and store all the numbers that you find, if no numbers are found print out an error message. As an added note, you may what to consider searching for mathematical constants such as pi or e. This should work
nums = someString./\d+|pi|e/gi
The next part is going to be hard but to boil it down to is core concept, you need to look for key words such as 'square root', 'times', or 'plus'. You should do this word by word going left to right. For example if a user inputs
What is 5 plus 3 minus 8?
you should detect the plus before the minus, while if this is inputted
What is 5 minus 3 plus 8?
You should detect the minus before the plus.
For operations that uses two numbers you need to take the first two numbers that you found and do the operation and replace the two numbers with the result. I am trying to use reverse polish notation if you do not quite understand what I am trying to do, look it up if do not know what it is.
I hope I understood your question correctly and provided some help to coming to a solution because what you asked is very hard but seems like fun. Good luck. Also as a warning I am not considering order of operations in my response.

Javascript percentage validation

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.
Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?
#Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.
Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.
var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
// value is out of range
}
I propose this one:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
It matches 100, 100.0 and 100.00 using this part
^100(\.0{1,2})?$
and numbers like 0, 15, 99, 3.1, 21.67 using
^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$
Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
This reminds me of an old blog Entry By Alex Papadimoulis (of The Daily WTF fame) where he tells the following story:
"A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?"
How would you answer the question?
It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.
There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.
This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.
The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.
The solution given by Greg Hewgill is probably better - even though it would validate "99fxx" as "99". But given the circumstances that might actually be ok.
Given that your value is in str
str.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/)
^100(\.(0){0,2})?$|^([1-9]?[0-9])(\.(\d{0,2}))?\%$
This would match:
100.00
optional "1-9" followed by a digit (this makes the int part), optionally followed by a dot and two digits
From what I see, Greg Hewgill's example doesn't really work that well because parseFloat('15x') would simply return 15 which would match the 0<x<100 condition. Using parseFloat is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.
I recomend this, if you are not exclusively developing for english speaking users:
[0-9]{1,2}((,|\.)[0-9]{1,10})?%?
You can simply replace the 10 by a 2 to get two decimal places.
My example will match:
15.5
5.4366%
1,43
50,55%
34
45%
Of cause the output of this one is harder to cast, but something like this will do (Java Code):
private static Double getMyVal(String myVal) {
if (myVal.contains("%")) {
myVal = myVal.replace("%", "");
}
if (myVal.contains(",")) {
myVal = myVal.replace(',', '.');
}
return Double.valueOf(myVal);
}
None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'
This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.
/(^$)|(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)\.(\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/
(100|[0-9]{1,2})(\.[0-9]{1,2})?
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.
#mlarsen:
Is not that a regex here won't do the job better.
Remember that validation msut be done both on client and on server side, so something like:
100|(([1-9][0-9])|[0-9])(\.(([0-9][1-9])|[1-9]))?
would be a cross-language check, just beware of checking the input length with the output match length.
(100(\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\.[0-9]{1,2})?)

Categories

Resources